Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a scrollbar position

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                               |   | +--------------------------------------+ 
like image 906
Scrollbar Avatar asked Aug 25 '10 01:08

Scrollbar


People also ask

How can I get the scrollbar position?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

What is the position of scroll bar?

The scrollbar is the horizontal or vertical position of the window's viewing area, meaning how much the user has scrolled from the left or the top. By default, the scroll position is 0px from the left and 0px from the top.

How do I get a scrollbar on the top?

To simulate a second horizontal scrollbar on top of an element, put a "dummy" div above the element that has horizontal scrolling, just high enough for a scrollbar. Then attach handlers of the "scroll" event for the dummy element and the real element, to get the other element in synch when either scrollbar is moved.


2 Answers

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; 
like image 181
Dan Herbert Avatar answered Oct 06 '22 23:10

Dan Herbert


You can use this:

$('a').on('click', function(e){   var t = this.id.substring(1);   e.preventDefault();   var target= $(".section")[t] ;   var offset = $( target ).offset();   $('html, body').stop().animate({     scrollTop: offset.top   }, 1000); }); 

Also, you could check this example on jsfiddle .

like image 29
Hessam Nadr Avatar answered Oct 06 '22 23:10

Hessam Nadr