Detect scrolling in loaded ajax element using jQuery

If there is a button loaded with ajax and you need to listen for clicks on it, use .on() as follows:

 $(document).on('click', '.button', function(e) { // Do somethinh... }); 

What I know, but I can not use the same logic with a scroll. I have an element called #overlayer that loads ajax, and then I try to listen to it scroll and run a function that adds a sticky class to the sidebar when it is about to exit the viewport:

 $(document).on('scroll', '#overlayer', function() { stickySidebar(); console.log('scroll happened'); }); 

But it does not work.

I can get it to work as follows:

 $('#overlayer').on('scroll', function() { stickySidebar(); console.log('scroll happened'); }); 

But it will not work with ajax content uploaded.

+1
jquery scroll
Mar 14 '15 at 16:23
source share
1 answer

Binding an event to a loaded ajax element will not work unless you do it after the element has been inserted into the DOM, for example. in the callback function. Assuming you are using $.post , follow these steps:

 $.post("filename", function(data){ //insert element here //event handler $('#overlayer').on('scroll', function() { stickySidebar(); console.log('scroll happened'); }); }) 
+1
Mar 14 '15 at 16:36
source share



All Articles