Maintain cursor position after changing an input value programatically

Sometimes you want to programatically change an input value, like in a case of input validation.
replacing an input value is easy, but has a common drawback – the cursor position will reset.

to overcome it, we can use this simple JS snippet:


function handleInputValueChange(e) {

    var cursorStart = e.target.selectionStart,
        cursorEnd = e.target.selectionEnd;

        // value manipulations...

    e.target.setSelectionRange(cursorStart, cursorEnd);
}

* note that this specific snippet relies on passing an event, onChange for instance.

Leave a Reply

Your email address will not be published. Required fields are marked *