Search code examples
javascriptcursorcontenteditable

get and set cursor position in content editable div


in a content editable div, i wish get and set cursor position but but without taking into account the child elements (, , etc for example).

for get, i find this solution : Get a range's start and end offset's relative to its parent container

but for set, i don't know.

please, can u help me.

thank u


Solution

  • You can use rangy to define it yourself, just like this:

    var selector = document.querySelector('[contenteditable]');
    
    var setCaretIndex = function (index) {
        var charIndex = 0, stop = {};
    
        var traverseNodes = function (node) {
            if (node.nodeType === 3) {
                var nextCharIndex = charIndex + node.length;
                if (index >= charIndex && index <= nextCharIndex) {
                    rangy.getSelection().collapse(node, index - charIndex);
                    throw stop;
                }
                charIndex = nextCharIndex;
            }
    
            // Count an empty element as a single character. The list below may not be exhaustive.
            else if (node.nodeType === 1 && /^(input|br|img|col|area|link|meta|link|param|base)$/i.test(node.nodeName)) {
                charIndex += 1;
            } else {
                var child = node.firstChild;
                while (child) {
                    traverseNodes(child);
                    child = child.nextSibling;
                }
            }
        };
    
        try {
            traverseNodes(selector);
        } catch (ex) {
            if (ex !== stop) throw ex;
        }
    };
    

    To use this function, you need to focus the editor first:

    selector.focus();
    

    Then giving an index to set cursor position:

    setCaretIndex(3);
    

    Fiddle