ler ler - 4 years ago 114
Javascript Question

Jquery scroll dosn't work if i load new data on a div

I don't know what's the problem in my code, i did some search about this problem but i don't know how to make my code work.
i made a simple demo of my problem on jsfiddle. this is the link: jsfiddle

this is my code:

$(function() {
$('.container').scroll(function() {
alert('scroll');
});
$('.clickMe').click(function () {
$('.dddd').html('<div class="container"><div class="my_div">test</div></div>');
})
})


what i want is how to make the scroll event work if some new data was loaded.

Answer Source

You have to bind on the new content. Binding only works on elements that exist at the time it executed.

$(function() {
    var scrollHandler = function(){
        alert('scroll');
    };

    $('.container').on('scroll', scrollHandler);

    $('.clickMe').on('click', function () {
        $('.dddd').html('<div class="container"><div class="my_div">test</div></div>');
        $('.dddd').find('.container').on('scroll', scrollHandler);
    });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download