Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a ContentEditable div read-only?

So I want the features of a contenteditable div (text selection via keyboard being the main one), but I don't want to allow the user to edit the text - I presumed a readonly="readonly" would work, but sadly it doesn't.

Do we know if there's a way to do it? The contenteditable div may have nested tags inside (<p>'s, <h1>'s).

I want to avoid a textarea (that's what this is for), as it doesn't allow me to do other things I need to be able to do.

Is there a nice way to do this without javascript? And if there isn't, is there a small snippet of javascript that will still allow copying, highlighting etc?

Thanks.

Here's an example: http://codepen.io/anon/pen/dxeAE

like image 873
Matthew Evans Avatar asked Oct 14 '14 12:10

Matthew Evans


Video Answer


2 Answers

I made a jquery solution/workaround. What is does is prevent the default action when a key is pressed:

$(document).ready(function(){
  $("#editor").on("keypress", function(e) {
      e.preventDefault();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="editor" contenteditable="">
   <h1>Heading</h1>
   <p>Test</p>
</div>
like image 102
Andreas Furster Avatar answered Oct 17 '22 12:10

Andreas Furster


You could also try this, plain javascript solution

document.getElementById('div').onkeydown = function (e) {
    var event = window.event ? window.event : e;
    return !(!~[37, 38, 39, 40].indexOf(e.keyCode) && !e.ctrlKey);
}

This allows selection using arrow keys and copying the same.

like image 32
Salman Avatar answered Oct 17 '22 12:10

Salman