I have a div with a click event bound to it. I want to add an anchor tag inside this div that will not trigger the action of the div click. I have tried putting 'onclick="return false;"'
on the anchor but it still triggers the click on the div. Is there a trick to this?
Asked
Active
Viewed 2,127 times
2

Bill the Lizard
- 398,270
- 210
- 566
- 880

coder
- 6,111
- 19
- 54
- 73
-
How are you binding the click handler to the div element? – David Thomas Jan 03 '12 at 00:00
-
I'm using the jquery .click method – coder Jan 03 '12 at 00:03
-
possible duplicate of [How to stop event propagation with inline onclick attribute?](http://stackoverflow.com/questions/387736/how-to-stop-event-propagation-with-inline-onclick-attribute) – Purag Jan 03 '12 at 00:09
2 Answers
4
Given that you're using jQuery's click()
, you can do:
$('div').click(
function(e){
if (e.target.tagName == 'A') {
return false; // do nothing if the click is on the a element
}
else {
// do something else
}
});
Or:
$('a').click(
function(e){
e.stopPropagation(); // stops the click moving up to the parent elements
});

David Thomas
- 249,100
- 51
- 377
- 410
1
To prevent it you should prevent event bubbling. For no w3c browsers there is cancelBubble property other ways there is stopPropagation.
In the way you want to use it better to set events in one style. For the case jquery has: event.stopPropagation and event.stopImmediatePropagation methods to prevent it bubbling with one way in all browsers.

Flops
- 1,410
- 15
- 18