Juliver Galleto
Juliver Galleto

Reputation: 9037

separate event function trigger twice on a child element where parent has the same event function

below is my snippet, the issue is, if you click unto the "li" element that has a text of "test 1" the alert prompt did trigger once (normal) but if you click unto the "li" element that has a text of "test 2", the alert prompt triggered twice like the click event function called twice. Any ideas, clues?

$(document).ready(function(){
  
  $(document).on("click", ".nav a", function(){
    
   alert("test"); 
  })
  $(document).on("click", ".dp a", function(){
    
   alert("test"); 
  })
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul class="nav">
  <li><a href="#">test 1</a></li>
  <li><a href="#">test 1</a></li>
  <li><a href="#">test 1</a>
    <ul class="dp">
      <li><a href="#">test 2</a></li>
      <li><a href="#">test 2</a></li>
    </ul>
  </li>
</ul>

Upvotes: 0

Views: 256

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115232

Use event.stopPropagation(), It will prevent any parent event action

$(document).ready(function() {
  $(document).on("click", ".nav a", function() {
    alert("test");
  }).on("click", ".dp a", function(e) {
    e.stopPropogation();
    alert("test");
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul class="nav">
  <li><a href="#">test 1</a>
  </li>
  <li><a href="#">test 1</a>
  </li>
  <li><a href="#">test 1</a>
    <ul class="dp">
      <li><a href="#">test 2</a>
      </li>
      <li><a href="#">test 2</a>
      </li>
    </ul>
  </li>
</ul>

UPDATE :

As haim770's suggested, bind event handler to the appropriate selector to prevent bubbling

$(document).ready(function() {
  $(document).on("click", ".nav > li > a", function() {
    alert("test");
  }).on("click", ".dp a", function() {
    alert("test");
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul class="nav">
  <li><a href="#">test 1</a>
  </li>
  <li><a href="#">test 1</a>
  </li>
  <li><a href="#">test 1</a>
    <ul class="dp">
      <li><a href="#">test 2</a>
      </li>
      <li><a href="#">test 2</a>
      </li>
    </ul>
  </li>
</ul>

Upvotes: 1

quirky purple
quirky purple

Reputation: 2219

Specify which hyperlink for the first click event.

FIDDLE: https://jsfiddle.net/cshanno/Loc4427u/1/

JS

$(document).ready(function(){

  $(document).on("click", "ul:nth-child(1) > li > a", function(){

   alert("test"); 
  })
  $(document).on("click", ".dp a", function(){

   alert("test 2"); 
  })

});

Upvotes: 1

Related Questions