Tony R
Tony R

Reputation: 11524

onclick event bubbling order

I'm getting a little confused about bubbling.

<html>
    <body>
        <div onclick="window.location='http://www.yahoo.com';">
            <span>
                <h3 onclick="window.location='http://www.google.com';">
                    Click me
                </h3>
            </span>
        </div>
    </body>
</html>

Can someone explain why the page is changed to www.yahoo.com? How do I force it to "bubble" instead of "capture"?

Upvotes: 2

Views: 2433

Answers (2)

SeanCannon
SeanCannon

Reputation: 77966

It will bubble by default. You can't force capture in IE anyway, do don't use it as a reliable method of event handling.

If you want to stop the event, you'll need to use event.stopPropagation(); and event.cancelBubble = true for IE.

Demo: http://jsfiddle.net/AlienWebguy/cZWQg/ (used window.open() so you can see the effect in jsfiddle).

JQuery will normalize the event.stopPropagation() function so it'll work for all browsers.

Example:

$('h3').click(function(e){
    e.stopPropagation();
    window.location = 'http://www.google.com';
});

Upvotes: 4

Mikey G
Mikey G

Reputation: 3491

when h3 is clicked, it is also calling the on click of the div, thus redirecting to yahoo instead of google

This might help explain it better than i can:

http://www.quirksmode.org/js/events_order.html

Upvotes: 0

Related Questions