views:

659

answers:

3

I have an onclick event attached to a region in my page that causes a certain action to fire when the user clicks in it (naturally). I recently added an image to that region. When the user clicks on that image, I want another action to occur, and I do NOT want the action associated with the entire region to occur. However, I find that both events are, in fact fired when one clicks the image. How do I suppress the region-wide action when the image is clicked?

+1  A: 

In the event handler for the image do

event.cancelBubble = true;

and then at the end do

return false;
d4nt
+1  A: 

The issue you are running into is known as event bubbling. The click event of the image bubbles up to all parent elements of that node. You want to cancel bubbling.

The best way to do this that works across all browsers is by using a JavaScript framework. jQuery has a very simple way to do this. Other frameworks have similar mechanisms to cancel bubbling, I just happen to be most familiar with jQuery.

For example, you could do something like this in jQuery:

$('img').click(function () {
    // Do some stuff

    return false;// <- Cancels bubbling to parent elements.
});
Dan Herbert
+2  A: 

Darit is correct, you need to stop the event from bubbling (propagating):

function imgEventHandler(e) {
    // ^notice: pass 'e' (W3C event)

    // W3C:
    e.stopPropagation();

    // IE:
    if (window.event) {
        window.event.cancelBubble = true;
    }

}
J-P
The most correct answer, but I believe "return false" is also required.
annakata
Maybe I'm doing something wrong here, but for IE purposes I found I had to do:if (window.event) { cancelbubble} else { e.stopPropagation}
ep4169