简体   繁体   中英

jQuery Scroll Event Not Working With Section

I'm trying to make a simple scrollspy with jQuery Scroll event but it fails. Here is my JavaScript part:

<script>
 $(document).ready(function(){
   $("#credit_card").scroll(function(){
     console.log('OK');
   });
 });
</script>

And HTML part:

<section class="method first-of-group" id="credit_card">
...
</section>

As you might have guessed, console.log is just for testing. This section is under a div and this div has "content" id. If I change my JavaScript code for "content" id, it is working. It's really weird.

If you want to see it live, please visit here .

Thanks in advance.

After reading the comments and actually understanding what you mean, this is the solution you are looking for.

 $(document).ready(function(){
   $("#content").scroll(function(){

     // when the user scrolls, we want to detect at what section they currently are. 
     // This can be calculated, by comparing the current window scrolltop to the position and height of the section elements.
    var currentTopOffset = $(document).scrollTop();

     $('section').each(function(){
         var min = $(this).offset().top;
         var max = $(this).offset().top + $(this).height();
         if(currentTopOffset > min && currentTopOffset < max){
           // current section
           // do something here, like getting a value from an input type hidden with the section name
         }
     });
   });
 });

I hope this is what you are looking for, or atleast something to get you started with.

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