Reputation: 4293
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
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
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
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