How to change behavior of contenteditable blocks after on enter pressed in various browsers
Solution 1:
As Douglas said earlier, browsers try to clone previous tag when customer starts a new paragraph on an editable page. The discrepancy occurs when browser has nothing to depart from - e.g. when initially the page body is empty. In this case different browsers behave differently: IE starts to wrap every string into <p> tag, Chrome wraps each line in <div>.
To increase cross-browser experience, WebKit developers have introduced the DefaultParagraphSeparator command. You can use the following JavaScript on page loading for Chrome to change default paragraph separator to <p> tag:
document.execCommand('defaultParagraphSeparator', false, 'p');
Solution 2:
The following will add a <br>
when the enter key is pressed in all major browsers and attempts to place the caret directly after it. However, WebKit, Opera and IE all have issues with placing the caret correctly after the <br>
, which the following code does not attempt to correct.
function enterKeyPressHandler(evt) {
var sel, range, br, addedBr = false;
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
if (charCode == 13) {
if (typeof window.getSelection != "undefined") {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
br = document.createElement("br");
range.insertNode(br);
range.setEndAfter(br);
range.setStartAfter(br);
sel.removeAllRanges();
sel.addRange(range);
addedBr = true;
}
} else if (typeof document.selection != "undefined") {
sel = document.selection;
if (sel.createRange) {
range = sel.createRange();
range.pasteHTML("<br>");
range.select();
addedBr = true;
}
}
// If successful, prevent the browser's default handling of the keypress
if (addedBr) {
if (typeof evt.preventDefault != "undefined") {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
}
}
var el = document.getElementById("your_editable_element");
if (typeof el.addEventListener != "undefined") {
el.addEventListener("keypress", enterKeyPressHandler, false);
} else if (typeof el.attachEvent != "undefined") {
el.attachEvent("onkeypress", enterKeyPressHandler);
}