How to use jQuery.on () to catch a scroll event

I am trying to use .on () from jQuery to catch a scroll event that is inside a tag.

so this was my solution:

  • div id = 'popup'
  • the .fixedHeader class is what I'm trying to commit 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()); }); 
+7
jquery css jquery-plugins
May 16 '12 at 19:10
source share
3 answers

The event is just 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()); }); 
+5
May 16 '12 at 19:11
source share

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

If the document does not receive the xx event, then it does not bubble! See the jQuery On documentation for details, but the three load, error, and scroll events do not create DOM bubbles.

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

+11
Dec 28 '12 at 18:19
source share

As @ Venar303 says, scrolling does not bubble, so document snapping will not work.

Use this:

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

Instead of this:

 $(document).on('scroll', '#popup', function() {}); 
+2
Mar 13
source share



All Articles