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?
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?
Share Improve this question asked Aug 20, 2012 at 18:47 tophergtopherg 4,3234 gold badges38 silver badges73 bronze badges3 Answers
Reset to default 2Use 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);
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();
};
the parent click handler: (check on the id of the clicked element)
function handler(e){
if(e.target.id != "parentID") return;
....
}