Monday, April 2, 2012

jQuery how to scroll to particular line in textarea

Recently I was working with outputting formatted source code in a textarea, and the requirement is you have a control "sidebar", which is a list, that allow user to click on and the textarea will scroll to particular line accordingly.

In jQuery, when you use the below. the textarea will scroll to the top

$('.my_class_for_this_textarea').animate({ scrollTop: 0 });

However, in my case, the sidebar list only tells you the code is in line 100 for example.  How to make sure you tell jQuery to scroll to the correct line every time??

scrollTop  takes "pixels", and you need to find out your pixel of each line is. And the following is the formular.

$('.my_class_for_this_textarea').animate({
  scrollTop: my_relative_line_number * LINE_PIXEL
}); 

No comments:

Post a Comment