any_h
any_h

Reputation: 568

Detect scroll in an ajax loaded element with jQuery

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.

Upvotes: 1

Views: 1656

Answers (1)

Miqi180
Miqi180

Reputation: 1691

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

Upvotes: 2

Related Questions