Question

I'm using jHtmlArea, but I guess the question is relevant to any html textbox using iframe/document edit mode to function.

Having used the pasteHTML function to set some text into the jHtmlArea, I'd like to place the cursor after the text that I've inserted, is there a nice way to do this?

Was it helpful?

Solution

I would suggest replacing jHtmlArea's pasteHTML implementation with a competent one that uses no browser sniffing, behaves consistently between browsers and places the caret after the inserted content for you. Something like the following, which is adapted from my answer here: Insert html at caret in a contenteditable div

jHtmlArea.prototype.pasteHTML = function(html) {
    var sel, range, iframe = this.iframe[0],
        win = iframe.contentWindow || iframe.contentDocument.defaultView,
        doc = win.document;

    win.focus();
    if (win.getSelection) {
        // IE9 and non-IE
        sel = win.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // not supported in all browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = doc.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        // IE < 9
        sel.createRange().pasteHTML(html);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top