Search code examples
jqueryeventsinfinite-scrolljquery-load

event not working on loaded elements


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!


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.