Setting a scrollbar position

Scrollbar picture Scrollbar · Aug 25, 2010 · Viewed 75k times · Source

I have a table inside of a div (it's overflow, so the browser renders a scrollbar). Using JavaScript, how do I move the scrollbar handle along the track to a position that corresponds to the location of a row in the table?

+--------------------------------------+
|100                               |   |
|101                               |   |
|102                               |   |
|103                               |   |
|104                               |   |
|105     This is a table that      |---|
|106        has overflowed.        | - |  <-- I want to move this using JavaScript,
|107                               |---|      so that a specific row # is visible.
|108                               |   |
|109                               |   |
|110                               |   |
|111                               |   |
+--------------------------------------+

Answer

Dan Herbert picture Dan Herbert · Aug 25, 2010

If you want to go the non-jQuery way, use the containing table's scrollTop property.

Lets assume you can easily identify the row you want to scroll to using an ID, along with the containing <div />. Use the offsetTop of the element you want to scroll to.

var container = document.getElementById('myContainingDiv');
var rowToScrollTo = document.getElementById('myRow');

container.scrollTop = rowToScrollTo.offsetTop;