monocular
monocular

Reputation: 323

Jquery On Scroll not working with new element created

I'm using Jquery 1.9.1 . This code is for capture the scroll event when someone scroll the div in class "myclass".

$('.myclass').on('scroll', function() {
alert('test');
});

This work well with which element already have in page load. But when i using .append to create a new element :

$("body").append("<div class='myclass'> some large text to show the scrollbar ....</div>');

This new element will not fire any scroll event. How to resolve this problem ?


Updated the JsFiddle : http://jsfiddle.net/R6UH7/2/

Upvotes: 3

Views: 2734

Answers (3)

Krotz
Krotz

Reputation: 625

"In all browsers, the load, scroll, and error events (e.g., on an element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event."

Don't know exactly what they mean with directly attached but my first thought is that you can't scroll delegate dynamic data only those already existent.

Try this thanks to @Sergio

function apdDiv() {
    $("body").append('<div class="myclass" >This is another div that using append<br>This is another div that using append</div>');
    $('.myclass').scroll(function () {
        alert('test');
    });
}
$(document).ready(function () {
    apdDiv();
});

http://jsfiddle.net/VGVZJ/1/

This does not work with multiple appends!

Upvotes: 0

Sergio
Sergio

Reputation: 28837

Well, actually the events load, error and scroll do not bubble up the DOM. So you need another approach. The best I can think of is to add the listeners again... Like this:

function scrollfunc() {
    alert('test');
};

function listen_again() {
    var all = document.querySelectorAll(".myclass");
    for (i = 0; i < all.length; i++) {
        all[i].onscroll = scrollfunc;
    }
}

function apdDiv() {
    $("body").append('<div class="myclass" >This is another div that using append<br>This is another div that using append</div>');
    listen_again()
}

$(document).ready(function () {
    apdDiv();
    listen_again()
});

Demo here

Upvotes: 3

ArnauOrriols
ArnauOrriols

Reputation: 584

Put the on() function after the append.

$("body").append('<div class="myclass" >This is another div that using append<br>This is another div that using append</div>');
$('.myclass').on('scroll', function() {
alert('test');
});

http://jsfiddle.net/R6UH7/5/

Selecting "myclass" elements only happens once. If you select before you create the new one, you can't bind this event to the future div.

from on() documentation:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()

Upvotes: 0

Related Questions