Question

Using any event such as mouseenter or click on an element will not work with elements loaded with infinitescroll, jquery.load, or jquery.ajax.

I do not understand why. I understand that functions need to be recalled, but a click event should still work because the loaded elements have the same classes and such, yet they do not!

Not only will the event not work, but if I recall it after the new elements load, the already loaded elements have now accumulated two events so that if you do something like $('.class').toggleClass('.anotherclass'), it will add and then remove the class because there are now two events on it rather than just one.

Why does this happen? and how can I have an event that wont accumulate like that?

hopefully I was clear, thank you!

Was it helpful?

Solution

I've had this problem in the past when dynamically creating elements that needed event listeners binded to them, this is what you need to do:

$(document).on("event", "#selector", function(){
    //Your code here
});

Binding to the document will allow all dynamic events to be triggered properly. Just change the event to what you need and the selector you need as well and it'll work.

OTHER TIPS

It really depends on how you attach the event handlers. Example:

// This will be attached to all currently existing elements with class
// .class, but not to future ones
$('.class').click(handler);

Using on():

// This is attached to the document and if the target of the event
// matches the provided selector then the event would be triggered
// on it. Here it doesn't matter whether the element with class
// .class existed at the time the handler was attached
$(document).on('click', '.class', handler);

My answer is mostly inside the comments, but basically the difference is in whether the event handler is direct or delegated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top