I have a contentEditable div
that can contain several span
and br
tags.
Desired functionality: when the user presses return
, a new line is added and the caret is correctly placed in the new line, like in this first screenshot:
The issue I'm facing: if the last tag is not a br
(look at the very last br tag in the first screenshot), when the user presses return
to add a new line the cursor is for some reason misplaced (somewhere between the first line and the second line, see second screenshot). After hitting return
again and deleting the previous new line or by starting to type in, the caret eventually is correctly placed. Currently the last br
tag is lost only if the user selects all text (ctrl + a
) and deletes all contents.
To avoid having problems I'd just append a br tag at the end of my div (unless there is already one). Otherwise I'm happy to try out any other solution. How can I fix this behave?
Things I've tried:
var brTag = document.createElement("br");
if (textBox.lastChild != brTag) {
$(textBox).append("<br />");
}
and...
if (textBox.lastChild != "<br></br>") {
$(textBox).append("<br />");
}
Neither worked!
First attempt does not work because "<br></br>"
is the string representation of the last child, but it's actually a complex object which not equates to a string.
Second attempt does not work because you are comparing to a newly created element, which is not equal to any other element.
What you want is to compare tagName
property of yout lastChild
.
Try that:
if (textBox.lastChild.tagName != 'BR') {
$(textBox).append("<br />");
}