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.
We can use the CSS “::-webkit-scrollbar” property which is responsible for changing the shape, color, size, shade, shadow, etc. of the scroll bar. But, here the property which we will use is the direction property of CSS for changing the position of the scroll bar.
To get scroll position with React, we can add a scroll listener to window . to create the scrollPosition state with the useState hook. Then we add the handleScroll function that takes the scroll position with the window.
In order to achieve our goal our easiest way is to apply: window. scrollTo( value-x, value-y ); Here value-x is the pixel value of the width, where you wanna jump or scroll to.
You can use window.scrollTo()
, like this:
window.scrollTo(0, 0); // values are x,y-offset
Also worth noting window.scrollBy(dx,dy)
(ref)
Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo
and scrollBy
methods. You should:
var el = document.getElementById("myel"); // Or whatever method to get the element
// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;
// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;
You can also mimic the window.scrollTo
and window.scrollBy
functions to all the existant HTML elements in the webpage on browsers that don't support it natively:
Object.defineProperty(HTMLElement.prototype, "scrollTo", {
value: function(x, y) {
el.scrollTop = y;
el.scrollLeft = x;
},
enumerable: false
});
Object.defineProperty(HTMLElement.prototype, "scrollBy", {
value: function(x, y) {
el.scrollTop += y;
el.scrollLeft += x;
},
enumerable: false
});
so you can do:
var el = document.getElementById("myel"); // Or whatever method to get the element, again
// To set the scroll
el.scrollTo(0, 0);
// To increment the scroll
el.scrollBy(100, 100);
NOTE: Object.defineProperty
is encouraged, as directly adding properties to the prototype
is a breaking bad habit (When you see it :-).
... Or just replace body
by documentElement
:
document.documentElement.scrollTop = 0;
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