Skip to content Skip to sidebar Skip to footer

Link Within A Link Onclick Event - Avoid Both Click Events Triggering

I have a link within a link, both with an onClick event. The outer link works as desired. However, the inner link triggers both onClick events. I would like it so that the outer e

Solution 1:

Javascript events will propagate up through the tree.

So when you click on the inner anchor it will also emit any click events for elements higher up, so the div element.

To stop this the inner click handler has to prevent the event from propagating with e.stopPropagation();.

However this gets a little messy when you don't register handlers with .addEventListener() in JavaScript.

If you add events this way you can do it like this (first give your anchor an id, say inner) which is nice and easy:

document.getElementById('inner').addEventListener('click', function (e) {
    e.stopPropagation();
    console.log(2);
});

You can however pass the event into your click handler if you do wish to use the attribute, so:

<a href="#" onClick="innerHandler(event)">Inner</a>

//JSfunctioninnerHandler(e) {
    e.stopPropagation();
    console.log(2);
}

Generally speaking (this is my opinion) i would avoid the latter. Events registered like this are difficult to remove and modify. You can't also easily register multiple handlers to the same element for the same event.

stopPropagation docs

Post a Comment for "Link Within A Link Onclick Event - Avoid Both Click Events Triggering"