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("nu200b");
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?
2
Answers
Use < BR /> instead of n
ive looked into your problem a bit
i use chrome mainly, it all works
except when the cursor is at the end of the string, then the newline is inserted at the end but the browser doesnt seem to pick it up in the ui, seems to be a browser bug, ive tried it with various elements and all are the same
ive just noticed, if you delete a character it starts working, try playing around with it
if you chose to use a
textarea
, then it does work and you can just usenow i come to think about it, browsers have always been a bit funny about white space at the end of contents, even with white-space set to
pre
, they just love to collapse whitespaceits fine to use newlines in any element in html, theyre a fundamental part of the html specification, a span is just an inline element
you use a span and then set its display to be block, which effectively renders it as a div as far as i can tell
i’ll post this for now so i dont lose my edits, i do have some more to suggest on the subject …