I have this simple issue: a div that contains a link, and the div has an onclick function defined. However, when I click the link, I just want to follow the link, and not fire the containing div's function.
Fiddle
HTML
<div>
<a href="http://www.google.com" target="_blank">Google</a>
</div>
JQuery
$('div').click(function() {
alert("test");
});
CSS
div {
height: 100px;
width: 200px;
border: 1px solid red
}
So here, when I click the div, an alert is shown: that's fine. When the link is clicked, I don't want the alert to show.
How to avoid this?
We set the onClick prop on the div element, so every time the element is clicked, the handleClick function gets invoked. If you need to access the div element in your handleClick function, access the currentTarget property on the event object.
The onclick event occurs when the user clicks on an element.
We simply add the onlcick event and add a location to it. Then, additionally and optionally, we add a cursor: pointer to indicate to the user the div is clickable. This will make the whole div clickable.
You can apply event.stopImmediatePropagation();
to the link. According to the API, this keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree (https://api.jquery.com/event.stopimmediatepropagation/).
Here is the fiddle: http://jsfiddle.net/dxrdrqrc/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With