2

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?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
coder
  • 6,111
  • 19
  • 54
  • 73

2 Answers2

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