Move cursor to placeholder element in a contentEditable DIV

2k views Asked by At

I have a contentEditable DIV and, when the user presses a key, the underlying code is processed and replaced by updated code. Alas, this causes the cursor position to be lost.

However, in order to preserve the cursor position, I am successfully inserting a <span id="placeholder"></span> into the DIV at the correct position before processing begins. This preserves the cursor's intended position, but now I can't seem to set the range to select it.

Here's what I currently have:

function focusOnPlaceholder() {

    var placeholder = document.getElementById('placeholder');

    if( !placeholder ) return;

    var sel, range;

    if (window.getSelection && document.createRange) {                    
        range = document.createRange();
        range.selectNodeContents(placeholder);
        range.collapse(true);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(placeholder);
        range.select();
    }

}

Any help would be appreciated, and a cross-browser solution would be incredible :)

1

There are 1 answers

1
Tim Down On BEST ANSWER

A cross-browser solution would be to use my Rangy library and specifically the selection save/restore module, which uses a similar placeholder technique and is well tested. However, this can probably be fixed without using a library by putting some content (for example, a non-breaking space (\u00A0 or &nbsp; in HTML) inside your placeholder element. You may want to remove the placeholder in focusOnPlaceholder() after selecting the range.