JavaScript: Scroll to selection after using textarea.setSelectionRange in Chrome JavaScript: Scroll to selection after using textarea.setSelectionRange in Chrome google-chrome google-chrome

JavaScript: Scroll to selection after using textarea.setSelectionRange in Chrome


Here is a simple and efficient solution, pure js :

//first of all, you ignore any bad english, as i'm french and had a funny evening//get the textareavar textArea = document.getElementById('myTextArea');//define your selectionvar selectionStart = 50;var selectionEnd = 60;textArea.setSelectionRange( selectionStart, selectionEnd);// now lets do some math// we need the number of chars in a rowvar charsPerRow = textArea.cols;// we need to know at which row our selection startsvar selectionRow = (selectionStart - (selectionStart % charsPerRow)) / charsPerRow;// we need to scroll to this row but scrolls are in pixels,// so we need to know a row's height, in pixelsvar lineHeight = textArea.clientHeight / textArea.rows;// scroll !!textArea.scrollTop = lineHeight * selectionRow;

Put this in a function, extend the prototype of javascript's Element object with it, and you're good.

Feel free to ask if you need any further help.


A lot of answers, but the accepted one doesn't consider line breaks, Matthew Flaschen didn't add the solution code, and naXa answer has a mistake. The simplest solution code is:

textArea.focus();const fullText = textArea.value;textArea.value = fullText.substring(0, selectionEnd);textArea.scrollTop = textArea.scrollHeight;textArea.value = fullText;textArea.setSelectionRange(selectionStart, selectionEnd);


You can see how we solved the problem in ProveIt (see highlightLengthAtIndex). Basically, the trick is to truncate the textarea, scroll to the end, then restore the second part of the text. We also used the textSelection plugin for consistent cross-browser behavior.