Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

I'm currently using jQuery to make a div clickable and in this div I also have anchors. The problem I'm running into is that when I click on an anchor both click events are firing (for the div and the anchor). How do I prevent the div's onclick event from firing when an anchor is clicked?

Here's the broken code:

JavaScript

var url = $("#clickable a").attr("href");  $("#clickable").click(function() {     window.location = url;     return true; }) 

HTML

<div id="clickable">     <!-- Other content. -->     <a href="http://foo.com">I don't want #clickable to handle this click event.</a> </div> 
like image 684
Jonathon Watney Avatar asked Sep 02 '09 17:09

Jonathon Watney


People also ask

How do I stop click event propagation?

To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e. stopPropagation(); alert('The button was clicked!

How do you handle button click events?

Onclick in XML layout When the user clicks a button, the Button object receives an on-click event. To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.


1 Answers

Events bubble to the highest point in the DOM at which a click event has been attached. So in your example, even if you didn't have any other explicitly clickable elements in the div, every child element of the div would bubble their click event up the DOM to until the DIV's click event handler catches it.

There are two solutions to this is to check to see who actually originated the event. jQuery passes an eventargs object along with the event:

$("#clickable").click(function(e) {     var senderElement = e.target;     // Check if sender is the <div> element e.g.     // if($(e.target).is("div")) {     window.location = url;     return true; }); 

You can also attach a click event handler to your links which tell them to stop event bubbling after their own handler executes:

$("#clickable a").click(function(e) {    // Do something    e.stopPropagation(); }); 
like image 77
Rex M Avatar answered Oct 10 '22 09:10

Rex M