Detecting Scroll Direction
Utilizing JavaScript's scroll event, it's possible to determine the direction of scrolling without the need for jQuery.
Detecting Scroll Direction
To accomplish this, we'll store the previous scrollTop value and compare it to the current scrollTop value.
<code class="javascript">var lastScrollTop = 0; // element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element. element.addEventListener("scroll", function () { // or window.addEventListener("scroll".... var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426" if (st > lastScrollTop) { // downscroll code } else if (st < lastScrollTop) { // upscroll code } // else was horizontal scroll lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling }, false);</code>
By employing this method, you can accurately detect the scrolling direction in any web page without relying on third-party libraries.
The above is the detailed content of How can I detect scroll direction using JavaScript without jQuery?. For more information, please follow other related articles on the PHP Chinese website!