How to use JQuery .on() to catch the scroll event

前端 未结 3 372
既然无缘
既然无缘 2021-01-18 04:08

I\'m attempting to use the .on() from jQuery to catch a scroll event that is inside a tag.

so this was my solution:

  • the div id=\'popup\'
  • the
相关标签:
3条回答
  • 2021-01-18 04:38

    The confusion is in how "on()" works. In jQuery when you say $(document).on(xx, "#popup", yy) you are trying to run yyy whenever the xx event reaches document but the original target was "#popup".

    If document is not getting the xx event, then that means it isn't bubbling up! The details are in the jQuery On documentation, but the three events "load", "error" and "scroll" do not bubble up the DOM.

    This means you need to attach the event directly to the element receiving it. $("#popup").on(xx,yy);

    0 讨论(0)
  • 2021-01-18 04:42

    As @Venar303 says, scroll doesn't bubble, thus binding to document will not work.

    Use this:

    $('#popup').on('scroll', function() {});
    

    Instead of this:

    $(document).on('scroll', '#popup', function() {});
    
    0 讨论(0)
  • 2021-01-18 04:43

    The event is simply scroll, not scroll#popup.

    // http://ejohn.org/blog/learning-from-twitter
    // Also, be consistent with " vs '
    var $fixedHeader = $('.fixedHeader').css('position', 'relative');
    
    $(document).on('scroll', '#popup', function() {
       console.log('scrolling'); // you *really* don't want to alert in a scroll
       $fixedHeader.css("top", getScrollTop()); 
    });
    
    0 讨论(0)
提交回复
热议问题