Prevent inner elements trigger an event on the parent

Method 1
Stop propagation on inner elements before attaching an event on the parent.

$('#parent a').on('click', function(event){
  //stop the event bubbling up to the parent
  event.stopPropagation();
});

$('#parent').on('click', function(event){
  //attach event on the parent
  alert('Parent element clicked!');	
});

Method 2
Check if the event target matches the designated target.

$('#parent').on('click', function(event) {
  if(event.target == event.currentTarget) {
    alert('Parent element clicked!');
  } else {
    alert('Child element clicked!');
  }
});

Method 2.1
Check if the tag name of the event target matches a certain element.

$('#parent').on('click', function(event){
  if(event.target.tagName.toLowerCase() === 'a'){
    alert('Child anchor element clicked!');
  } else {
    alert('Parent element clicked!');
  }
});

Comments

  1. written by: Tonnie on January 3, 2018 at 4:24 pm - Reply

    nice man

  2. written by: sutara79 on July 22, 2018 at 5:21 am - Reply

    It is very helpful for me.
    Thank you.

    • written by: Mihai on August 5, 2018 at 11:23 pm - Reply

      You are welcome!

  3. written by: Juan on November 1, 2018 at 4:29 pm - Reply

    gracias!!

  4. written by: Mustafa Flexwala on June 18, 2019 at 8:29 pm - Reply

    Thanks a lot man It works!!

Leave a Reply

Your email address will not be published. Required fields are marked *

× 1 = 2

This site uses Akismet to reduce spam. Learn how your comment data is processed.