JavaScript Events & Propagation πŸš€ | JavaScript Journey | In Hindi | Death Code - DeathCode

Events and Propagation in JavaScript

A comprehensive guide to understanding events and event propagation in JavaScript.

1. What are Events?

In JavaScript, an event is an action or occurrence that happens in the browser, which the JavaScript code can respond to. Events can be triggered by user interactions, such as clicks, keyboard presses, or mouse movements, as well as by other actions like page loading or resizing.

2. Types of Events

Event Type Description
Click Triggered when an element is clicked.
Mouseover Triggered when the mouse pointer is moved over an element.
Keydown Triggered when a key is pressed down.
Load Triggered when the page or an image is fully loaded.
Resize Triggered when the window is resized.

3. Event Propagation

Event propagation is the way in which events travel through the DOM. There are two phases of event propagation:

  • Bubbling: The event starts from the target element and bubbles up to the root of the DOM.
  • Capturing: The event starts from the root and travels down to the target element.

By default, events bubble up, but you can control this behavior using the stopPropagation() method.

4. Example of Event Handling and Propagation

Here’s an example that demonstrates event handling and propagation:

const ul = document.getElementById("fruits");
const fruits = document.querySelectorAll("#fruit");
 
ul.addEventListener("click", function(ev) {
    console.log("Parent");
    ev.stopPropagation();
}, true);
 
fruits.forEach(function(fruit) {
    fruit.addEventListener('click', function(ev) {
        console.log(ev.target.innerText);
        ev.stopPropagation();
    });
});

In this example:

  • When a fruit is clicked, it logs the fruit's name and stops the event from bubbling up to the parent ul.
  • If the ul is clicked, it logs "Parent" but does not trigger if a fruit is clicked due to stopPropagation().

5. Project: Color Circles

In this project, we create color circles that change the background color of the page when clicked. Here’s the HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Color Circles</title>
    <style>
        /* Dark theme background color */
        body {
            font -family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #2c3e50;  /* Dark background */
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: #ecf0f1; /* Light text color for contrast */
        }
 
        /* Heading style */
        h1 {
            text-align: center;
            font-size: 2em;
            color: #ecf0f1;  /* Light color for the heading */
        }
 
        /* Style for the unordered list */
        #colors {
            list-style-type: none;
            padding: 0;
            display: flex;
            justify-content: center;
            gap: 20px;
        }
 
        /* Circle styles */
        .color-circle {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: inline-block;
            transition: all 0.3s ease; /* Smooth hover effect */
        }
 
        #red {
            background-color: #e74c3c;  /* Dark Red */
        }
 
        #blue {
            background-color: #3498db;  /* Dark Blue */
        }
 
        #green {
            background-color: #2ecc71;  /* Dark Green */
        }
        #grey {
            background-color: #3b3b3b;  /* Dark Grey */
        }
 
        #yellow {
            background-color: #f39c12;  /* Dark Yellow */
        }
 
        #purple {
            background-color: #9b59b6;  /* Dark Purple */
        }
 
        /* Hover effect with border */
        .color-circle:hover {
            border: 3px solid #ecf0f1;  /* Light border on hover */
            transform: scale(1.1);  /* Slight zoom effect */
        }
    </style>
</head>
<body>
 
    <div>
        <h1>Color Circles</h1>
        <ul id="colors">
            <li id="red" class="color-circle"></li>
            <li id="blue" class="color-circle"></li>
            <li id="green" class="color-circle"></li>
            <li id="yellow" class="color-circle"></li>
            <li id="purple" class="color-circle"></li>
            <li id="grey" class="color-circle"></li>
        </ul>
    </div>
    <script src="project.js"></script>
</body>
</html>

In this HTML code:

  • We create a list of color circles using <ul> and <li> elements.
  • Each circle has a unique ID corresponding to its color.
  • The CSS styles define the appearance and hover effects of the circles.

Now, let's look at the JavaScript code:

const colors = document.querySelector("#colors");
 
for(let i = 0; i < colors.children.length; i++) {
    colors.children[i].addEventListener('click', (ev) => {
        document.body.style.backgroundColor = ev.target.id;
    });
}

In this JavaScript code:

  • We select the #colors element and loop through its children (the color circles).
  • For each circle, we add a click event listener that changes the document.body's background color to the ID of the clicked circle.
Β© 2024 DeathCode. All Rights Reserved.