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

点点圈 提交于 2019-12-19 17:27:42

问题


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 .fixedHeader class is something I'm trying have fixed at the top of the div frame.
  • getScrollTop() is a javascript function to return the top value (works)

    $(document).on("scroll#popup", '#popup', function(){
       alert('scrolling');
       $(".fixedHeader").css("position", "relative");
       $(".fixedHeader").css("top", getScrollTop());
    });
    

回答1:


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



回答2:


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




回答3:


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() {});


来源:https://stackoverflow.com/questions/10625104/how-to-use-jquery-on-to-catch-the-scroll-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!