Fouaad
  • Login
Cart / £0.00
No Result
View All Result
  • Home
  • Philosophy
    • Books
    • Theory
  • How-To
    • Life
    • Work
    • Write
    • Finance
  • Tech
    • Hardware
    • Firmware
  • War
  • Politics
Fouaad
No Result
View All Result

Event Bubbling Unveiled: Navigating JavaScript’s Event Propagation

by Admin
October 15, 2023
in Firmware, Hardware, Tech
Reading Time: 5 mins read
392 4
A A
0
Share on FacebookShare on TwitterShare on WhatsappEmailShare on LInkedinShare on Pinterest


You will learn:

  • Introduction
  • 1. The Essence of Event bubbling in JavaScript
    • 1.1 Understanding Event bubbling in JavaScript
  • 2. Practical Illustration of Event bubbling in JavaScript
  • 3. The Intriguing World of Fibonacci Series in JavaScript
    • 3.1 Understanding the Fibonacci Series
    • 3.2 Generating the Fibonacci Series in JavaScript
  • 4. Embracing the Essence of Event Bubbling
    • 4.1 Event Delegation: A Practical Application
    • 4.2 Preventing Event Bubbling
  • 5. Conclusion

Introduction

JavaScript, the cornerstone of dynamic web development, empowers developers to create interactive and engaging user experiences. Central to this interactivity is the handling of events, which occur when users interact with elements on a webpage. While events themselves play a crucial role, understanding event propagation mechanisms is equally vital. One such mechanism is event bubbling, which governs how events traverse the DOM tree. In this comprehensive exploration, we will unveil the intricacies of event bubbling in JavaScript, shedding light on its significance, inner workings, and practical implications. As we delve into this topic, we will also take a detour to explore the fascinating concept of the Fibonacci series in JavaScript, showcasing the versatility of the language.

1. The Essence of Event bubbling in JavaScript

At the core of event handling in JavaScript lies the concept of event propagation. Event propagation refers to the process by which an event generated by a user’s action on an element propagates through the DOM tree, potentially triggering handlers on parent elements. Among the two primary mechanisms of event propagation—event bubbling and event capturing—we will focus on event bubbling.

1.1 Understanding Event bubbling in JavaScript

Event bubbling is a phenomenon in which an event starts from the target element that triggered the event and travels up the DOM tree, invoking event handlers on parent elements. This bubbling effect enables you to capture events at various levels of the DOM hierarchy.

Consider the following HTML structure:

<div id="outer">
  <div id="middle">
    <button id="inner">Click me!</button>
  </div>
</div>

If a click event occurs on the “inner” button element, the event will propagate in the following order: “inner” → “middle” → “outer”. This allows you to capture the event at any level of the hierarchy.

2. Practical Illustration of Event bubbling in JavaScript

To grasp the concept of event bubbling, let’s delve into a practical example involving click events:

<div id="container">
  <button id="btn1">Button 1</button>
  <button id="btn2">Button 2</button>
</div>
document.getElementById("container").addEventListener("click", function (event) 
  console.log("Container clicked!");
);

document.getElementById("btn1").addEventListener("click", function (event) 
  console.log("Button 1 clicked!");
  event.stopPropagation(); // Prevent further event propagation
);

document.getElementById("btn2").addEventListener("click", function (event) 
  console.log("Button 2 clicked!");
);

In this example, when you click “Button 1”, event bubbling occurs. The click event is first captured by the “Button 1” event handler, and then it bubbles up to the “Container” level. However, since we’ve used event.stopPropagation() in the “Button 1” handler, the event propagation is halted, and the “Container” click event is not triggered.

3. The Intriguing World of Fibonacci Series in JavaScript

As we navigate the realm of event bubbling, let’s take a moment to explore the fascinating concept of the Fibonacci series in JavaScript.

3.1 Understanding the Fibonacci Series

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence begins: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

3.2 Generating the Fibonacci Series in JavaScript

Let’s implement a function to generate the Fibonacci series in JavaScript:

function generateFibonacciSeries(n) 
  const fibonacciSeries = [0, 1];
  for (let i = 2; i < n; i++) 
    const nextNumber = fibonacciSeries[i - 1] + fibonacciSeries[i - 2];
    fibonacciSeries.push(nextNumber);
  

  return fibonacciSeries;


const n = 10;
const fibonacciSeries = generateFibonacciSeries(n);
console.log(`Fibonacci series of length $n:`, fibonacciSeries);

In this code snippet, we create a function generateFibonacciSeries that generates the Fibonacci series up to a specified length n. The function utilises a loop to calculate and populate the series.

4. Embracing the Essence of Event Bubbling

Returning to the concept of event bubbling, let’s delve deeper into its significance and applications.

4.1 Event Delegation: A Practical Application

Event bubbling enables a powerful technique known as event delegation. Event delegation involves attaching a single event handler to a parent element, allowing you to handle events for multiple child elements. This approach is particularly useful when dealing with dynamically added elements or optimising performance.

Consider the scenario where you have a list of items, each with a “Delete” button:

<ul id="item-list">
  <li>Item 1 <button class="delete">Delete</button></li>
  <li>Item 2 <button class="delete">Delete</button></li>
  <li>Item 3 <button class="delete">Delete</button></li>
</ul>

Instead of attaching a separate event handler to each “Delete” button, you can use event delegation:

document.getElementById("item-list").addEventListener("click", function (event) 
  if (event.target.classList.contains("delete")) 
    const listItem = event.target.closest("li");
    listItem.remove();
  
);

In this example, the event handler is attached to the “item-list” element. When a “Delete” button is clicked, the event bubbles up to the “item-list” level, and the handler checks if the clicked element has the “delete” class. If it does, the corresponding list item is removed.

4.2 Preventing Event Bubbling

While event bubbling is often desirable, there are scenarios where you might want to prevent it. This is where event.stopPropagation() comes into play. By invoking this method within an event handler, you can halt the propagation of the event to parent elements.

document.getElementById("inner").addEventListener("click", function (event) 
  console.log("Inner element clicked!");
  event.stopPropagation();
);

document.getElementById("middle").addEventListener("click", function (event) 
  console.log("Middle element clicked!");
);

document.getElementById("outer").addEventListener("click", function (event) 
  console.log("Outer element clicked!");
);

In this example, clicking the “inner” element triggers its event handler, but the propagation is stopped, preventing the “middle” and “outer” event handlers from executing.

5. Conclusion

Event bubbling in JavaScript, a fundamental concept in JavaScript’s event propagation mechanism, empowers developers to create efficient and dynamic user interactions. By understanding how events bubble up through the DOM tree, you gain the ability to harness event delegation, optimise performance, and create cleaner and more maintainable code.

In parallel, the Fibonacci series in JavaScript showcases the language’s mathematical capabilities, allowing you to generate sequences that find applications in various mathematical and computational scenarios.

As you navigate the landscape of JavaScript, remember that mastering event bubbling and related concepts is essential for creating interactive and responsive web applications. By leveraging event bubbling and honing your skills, you unlock the potential

In case you have found a mistake in the text, please send a message to the author by selecting the mistake and pressing Ctrl-Enter.



Source link

Share360Tweet225SendSendShare63Pin81
Admin

Admin

Related Posts

Best Black Friday deals at Best Buy: TVs, laptops, headphones, and mor…
Firmware

Best Black Friday deals at Best Buy: TVs, laptops, headphones, and mor…

November 17, 2023

Table of Contents Table of Contents TV deals Apple deals Laptop deals Tablet deals Monitor deals Gaming deals Headphone and earbud deals Smartwatch deals Dyson...

Joe Biden’s top climate adviser on how climate change will shape the U…
Firmware

Joe Biden’s top climate adviser on how climate change will shape the U…

November 17, 2023

Climate change is already taking its toll on the US economy, according to the most sweeping national assessment yet that was published earlier this week....

Will 2024 be a bounce-back year for startups?
Firmware

Will 2024 be a bounce-back year for startups?

November 17, 2023

In 2021 and early 2022, startups experienced a time of wild optimism. Capital was still plentiful and cheap, and enterprise buyers were heavily into experimentation,...

This is the Nothing Phone 2’s Best Black Friday Deal, But It’s Limited
Firmware

This is the Nothing Phone 2’s Best Black Friday Deal, But It’s Limited

November 17, 2023

Nothing launched its Black Friday sale today through its own website, where you’ll find a minimum of $50 off the Nothing Phone (2), with discounts...

X’s New Job Search Tool Now Accessible Through Web
Firmware

X’s New Job Search Tool Now Accessible Through Web

November 17, 2023

2023-11-17 13:36:33SummaryX's job search tool, which has been in beta testing since August, is now live on the web and available to all users. Although...

Dexcom launches eye-opening diabetes research around HCL perceptions –…
Firmware

Dexcom launches eye-opening diabetes research around HCL perceptions –…

November 17, 2023

Newsletter Sed ut perspiciatis unde. Subscribe Dexcom, a global leader in real-time continuous glucose monitoring for people with diabetes, have released new market research which...

Tuft and Paw Porto Cat Carrier Review: Folding and Versatile
Firmware

Tuft and Paw Porto Cat Carrier Review: Folding and Versatile

November 17, 2023

When all zipped up, the Porto kind of looks like a sophisticated duffle bag and there is a luggage handle pass-through on the back. When...

Bluesky is now 2 million users strong, with big plans ahead
Firmware

Bluesky is now 2 million users strong, with big plans ahead

November 17, 2023

X rival and social media platform Bluesky now boasts over 2 million users, as announced by the team on Thursday. A year after its creation,...

Discord is shutting down its AI chatbot Clyde
Firmware

Discord is shutting down its AI chatbot Clyde

November 17, 2023

Discord is shutting down Clyde, its experimental AI chatbot. In a support note, Discord says the chatbot will be “deactivated” at the end of the...

Signal details costs of keeping its private messaging service alive
Firmware

Signal details costs of keeping its private messaging service alive

November 17, 2023

What price privacy? End-to-end encrypted (E2EE) messaging app Signal has put out an interesting overview of the costs required to develop and maintain its pro-privacy...

Please login to join discussion
Best Black Friday deals at Best Buy: TVs, laptops, headphones, and mor…
Firmware

Best Black Friday deals at Best Buy: TVs, laptops, headphones, and mor…

by Admin
November 17, 2023
0
990

Table of Contents Table of Contents TV deals Apple deals Laptop deals Tablet deals Monitor deals Gaming deals Headphone and...

Read more
Tim Allen’s ‘The Santa Clauses’ Season 2 Highlights Jesus’ Birth – ‘Al…
Politics

Tim Allen’s ‘The Santa Clauses’ Season 2 Highlights Jesus’ Birth – ‘Al…

by Admin
November 17, 2023
0
990

The second season of Tim Allen’s television series “The Santa Clauses” premiered earlier this month, and it defied the largely...

Read more
Joe Biden’s top climate adviser on how climate change will shape the U…
Firmware

Joe Biden’s top climate adviser on how climate change will shape the U…

by Admin
November 17, 2023
0
990

Climate change is already taking its toll on the US economy, according to the most sweeping national assessment yet that...

Read more
Ron DeSantis Is Having His Secret Police Trained By Company Employing …
Politics

Ron DeSantis Is Having His Secret Police Trained By Company Employing …

by Admin
November 17, 2023
0
990

In case there is any doubt of the kind of country Governor Ron DeSantis (R-Fla) has in mind for the...

Read more
Fouaad

fouaad.com is an exploration of philosophy, science, art, design, business, technology, and war. Dive into profound questions, cutting-edge science, creative expression, business innovations, and the complexities of war, as we journey through the rich tapestry of our world's interconnected themes.

Follow fouaad on X!

Categories

  • Books (14)
  • Finance (154)
  • Firmware (1,204)
  • Hardware (1,204)
  • How-To (138)
  • Life (8)
  • Philosophy (25)
  • Politics (913)
  • Tech (1,201)
  • Theory (17)
  • War (177)
  • Work (8)
  • Writing (129)

Tags

albert camus conflict deontology determinism diogenes ethics fatalism greek philosophy indian philosophy metaphysics millitary morality moral principles philosophers philosophy philosopphy politics putin robert lynd socrates tesla war
  • About
  • Write
  • Privacy & Policy
  • Contact

© 2023 fouaad.com All RIghts Reserved!

No Result
View All Result
  • Home
  • Shop
  • Write for us
  • Contact
  • Philosophy
    • Theory
    • Books
  • How-To
    • Work
    • Life
    • Write
    • Finance
  • Tech
    • Hardware
    • Firmware
  • War
  • Politics

© 2023 fouaad.com All RIghts Reserved!

Welcome Back!

OR

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
Ads Blocker Image Powered by Code Help Pro

Support Free Content. Please Disable Your Ad Blocker.

 Please support us by disabling your ad blocker extension :)

Refresh
This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.