Skitterm
Skitterm

Reputation: 4575

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});
    element.trigger(evt);
});

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.

Upvotes: 1

Views: 2357

Answers (3)

Mohamed Elgharabawy
Mohamed Elgharabawy

Reputation: 366

In jQuery. You can clone the current element. Add the clone after the original element and then remove it.

Here is an example:

// target is the editable div and clone is its copy
var target = $(".editableContent");
var clone = target.clone();
target.after(clone).remove();

Upvotes: 0

Skitterm
Skitterm

Reputation: 4575

As @firefoxuser_1 mentioned, the thing to do is to re-set the inner html. However, I found that I had to empty out the inner html, wait a dash, and then re-apply it. Example:

var value = myElement.innerHTML;
myElement.innerHTML = '';
setTimeout(function() {
    myElement.innerHTML = value;
}, 1);

Upvotes: 0

firefoxuser_1
firefoxuser_1

Reputation: 1839

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.

Upvotes: 2

Related Questions