Difference between .on() functions calls

The difference between these two are

$('.wrapper1').on("scroll", ....) binds the scroll event to only those elements which are present at the time of execution of this statement, ie if any new element with class wrapper1 is added dynamically after this statement is executed then the event handler will not get executed for those elements.

$(document).on("scroll",".wrapper1", ...) on the other hand will register one event handler to the document object and will make use of event bubbling to invoke the handler whenever scrolling happens within an element with class `wrapper“, so it will support dynamic addition of elements.

So when to prefer a method

you can prefer first method if you have only a limited number of elements and they are not dynamically added

Prefer the second method if you have lot of elements or these elements are added dynamically.

Leave a Comment