Blupixel IT Blog – Computer Science and Web Developing Articles

Offical Blog of Blupixel IT Srl

Scroll textarea to selected word using javascript / jQuery

Here now one of those article which content will not be found easily on the net.
This is the solution to a problem I’ve never found answer before…

The question is really simple: We have a textarea, how can we scroll inside it to a specific word?

If you look on the net you’ll find a lot of solutions with strange numbers that work only in specific cases and not when the textarea has fluid dimension.

After a lot of time, finally, I found in Math the real solution!

Let’s start from the code and let’s suppose our textarea has id=”my_textarea”
Be aware that there is just one rule: specify a line-height in the css of the textarea!
We’ll use jquery but you can easily convert the code in pure javascript.
To see better the searched word we will highlight it!

The code is written using italian words, but it’s commented in english language

var parola_cercata = "parola"; // the searched word
var posi = jQuery('#my_textarea').val().indexOf(parola_cercata); // take the position of the word in the text
if (posi != -1) {
	var target = document.getElementById("my_textarea");
        // select the textarea and the word
	target.focus();
        if (target.setSelectionRange)
            target.setSelectionRange(posi, posi+parola_cercata.length);
        else {
            var r = target.createTextRange();
            r.collapse(true);
            r.moveEnd('character',  posi+parola_cercata);
            r.moveStart('character', posi);
            r.select();
        }
        var objDiv = document.getElementById("my_textarea");
	var sh = objDiv.scrollHeight; //height in pixel of the textarea (n_rows*line_height)
	var line_ht = jQuery('#my_textarea').css('line-height').replace('px',''); //height in pixel of each row
	var n_lines = sh/line_ht; // the total amount of lines
	var char_in_line = jQuery('#insert_textarea').val().length / n_lines; // amount of chars for each line
	var height = Math.floor(posi/char_in_line); // amount of lines in the textarea
	jQuery('#my_textarea').scrollTop(height*line_ht); // scroll to the selected line
} else {
        alert('parola '+parola_cercata+' non trovata'); // alert word not found
}

Let’s have a look to the code:

  • The searched word is stored in a javascript variable. If you need to create a function you can pass it as an input parameter
  • In the variable named “posi” we store the position of the word found in the text of the textarea
  • If the word has been found (posi != -1) we continue. Otherwise return an alert saying that the word has not been found
  • We select the word to highlight it and make it more visible
  • We take the scroll height in pixel of the textarea
  • We get the height in pixel of the line-height paramater replacing the “px” word from the result
  • We calculate the total amount of rows of the textarea dividing the total height for the height of the single row
  • The fundamental part is now! We need to know how many chars there are in a row. So we get it making a division between the length of all the text and the total number of rows
  • Now everything is easy! The row where the word has been found and then where we have to scroll to is the division between the position of the word in the text and the number of chars for each row.
  • To get the scroll now just recalculate the pixel height as the number of the row multiplied the line-height

You can test it here with a word in the textarea (it has been tested on Firefox Web Browser):

See you soon!

  • Michelle says:

    Bless your heart!! I’ve been searching for hours on how to do this!
    Thanks you so much!!!

    July 15, 2013 at 7:27 pm
  • Irving Salgado says:

    Hi, Blupixel IT Sr.

    Is an excelent blog, this solution is great, well, I look for the complete code, don’t can find, please Where Can I download the code..??

    Thank’s a millon..!

    December 18, 2013 at 7:26 pm
  • Chris says:

    Thank You very much. Based on your model I added a style attribute to my textarea element. (style=”line-height:20px”). Then in the script after counting the number of lines from the top to get the required position:

    textarea.scrollTop= linecount* parseInt(textarea.style.lineHeight);

    this is behaving very well for me so again

    THANKS !!!

    February 5, 2014 at 5:47 am
    • reus says:

      grate work master! thank you for this. more power!

      March 7, 2014 at 1:24 pm
  • Dave K says:

    Tested it in both Firefox and Chrome, both working but code will only return the first found item.
    e.g. search ‘the’, only the first will be highlighted the remain 6 are not

    May 29, 2014 at 12:54 am
    • admin says:

      Yes, it finds only the first occurrences. If you want more I think you can add a Next button to execute again the function and change the command:
      var posi = jQuery(‘#my_textarea’).val().indexOf(parola_cercata);
      in
      var posi = jQuery(‘#my_textarea’).val().indexOf(parola_cercata, start_from_here);
      where start_from_here is the last position + 1

      If you want it to be automatized, insetad, just put the code in a loop changing the commands as above and checking everytime if there is a new occurrences starting from last position.

      Hope this helps

      May 29, 2014 at 8:52 am
  • Wen shoo says:

    Not that perfect if there are some new blank lines or lines with just one or two letters in the textarea

    July 28, 2014 at 2:24 am

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

*

6oIpK

Please type the text above: