Skip to content
Advertisement

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

A JavaScript function selects a certain word in a textarea using .setSelectionRange().

In Firefox, the textarea automatically scrolls down to show the selected text. In Chrome (v14), it does not. Is there a way to get Chrome to scroll the textarea down to the newly selected text?

jQuery solutions are welcome.

Advertisement

Answer

Here is a simple and efficient solution in pure JavaScript:

// Get the textarea
var textArea = document.getElementById('myTextArea');

// Define your selection
var selectionStart = 50;
var selectionEnd = 60;
textArea.setSelectionRange(selectionStart, selectionEnd);

// Mow let’s do some math.
// We need the number of characters in a row
var charsPerRow = textArea.cols;

// We need to know at which row our selection starts
var 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 pixels
var 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.

Advertisement