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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
function selectTextareaText(tarea, txt) { if (txt === undefined || ''){return;} var startPos = tarea.value.indexOf(txt); var endPos = startPos + txt.length; if (typeof (tarea.selectionStart) != "undefined") { tarea.focus(); tarea.selectionStart = startPos; tarea.selectionEnd = endPos; var totalHeight = tarea.scrollHeight; var totalLines = tarea.value.split(/\r\n|\r|\n/).length; var linesAfterStartpos = tarea.value.substring(startPos).split(/\r\n|\r|\n/).length; var lineheight = totalHeight / totalLines; var scrollTo = lineheight * (totalLines - linesAfterStartpos); tarea.scrollTop = scrollTo; return true; } // IE if (document.selection && document.selection.createRange) { tarea.focus(); tarea.select(); var range = document.selection.createRange(); range.collapse(true); range.moveEnd("character", endPos); range.moveStart("character", startPos); range.select(); return true; } return false; } |
Uasage
this is how to use it
1 2 |
var txtArea = document.getElementById('txtCustomList'); selectTextareaText(txtArea, txt); |
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