Detect scroll in an ajax loaded element with jQuer

2019-08-14 04:58发布

问题:

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.

回答1:

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:

$.post("filename", function(data){

    //insert element here

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


标签: jquery scroll