Skip to content Skip to sidebar Skip to footer

How To Place Cursor At The End Of Text After Replacing Html With Jquery?

I have a contenteditable div and trying to replace tag with tag but after replacing the html using jQuery replaceWith() function cursor defaults to the be

Solution 1:

You can use this function

functionplaceCaretAtEnd(el) {
    el.focus();
    if (typeofwindow.getSelection != "undefined"
            && typeofdocument.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } elseif (typeofdocument.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

call it as follows

placeCaretAtEnd( document.getElementById("content") );

EXAMPLE

Solution 2:

If you create the <span> element by hand using document.createElement() and keep a reference to it, you can easily place the caret immediately after it.

Demo: http://jsfiddle.net/Gaqfs/10/

Code:

functionplaceCaretAfter(el) {
    el.focus();
    if (typeofwindow.getSelection != "undefined"
            && typeofdocument.createRange != "undefined") {
        var range = document.createRange();
        range.setStartAfter(el);
        range.collapse(true);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } elseif (typeofdocument.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

$('#test').focus();
$('#replace').on({
    mousedown: function (event) {
        event.preventDefault();
    },
    click: function () {
        var span = document.createElement("span");
        span.style.color = "red";
        span.innerHTML = "New Text";
        $('#test').find('font').replaceWith(span);
        placeCaretAfter(span);
    }
});

Post a Comment for "How To Place Cursor At The End Of Text After Replacing Html With Jquery?"