Event Bubbling and Throttling in JavaScript

Syed Muhammad Ali Raza - Sep 5 '23 - - Dev Community

Introduction

JavaScript is a versatile and powerful programming language that allows developers to create interactive and dynamic web applications. Two important concepts that come up often when dealing with events and user interactions in JavaScript are event propagation and inflating. In this article, we'll explore these concepts with real-life examples and provide code to show how it works.

Event Bubbling

Event bubbling is a basic concept in JavaScript and refers to the order in which events are propagated through the DOM (Request Object Model) when an event occurs on an element. When an event occurs in a cell element, it triggers not only that element, but also the parent element that bubbles up the DOM tree.

Example 1: Click Event Bubbling

Imagine a list of elements and event listeners on each element. Clicking on the element should change its color to red, but you want to see how the increase in the event affects the behavior.

<! DOCTYPE html>
<html>
<head>
  <title>Example of event bubble</title>
  <style>
    .item {
      padding: 10px;
      border: 1px solid #ccc;
      border: 5px;
    }
  </style>
</head>
<body>
  <div class="item" id="item1">Item 1</div>
  <div class="item" id="item2">Item 2</div>
  <div class="item" id="item3">Item 3</div>

  <script>
    const element = document.querySelectorAll('.element');

    item.forEach(item => {
      item.addEventListener( 'click', () => {
        item.style.backgroundColor = 'red';
      });
    });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example, if you click on "Item 1", it will flash red. However, all three items change color when you click on "Item 1" due to increased occurrences. This is because the click event propagates to the main element.

Throttling

Sitting is a technique used to control the speed of execution of a function. This ensures that the function is called at a certain maximum frequency, regardless of how many times an event is fired.

Example 2: Throttling for Scrolling

Consider a scenario where you have a looping event listener that performs a time-consuming operation such as making an API request every time the user loops. Without prompts, this process can become overwhelming and affect performance.

<! DOCTYPE html>
<html>
<head>
  <title>A strong example</title>
  <style>
    body {
      height: 2000px;
    }
  </style>
</head>
<body>
  <p>Scroll down to see the moves. </p>

  <script>
    must be inflated = false;

    function ExpensiveOperation () function
      console.log('Performing expensive operation...');
      // Wait 2 seconds and simulate expensive operation
      setTimeout (() => {
        console.log('Operation completed.');
        thrown = false;
      }, 2000);
    }

    windows.addEventListener( 'scroll', () => {
      if (!thrown) {
        performExpensiveOperation ();
        thrown = true;
      }
    });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example, when you scroll down the page, the message "Performing expensive operation..." is written every 2 seconds. This prevents expensive operations from being called continuously during fast cycles.

The results

An important concept in JavaScript that can significantly affect the behavior and functionality of event programs. Understanding how events are propagated through the DOM and how to control the frequency of function execution can help you create more efficient and effective web applications. The examples provided here should provide a solid foundation for incorporating these concepts into your JavaScript projects.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .