Event Propagation in Javascript

One of the most important concept in javascript is DOM traversal. Before getting into event propagation, let us walkthrough with few basics of DOM and Events in javascript.

The DOM, Document Object Model, is a structure maintained by the browser on various elements present in it. It consists of set of nodes, elements and a well defined hierarchy of the browser elements.

Events are actions performed by the DOM elements. Javascript has various events like click, keyup, keydown and so on. These are the actions which an element performs when the it is triggered.

Now let us get into the topic of Event Propagation. As discussed earlier, the DOM hierarchy will have a definite structure which starts from the outermost element and goes into the innermost one. Events are triggered on the DOM elements. When an event is triggered on a particular element, the selected element does not get selected directly. Instead, it traverse from the outermost (parent) element and reaches the innermost (child) element, there by triggering all the elements present in between. After triggering, the traversal continues back in the opposite direction and ends at the outermost (parent) element. The former is called Capturing phase and the latter is called Bubbling phase. Due to this bubbling and capturing, other elements get triggered even when it is not required. Hence to prevent these actions related to bubbling and capturing, javascript has three methods:

  1. stopPropagation()
  2. stopImmediatePropagation()
  3. preventDefault()

When an event is triggered, it has to be triggered only for the selected elements. This means the parent element should be prevented from getting triggered and only the selected (child) element has to be triggered. To achieve this, stopPropagation() method is used.

In javascript, same event can be triggered for similar html elements. So when the event is triggered on one particular element, it happens, such that all similar elements will be triggered. To prevent this action, stopImmediatePropagation() method is called.

There are certain default actions, performed by the browser. For example, on mouse hover a hyperlink, the browser by default will show the full url of it. In a web application, generally a customised tool tip will be used to serve this purpose, there by maintaining the stability of the user experience throughout the application. But this tool tip action and browser default action will affect the look of the application. So, to prevent the default browser action, preventDefault() is used.