Baz
Baz

Reputation: 13125

Reposition cursor for a contenteditable div

I am using a div to implement a text box, as follows:

<div id="text" contenteditable="true">

I then add some background coloring to each of the words using span. And I do this using the following event.

document.getElementById("text").addEventListener('keyup', function () {
    ...
    this.innerHTML = output;
}

However, the cursor is set to the start of the text area each time this event is triggered. How do I set the cursor back to where it was after the user had entered a new letter?

UPDATE:

Please note that I am only changing color and the raw text itself doesn't change so the cursor position should be in the same position as it was in if I hadn't added the keyup event.

Upvotes: 2

Views: 63

Answers (1)

closure
closure

Reputation: 7452

Please call this function with the div element.

        function placeCaretAtEnd(el) {
          el.focus();
          if (typeof window.getSelection != "undefined"
                  && typeof document.createRange != "undefined") {
            var range = document.createRange();
            range.selectNodeContents(el);
            range.collapse(false);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
          } else if (typeof document.body.createTextRange != "undefined") {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(false);
            textRange.select();
          }
        } 

Upvotes: 2

Related Questions