Tuesday, 16 June 2015

Set focus at contenteditable end text

contenteditable="true" means it is not any input type. it is just a div. but when you click on that div it will acts as text field. so, in this how can we set the focus at end of text? it is not possible with .focus(). by using the following code it is possible.


HTML:
<div contenteditable="true" id="chk">vamsi</div>

SCRIPT:

$(document).ready(function(){
    $('#chk').click(function(){
        placeCaretAtEnd( document.getElementById("chk") );
    });
});

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}