Event Handling in JavaScript

Events in a web application demand actions. Every event has a handler associated with it.

In JavaScript, every event has a lifecycle, consisting of 3 phases:

  • Capturing
  • Targeting
  • Bubbling

Lets look at them in detail.

Capturing

Whenever user interacts with browser, in the form of clicks, select or entering values etc., events are generated. Lets assume that user has clicked a button.

In order to be captured, it traverses from Document 🠊 HTML🠊Body 🠊 Div 🠊 Button which is clicked.
As you could see in the above image, event traverses to actual element where it has occurred.
This is called as capturing an event.

Targeting

When an event reaches to the destination or element where it has occurred, it is called as targeting phase.

As can be seen above, when user clicked the button, it gets captured in phase 1 and traverses through until it reaches to its destination or target element, which is Button.

Bubbling

When event is targeted, then it must be handled. In order to be handled, this event starts its journey in reverse order of capturing, i.e., Button🠊 Div 🠊Body 🠊 HTML 🠊 Document looking for a handler.
This is the process of event bubbling. If there is no event handler associated at Button element, JavaScript keeps looking for its ancestors for that handler until it finds it.

Comments

Popular Posts