简体   繁体   中英

Jquery detect if scroll is on the top

I have a code to detect user scroll, it works when scrolling bottom

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(window).scroll(function() { if($(window).scrollTop() + $(window).height() == $(document).height()) { alert("bottom!"); } }); </script> <div style="height: 4000px">Scroll down!</div> 

I would like to make it works when scroll to the top of the page, how can I do that?

You can check the scrollTop() value to see if it equals zero:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(window).scroll(function() { if ($(window).scrollTop() + $(window).height() == $(document).height()) { alert("bottom!"); } if ($(window).scrollTop() == 0) { alert("top!"); } }); </script> <div style="height: 4000px">Scroll down!</div> 

As the scrollTop() docs state:

If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM