topherg
topherg

Reputation: 4293

Stop Javascript event from affecting child elements

I have a script that creates an element, and part of the creation process is to add an onclick event (using addEventListener), but when I click a child element, the onclick event of the parent is triggered. How can I prevent the click from being detected when the source is a child element?

Upvotes: 1

Views: 4577

Answers (3)

jeremy
jeremy

Reputation: 10057

Use event.stopPropagation(). This stops the bubbling of Javascript events and will only allow the events applied to the targetted element to execute;

window.addEventListener("click", function(event){

    // event here

    event.stopPropagation();
}, false);

Upvotes: 2

unloco
unloco

Reputation: 7320

the parent click handler: (check on the id of the clicked element)

function handler(e){
  if(e.target.id != "parentID") return;
  ....
}

Upvotes: 2

Brian Ustas
Brian Ustas

Reputation: 65529

The problem is that the event is bubbling up to the parent.

In the child's onclick event, tell the event to stop propagation:

onclick = function (event) {
    // ...
    event.stopPropagation();
};

Upvotes: 2

Related Questions