When you hit Enter on a contentEditable
element every browser is handling the resulting code differently: Firefox inserts a BR tag, Chrome inserts a DIV tag while Internet Explorer inserts a P tag.
I was desperately looking for a solution to at least use a BR or P for all browsers and the most common answer was this:
inserting BR tag :
$("#editableElement").on("keypress", function(e){
if (e.which == 13) {
if (window.getSelection) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
br = document.createElement("br");
range.deleteContents();
range.insertNode(br);
range.setStartAfter(br);
range.setEndAfter(br);
selection.removeAllRanges();
selection.addRange(range);
return false;
}
}
});
But this doesn't work because it seems that browsers don't know how to set the caret after <br>
which means the following is not doing anything useful (especially if you hit enter when the caret is placed at the end of text):
range.setStartAfter(br);
range.setEndAfter(br);
Some people would say: use double <br><br>
but this results in two line breaks when you hit enter inside a text node.
Others would say always add an additional <br>
at the end of contentEditable, but if you have a <div contenteditable><p>text here</p></div>
and you place the cursor at the end of text then hit enter, you will get the wrong behavior.
So I said to myself maybe we can use P instead of BR, and the common answer is:
inserting P tag:
document.execCommand('formatBlock', false, 'p');
But this doesn't work consistently either.
As you can see, all these solutions leave something to be desired. Is there another solution that solves this issue?