I would like to insert a new line in a contenteditable when the user press Ctrl+Enter.
Based on the following questions, I wrote the code below:
- Insert newline on enter key in contenteditable div
- How to insert a <CR> (Carriage Return) in a Javascript String?
- Dealing with line Breaks on contentEditable DIV
- Problem detecting Newlines in JavaScript Range Object
Here is my HTML:
<span id="myInput" contenteditable="true" style="white-space: pre;"></span>
Here is the JavaScript:
let myInput = document.getElementById('myInput');
myInput.addEventListener('keypress', (event) => {
if (event.key == 'Enter' && event.ctrlKey == true) {
event.preventDefault();
this.insertNewLine();
}
})
function insertNewLine(text) {
var sel, range, html;
sel = window.getSelection();
range = sel.getRangeAt(0);
range.deleteContents();
// Do not always works
var textNode = document.createTextNode("\n");
// Always works
//var textNode = document.createTextNode("\n\u200b");
range.insertNode(textNode);
range.setStartAfter(textNode);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}
When the user press Ctrl+Enter, the behavior is a bit weird:
- On Chrome, the new line is not always inserted
- On Firefox, the new line is inserted, but the caret does not jump to the next line
I noticed that the above code always works when an zero-width space (\u200b) is added after the \n character.
I made a JSFidle: https://jsfiddle.net/Alphonsio/atr7e2uw/27/
Of course, I'd prefer not to insert the second character. But I can't figure out why the new line is not inserted in the first case (\n only). Can anyone help?
Use < BR /> instead of \n