I need to move caret to end of contenteditable
node like on Gmail notes widget.
I read threads on StackOverflow, but those solutions are based on using inputs and they doesn't work with contenteditable
elements.
I need to move caret to end of contenteditable
node like on Gmail notes widget.
I read threads on StackOverflow, but those solutions are based on using inputs and they doesn't work with contenteditable
elements.
It's possible to do set cursor to the end through the range:
Geowa4's solution will work for a textarea, but not for a contenteditable element.
This solution is for moving the caret to the end of a contenteditable element. It should work in all browsers which support contenteditable.
It can be used by code similar to:
There is also another problem.
The Nico Burns's solution works if the
contenteditable
div doesn't contain other multilined elements.For instance, if a div contains other divs, and these other divs contain other stuff inside, could occur some problems.
In order to solve them, I've arranged the following solution, that is an improvement of the Nico's one:
Usage:
In this way, the cursor is surely positioned at the end of the last element, eventually nested.
EDIT #1: In order to be more generic, the while statement should consider also all the other tags which cannot contain text. These elements are named void elements, and in this question there are some methods on how to test if an element is void. So, assuming that exists a function called
canContainText
that returnstrue
if the argument is not a void element, the following line of code:should be replaced with:
EDIT #2: The above code is fully updated, with every changes described and discussed
I had a similar problem trying to make a element editable. It was possible in Chrome and FireFox but in FireFox the caret either went to the beginning of the input or it went one space after the end of the input. Very confusing to the end-user I think, trying to edit the content.
I found no solution trying several things. Only thing that worked for me was to "go around the problem" by putting a plain old text-input INSIDE my . Now it works. Seems like "content-editable" is still bleeding edge tech, which may or may not work as you would like it to work, depending on the context.