Skitterm Skitterm - 6 months ago 42
Javascript Question

ContentEditable element -- cursor back to beginning of editable text

I have a contentEditable header. It only allows for one line and doesn't show overflow, so it stays in a specified space on the page, as such:

<h2 id="element" contentEditable="true"></h2>

#element {
white-space: nowrap;
overflow: hidden;

The user can then edit the text and make it as long as they want. Regardless of how much text the user has entered, I want the cursor to go back to the beginning of the text when they focus out of the header. (This way, if they enter a bunch of text, they will always see the first part of it when they're not editing it).

I've tried the following ("home" key keycode is 36), but I can't get the cursor to move back to the beginning of the element.

var element = $('#element');

element.on('focusout', function() {
var evt = $.Event('keydown', {keyCode: 36});

Any ideas on getting the cursor back to the beginning of the element when I click out of it?

jQuery or vanilla are both fine.


A working (if not particularly good) solution to this is to just reset the html of the element when it is unfocused by using element.innerHTML = element.innerHTML;. Most browsers move the cursor back to the beginning when you do this. However, this is not a good idea if you have a lot of complicated markup in the element, as this causes everything to be repainted.