Skip to content Skip to sidebar Skip to footer

Keeping Caret Position In A Visible Position In Text Input - Firefox Misbehaves

I'm toying with the idea for my text input box of clicking on a div containing a selection of 'tags' to add meta content. My text input has a width of 35, but I want it to be able

Solution 1:

See my answer this question. Although it is relatively kludgy, you can trigger an keypress event in FF and the input will scroll to the end (showing the caret where you'd like to see it).


Solution 2:

Thanks, that works for me jtompson. Combined it with an existing script to move the caret to the end of a textinput or textarea seems to cover IE7, FF3, and chrome.

    function setCaretPosition(elemId, caretPos) {
        var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.setSelectionRange(caretPos, caretPos);
                elem.focus();
                // Workaround for FF overflow no scroll problem
                // Trigger a "space" keypress.
                var evt = document.createEvent("KeyboardEvent");
                evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 0, 32);
                elem.dispatchEvent(evt);
                // Trigger a "backspace" keypress.
                evt = document.createEvent("KeyboardEvent");
                evt.initKeyEvent("keypress", true, true, null, false, false, false, false, 8, 0);
                elem.dispatchEvent(evt);
            }
            else
                elem.focus();
        }
    }
}
 setCaretPosition(document.getElementById("searchinput").id, document.getElementById("searchinput").value.length);

Post a Comment for "Keeping Caret Position In A Visible Position In Text Input - Firefox Misbehaves"