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.