Set textarea's caret position using x and y position

html, javascript, textarea

Solution

Looks like you could do something like this:

createTextArea = function (e) {
    var range = window.getSelection().getRangeAt(0),
        start = range.startOffset,
        target = e.target,
        setPoint;
    while (target.tagName.toLowerCase() !== 'div') {
        target = target.parentElement;
        if (!target) return;
    }
    range.setStart(target, 0);
    setPoint = range.toString().length;
    // place and show #editor
    editor.focus();
    editor.setSelectionRange(setPoint, setPoint);
    return;
};

An example at jsFiddle. Notice that this works only in modern browsers. Older IE's don't have Input API, and the Selection/Range model is totally different.

Problem

I want to implement inline edition, so if user clicks on a div with some text, the textarea will appear at the same position as clicked div's position and will get the text from the div. This is fine for me, but what I want to do next is to set textarea's caret position according to x and y position from div click event. Any ideas? HTML: ``` <div id="content" style="display: block; z-index: 10">Some text</div> <textarea id="editor" style="position: absolute; display: none; z-index: 11"></textarea> ``` JS: ``` $('#content').click(function(e) { var content = $(this); var editor = $('#editor'); var position = content.offset(); editor.css('left', position.left); editor.css('top', position.top); editor.val(content.text()); editor.show(); var mousePosition = { x: e.offsetX, y: e.offsetY }; // here I want to set the #editor caret position at the same place, // where user clicks the #content (mousePosition variable) }); ```

Original source