简体   繁体   中英

how to detect if scroll is happening within certain element

I wanted to detect if the pointer scroll is happening within a certain element and then do certain actions. I've tried this code but it seems to not working:

var lastScrollTop = 0;
    $(".class-name").scroll(function(event){
       var st = $(this).scrollTop();
       if (st > lastScrollTop){
           console.log("scroll down");
       } else {
          console.log("scroll up");
       }
       lastScrollTop = st;
    });

can you help me understand what I am doing wrong?

Thank you!

EDIT:

scrollTop gives you the current position of the scroll bar of the element not of the page.
So if he hasn't scroll bar it will be 0.:

or if the element is not scrollable, this number will be 0.

and the same for .scroll() if the element hasn't scroll bar it will never occur.

 var lastScrollTop = 0; $(".class-name").scroll(function(event){ var st = $(this).scrollTop(); if (st > lastScrollTop){ console.log("scroll down"); } else { console.log("scroll up"); } lastScrollTop = st; });
 .class-name{ width:100px; height:200px; overflow:auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="class-name">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>

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