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 | | +--------------------------------------+
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.
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.
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.
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;
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With