Home > Web Front-end > JS Tutorial > How Can I Determine the Scroll Direction (Up or Down) Using jQuery?

How Can I Determine the Scroll Direction (Up or Down) Using jQuery?

Barbara Streisand
Release: 2024-12-07 08:16:13
Original
292 people have browsed it

How Can I Determine the Scroll Direction (Up or Down) Using jQuery?

Determining the Direction of jQuery Scroll Events

When handling scroll events in jQuery, it can be useful to know whether the scroll is moving up or down the page. This can be achieved by comparing the current scrollTop value to the previous scrollTop value. Here's how you can do it:

var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st;
});
Copy after login

In this code, lastScrollTop is initialized to 0. When the scroll event occurs, the current scrollTop value is stored in st. If st is greater than lastScrollTop, the code executes the downscroll code, and if st is less than lastScrollTop, the code executes the upscroll code. Finally, lastScrollTop is updated with the new scrollTop value.

The above is the detailed content of How Can I Determine the Scroll Direction (Up or Down) Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template