tags:

views:

56

answers:

4

So I have the following scenario:

<div id="block">
Sample text.
<a href="#">Anchor link</a>
</div>

<script type="text/javascript">
    $("#block").click(function() { alert('test'); });
</script>

When I click anywhere inside the div, I'm getting the 'test' alert. But, I want to prevent that from happening when I click on the "Anchor link". How can I implement that?

Thanks

+1  A: 

Hello,

This is what you need: http://api.jquery.com/event.target/ . Just compare to check if the element was triggered by the element you want or one of its children.

Regards, Alin

Alin Purcaru
+1  A: 

You can test which node was clicked with the target property of the event object:

$("#block").click(function(event) { 
    if(event.target.nodeName != 'A') {
        alert('test');
    }
});

I suggest to read Event Properties from quirksmode.org.

Felix Kling
+4  A: 

You can stop the clicks from bubbling up from links with an additional handler, like this:

$("#block a").click(function(e) { e.stopPropagation(); });

The the alternative we were discussing in comments:

$("#block").delegate('a', 'click', function(e){ e.stopImmediatePropagation(); })
           .click(function() { alert('test'); });​

This would prevent any child links from bubbling up (well, not really, but their handlers from executing), but not create a handler for each element, this is done via .stopImmediatePropagation().

Nick Craver
It feels a bit "overkill" to add a click handler to each link just to prevent event propagation (of course it depends on the number of links). But this is a good way to prevent event propagation for any specific element.
Felix Kling
@Felix - If there are many links I'd take a different approach entirely with a set of `.delegate()` handlers :) (you could use a delegate version of the above *before* the other click handler as well).
Nick Craver
I just tried with `delegate()` and it does not work for me: http://jsfiddle.net/cxcfA/. I assume because the event already bubbled up. Or do you mean something else?
Felix Kling
@Felix - `e.stopImmediatePropagation();` ;) http://jsfiddle.net/nick_craver/cxcfA/1/
Nick Craver
Very nice :) Good one! You always seem to have an answer ;)
Felix Kling
awesome answer! thank you
Elie
There's a bug though in jQuery, the delegate function doesn't return the object.
Elie
A: 
$("#block").click(function(event) {
    if($(event.target).attr('id') == $(this).attr('id'))
    {
        alert('test');
    }
});
methodin