Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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());
    });
    
like image 200
DFIVE Avatar asked May 16 '12 19:05

DFIVE


People also ask

How can use scroll event in jQuery?

jQuery scroll() MethodThe scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.

How can check scroll end in jQuery?

Use the . scroll() event on window , like this: $(window). scroll(function() { if($(window).

How do you call a function on a scroll?

The scroll() method is used to trigger the scroll event or attach a function to run when scrolling occurs. The scroll event occurs when a scrollbar is used for an element. The event is triggered when the user moves the scrollbar up or down. We can use the CSS overflow property for creating a scrollbar.


2 Answers

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

like image 104
Venar303 Avatar answered Sep 30 '22 21:09

Venar303


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()); 
});
like image 39
Matt Ball Avatar answered Sep 30 '22 20:09

Matt Ball