Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking link inside div firing div's onclick

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?

like image 535
chiapa Avatar asked May 16 '16 14:05

chiapa


People also ask

Can Onclick be used with div?

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.

What is Onclick in Dom?

The onclick event occurs when the user clicks on an element.

How do you click a div in HTML?

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.


1 Answers

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/

like image 69
Gerardo Furtado Avatar answered Sep 20 '22 12:09

Gerardo Furtado