Search code examples
javascriptjqueryevent-bubbling

How can I force to call dynamically added element,s onclick() first


<div id="outerDiv" onclick="javascript:addEvent()">
    <div id="inner">
        <a class='editEV' href="javascript:void(0)">event1</a>//*added dynamically from addEvent method.*
    </div>
 </div>

My script is:

$('#inner').on('click','.editEV',function(){
    editEvent();
});

When I click on anchor addEvent() called first then editEvent(), but I want that when I click on div then addEvent() should call and when I click anchor then editEvent.

I am aware about bubbling so that's why I introduce an inner static div to bind listener, but still addEvent() calls first. I am unable to figure out how can I force to call editEvent first.


Solution

  • You are using both - inline event set ( onclick=.. ) and Jquery on. Choose one of them to have more clear code. I would choose jquery on, and solution for this problem is to create two events - one on div, second on edit element, but in second We need to stop bubbling by using e.stopPropagation method. Here full working example:

    $(function(){
    
      $("#outerDiv").on("click",function(e){
      
          console.log("Add click");
    
      }); 
      
      $("#outerDiv").on("click",".editEV",function(e){
      
          console.log("Edit click");
          e.stopPropagation();//very important to stop propagate event
    
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="outerDiv" style="padding:20px; background:grey;">
        <div id="inner">
            <a class='editEV' >event1</a>
        </div>
     </div>

    Without stopPropagation our event is going up to div and runs its event, stopPropagation avoids propagate event to upper elements.