If there's a button that is loaded with ajax, and you need to listen clicks on it, use the .on()
like so:
$(document).on('click', '.button', function(e) {
// Do somethinh...
});
That I know, but I can't use this same logic with a scroll. I got an element called #overlayer
that gets ajax loading in, then I'm trying to listen scroll on it and trigger a function that adds sticky class to sidebar when it's about to exit the viewport:
$(document).on('scroll', '#overlayer', function() {
stickySidebar();
console.log('scroll happened');
});
But it's not working.
I can get it to work like this:
$('#overlayer').on('scroll', function() {
stickySidebar();
console.log('scroll happened');
});
But it wont work on the ajax loaded content.
Binding an event to an ajax loaded element won't work unless you do it after the element has been inserted into the DOM, e.g. in the callback function. Assuming you're using
$.post
, do something like this: