Computer >> Computer tutorials >  >> Programming >> Javascript

What is Event Bubbling in JavaScript?


Event Bubbling

Event bubbling process starts with the element that triggered the event and then bubbles up to the containing elements in the hierarchy. 

Debrief

In the following example we have 3 elements div, span and button.

  • To maintain the hierarchy we need that button element to be nested inside the span element, and span element to be nested inside div element. 
  • Assign click events to all the elements so that when an element got clicked, an alert box should open displaying a respected message as shown in the example.
  • After executing the program, the below shown image will get executed on the screen. 
  • When an element got clicked then automatically its outside elements(containing elements) also got bubbled up and executed.
  • For instance, if we click on the inner most nested element(button) then along with its alert box other element's alert box(span, div) will also open one by one following the hierarchy. 
  • For suppose, if we click on the span element then alert box of span and its containing element div will open up one by one. 
  • 8) This process of triggering element and then bubbling up to the containing elements in the hierarchy is called event bubbling.
  • 9) The triggered and bubbled up elements will be executed.

Example

<html>
<head>
<style>
   .styleClass{
      display:table-cell;
      border:1px solid black;
      padding: 20px;
      text-align:center;
   }
</style>
</head>
<body>
   <div class = "styleClass" onclick = "alert('Div clicked')">Div element
   <span class = "styleClass" onclick ="alert('Span clicked')">span element
   <input type = "button" value = "click me" onclick="alert('Button clicked')">
</span>
</div>
</body>
</html>

After executing the program in code editor the following image will display

What is Event Bubbling in JavaScript?  When clicked on the 'click me' button(button element) the following output will display.

Output

The following output will display on clicking the above "click me" button(button element)

What is Event Bubbling in JavaScript?

on clicking ok on above button alert box, we will get the following alert box with message span clicked. What is Event Bubbling in JavaScript?  on clicking ok on above span alert box, we will get the following alert box with message div clicked.  What is Event Bubbling in JavaScript?