Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: what correct use of .on() in this situation?

Tags:

jquery

events

Consider the following markup:

 <div class="parent">
     <div class="child">
         button
    </div>
 </div>

I need to run a function on a click event on the child class and I've got the following two options:

 $(".parent").on("click", ".child", function(){....});

and

 $(document).on("click", ".child", function(){....});

Is there a dramatic difference on performance between using a direct parent as a target and the document itself? To me using document seems as a more robust option (if the parent class was changed for instance) - just need to make sure it won't cause problems if I start using this method everywhere.

P.S. The child is added dynamically inside the parent hence I'm using .on()

like image 356
Allen S Avatar asked Oct 02 '22 10:10

Allen S


1 Answers

$(".parent").on("click", ".child", function(){....});

binds your click event to only those elements with class '.parent' that are present within the document and the event is bubbled from the target('.child') to the element where the handler is attached. This is much preferable than adding it to document as, adding it to document like

$(document).on("click", ".child", function(){....});
  1. Bubbles the click event from the target in the document where they occur all the way up to the body and the document element.

  2. As @Woff mentioned, bound handlers wont get removed on removal of .parent elements.

like image 185
rakhi4110 Avatar answered Oct 13 '22 11:10

rakhi4110