Event Propagation

When event handlers registered on nodes with children, children will also receive some events.

For example if a button inside a paragraph is clicked, event handlers on the paragraph will also receive the click event.

If both the paragraph and the button have a handler, and when button is clicked the more specific handler, button event go first. The event will propagate outward, from the node where it happened to that node's parent node and on to the root of the document. Once all handlers registered on a specific node have executed, handlers registered on the whole window get a chance to respond to the event.

To prevent this behavior like receiving the event "further up", an event handler can call the stopPropagation method on the event object. This will be useful when you have a button inside another clickable element and you don't want clicks on the button to activate the outer element's click behavior.

The following example registers "mousedown" handlers on both a button and the paragraph around it. When you click on the button with the right mouse button, the handler for the button calls stopPropagataion, which will prevent the handler on the paragraph from running. When the button is clicked with another mouse button, both handlers will run.

<p>A paragraph with a<button>button</button>.</p>

<script>
var para = document.querySelector("p");
var button = document.querySelector("button");
para.addEventListener("mousedown", function() {
    console.log("Handler for paragraph.");
});
button.addEventListener("mousedown", function(event) {
    console.log("Handler for button.");
    if (event.which == 3)
        event.stopPropagation();
});
</script>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents