Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert newline on enter key in contenteditable div

I am trying to insert a newline character instead of whatever the browser wants to insert when I press enter in a contenteditable div.

My current code looks something like this:

if (e.which === 13) {
        e.stopPropagation();
        e.preventDefault();

        var selection = window.getSelection(),
            range = selection.getRangeAt(0),
            newline = document.createTextNode('\n');

        range.deleteContents();
        range.insertNode(newline);
        range.setStartAfter(newline);
        range.setEndAfter(newline);
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
    }

This seems to work in Chrome, Firefox and Safari but fails in internet explorer.

My requirement is that it works in the most recent versions of Chrome/FF and similar (a couple versions back wouldn't be a bad idea) and in IE10+.

I have tried a lot of different things but just can't seem to get it to work.

Any help is much appreciated!

Edit: For clarification, the error for me in IE is that the caret does not move when the newline is inserted, but rather the newline seems to be added after the caret which is odd behavior. But if I press enter one, then move down to that line with the arrow keys, and start pressing enter again, it works as intended. Can't tell what I'm doing wrong here.

like image 357
Firas Dib Avatar asked May 31 '14 21:05

Firas Dib


2 Answers

Try this:

document.execCommand('insertHTML', false, '<br><br>');

Even undo\redo work :)

like image 81
JBeen Avatar answered Nov 15 '22 00:11

JBeen


this works in IE 11 and chrome for me

if(getSelection().modify) {     /* chrome */
  var selection = window.getSelection(),
    range = selection.getRangeAt(0),
    br = document.createTextNode('\n');
  range.deleteContents();
  range.insertNode(br);
  range.setStartAfter(br);
  range.setEndAfter(br);
  range.collapse(false);
  selection.removeAllRanges();
  selection.addRange(range);       /* end chrome */
} else {
  document.createTextNode('\n');    /* internet explorer */
  var range = getSelection().getRangeAt(0);
  range.surroundContents(newline);
  range.selectNode(newline.nextSibling);   /* end Internet Explorer 11 */
}

sorry for how unorganized it is. I used getSelection().modify to determine if it was ie or not because IE doesn't have modify for some reason.

like image 39
darbicus Avatar answered Nov 15 '22 01:11

darbicus