Thursday, October 29, 2009

jQuery workaround for click exclusion

I've been working with jQuery for a short time now. I would think there is a better way to do this, so I'm looking for help.

I have a <div> which contains an <a href="...">

In my javascript, I handle click events on the div, but don't want to handle the a clicks (want the link to be followed).

I would like to express

$('div-expression-excluding-the-hyperlink').click( function {
// do something
});



but I don't know how to do that. Instead I have


link_clicked=false;
$('#a-id').click( function {
link_clicked = true;
});
$('#div-id).click( function {
if (!link_clicked)
// do things
}
link_clicked = false;
});



This works, but I'm not sure its reliable/portable,and I think there was a much better way to either filter out the a or determine the type of what was actually clicked in the callback. I think this references a <div> though.

2 comments:

rhyolight said...

The problem you are having is due to event bubbling. Because all events in child elements bubble up by default through the ancestor chain, you have to be careful when you attach an event handler to an element with many sub elements. You probably want something like this:

$('#divId').click(function(event) {
if (event.target == this) {
// do things
}
});

This way, the event handler will only do the behavior after it checks that the event target really was the div and not one of its sub-elements.

Jeff Schmitz said...

Thanks, exactly what I needed.