superocean superocean - 6 months ago 24
Javascript Question

Need help to prevent parent onclick event when click on child div

I want to to prevent parent onclick event when click on child div like that:



<div onclick='parentClick()'>
<div onclick='childClick()'>
<div onlick='subchildClick()'>
</div>
</div>
</div>





I want the childClick() function will do the subchildClick() function but prevent the parentClick(). How to do that?
Thank you very much!

Answer

In your childClick function use event.stopPropagation(). Like this:

function childClick(event) {
    event.stopPropagation();
    // Other stuff
}

event.stopPropagation() prevents the event from continuing to bubble up the DOM. Because you're just calling this in the childClick handler the event from the subChild will still propagate up to the childClick handler.

Comments