Why does e.stopPropagation() not work?

Ilyes512 picture Ilyes512 · Jul 16, 2013 · Viewed 20.7k times · Source

I am reading a book called "Adaptive Web Design" by Aaron Gustafson were I got a piece of javascript that I didnt understand. While researching I find out about the difference between returning false and e.preventDefault. I also now know a little bit about the bubbeling effect of JavaScript and came to understand that to stop the bubbeling you can use e.stopPropagation() (in none-ie browser atleast).

I was playing around in fiddle but I couldnt get it working. I think it might got to do with the way the bubbeling takes effect (from root to the element and back?).

document.body.onclick = function (e) {
    alert("Fired a onclick event!");
    e.preventDefault();
    if ('bubbles' in e) { // all browsers except IE before version 9
        if (e.bubbles) {
            e.stopPropagation();
            alert("The propagation of the event is stopped.");
        } else {
            alert("The event cannot propagate up the DOM hierarchy.");
        }
    } else { // Internet Explorer before version 9
        // always cancel bubbling
        e.cancelBubble = true;
        alert("The propagation of the event is stopped.");
    }
}

Here is the fiddle: http://jsfiddle.net/MekZii/pmekd/ (FIXED link) EDIT: I copy-pasted the wrong link! Its fixed now!

So what I would like to see is that when you click on the anchor, the onclick that is used on the div doesn't get executed (this is not a practical case, just a study case!)

Answer

Quentin picture Quentin · Jul 16, 2013

Events bubble from the element clicked on up to the document object.

Any event handler on a div is going to fire before an event handler on the body (since the body is an ancestor of it in the DOM).

By the time the event reaches the body, it is too late to prevent it from acting on a div.