preventDefault vs. stopPropagation vs. stopImmediatePropagation

Working with events in HTML and JavaScript

Kunal Tandon
Developer’s Arena

--

While creating applications in JavaScript, we use the above terms interchangeably without knowing the difference between them.

Do you know what makes them different from each other?

In this article, we’ll discuss what the actual difference is among these statements and delve into the scenarios in which each of them is to be used.

Before we begin understanding these functions, we need to first understand event bubbling and event capturing.

What Are Event Bubbling and Event Capturing?

Event bubbling and event capturing are different ways by which an event (e.g., click event, key event, etc.) moves in a DOM structure.

To understand this, let's consider the following HTML element pseudocode:

<div class="parent" (onClick)="console.log('parent')">
<button class="child" (onClick)="console.log('child')"></button>
</div>

Event capturing means that when we click on the button, the click event will start from the top and move to the children. As a result, clicking on the button will print:

parent
child

--

--