textarea highlight / select and scroll to text – cross browser – pure javascript

I wanted a cross browser solution to select and highlight text within a text area. Trawling the internet yielded some partial solutions.

But I could not find one that scrolled to the correct location without a hack or some jiggery pockery

So I took what others had done and made it better. This is a cross browser solution that works in IE, firefox and chrome

the code pure javascript

Uasage

this is how to use it

how it works

Essentially, it uses the textareas full height (totalHeight), and the total number of new lines (totalLines). From this we can determine the line height

Now that we have the number of lines and the line height all we need now is to determine which line the selected text is on. To find this we take the total number of lines in the textare and deduct the number of new lines after our selected text

Finally to get the scroll to position we multiply the line number by the line position of the selected text