Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

contentEditable does not wrap first line in tags

I have a div with the attribute contentEditable set.

The trouble I am having is that the first line I type does not get wrapped in tags, but the subsequent lines do.

So typing:

qwerty
zxcv
asdfg

Results in:

<div class="editable" contentEditable="true">
    qwerty
    <div>zxcv</div>
    <div>asdfg</div>
</div>

So I need the qwerty line to become <div>qwerty</div>

like image 675
Tom Avatar asked Sep 25 '12 22:09

Tom


4 Answers

I had issues in Chrome just adding a div. It only worked if your div contains a br tag:

<div class="editable" contentEditable="true">
  <div>
    <br>
  </div>
</div>

@nicholas_r is right, deleting the last character in the editable div will also delete the div added at the beginning. You can avoid this, by catching the last 'backspace'. A simple solution using jquery to do it:

$(".editable").on('keydown', function(event) {
  if (event.keyCode === 8 && $(this).html() == '<div><br></div>') {
    event.preventDefault();
  }
}
like image 138
Christian Sommerauer Avatar answered Sep 25 '22 23:09

Christian Sommerauer


If it helps, running the following will let you wrap unwrapped divs . If you trigger it on keypress or something like that, it'll work even if the user removes all content from the div.

 $(".editable").contents().filter(function() {
    return this.nodeType == 3;
 }).wrap('<div></div>');
like image 34
Pirijan Avatar answered Sep 26 '22 23:09

Pirijan


If you start with an element that contains a div inside it like this:

<div class="editable" contentEditable="true"> <div></div> </div>

the first line you type will end up being wraped in a div.

UPDATE:

This is browser specific. While it did work in most browsers at the time the question was posted, it does not necessarily work anymore in the latest browser version. Best way to tell is to just test it.

like image 31
dcro Avatar answered Sep 22 '22 23:09

dcro


I did something like this and it works really well for making sure there's always a div wrapper on the first line of text.

This way if the user clicks into the field and its blank (initial state) it'll put a blank space in, to make sure that their cursor is inside of the new div.

$editable.on('focus', function() {
  if ($(this).text().trim() === '') {
    console.log('editable is blank, insert a div');
    $(this).append($('<div>&nbsp;</div>'));  
  }
});

You can remove the leading space (if it matters) before saving the data.

like image 23
Austin Wang Avatar answered Sep 26 '22 23:09

Austin Wang