Saturday, October 12, 2013

Event Bubbling, How to prevent it ?


Event bubbling and capturing are two ways of event propagation in HTML DOM.

In bubbling the event is first captured and handled by the inner most element and then propagated to outer elements.
In capturing the event is first captured by the outer most element and propagated to the inner most element.

Only event bubbling model is supported by all the major browsers.

If for some reasons you want to stop propagation, you should “capture” an event and stop it from going further.

preventDefault(), stopPropagation(), stopImmediatePropagation(), return false, all these 4 methods are used to cancel the event or prevent it from bubbling. But they all are different from each other, Here's a tiny bit of explanation.

event.preventDefault() :
- This method stops the default action of an element from happening. For example, Prevents a link from following the URL.

event.stopPropagation():
- Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
- For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.
- Allows other handlers on the same element to be executed.

return false :
- It will do both 'stops the default action of an element from happening' and 'Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.'

event.stopImmediatePropagation() :
- This method prevents every event from running.

For example, see below jQuery code block.

$("p").click(function(event){
  event.stopImmediatePropagation();
});
$("p").click(function(event){
  // This function won't be executed
  $(this).css("background-color", "#f00");
}); 

If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

Related Posts Plugin for WordPress, Blogger...

Receive all updates via Facebook. Just Click the Like Button Below

You can also receive Free Email Updates: