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; });
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!