Menu

Log in

Sign up

From beginner to master of web design, coding, infrastructure operation, business development and marketing

  • COURSES
  • HTML & CSS Introduction
  • HTML & CSS Coding with AI
  • Linux Introduction
  • Docker Basics
  • Git & GitHub Introduction
  • JavaScript Coding with AI
  • Django Introduction
  • AWS Basics
  • Figma Introduction
  • SEO Tutorial for Beginners
  • SEO with AI
  • OTHERS
  • About
  • Terms of Service
  • Privacy Policy

© 2024 D-Libro. All Rights Reserved

JavaScript Coding with AIChapter 7. Manipulating Web Pages With Javascript

JavaScript Custom Events

JavaScript Custom Events

Javascript Custom Events

JavaScript custom events provide a way for developers to define their own event behaviors, enabling a more flexible approach to managing interactions within web applications. Unlike built-in events such as click or keyup, custom events allow you to handle scenarios specific to your application's needs. This feature plays a crucial role in enhancing the modularity and maintainability of complex JavaScript projects.

In this section, we’ll cover the following topics:

  • What Are JavaScript Custom Events?
  • How to Create and Use a Custom Event
  • Innovative Use Cases for Custom Events with AI Assistance
  • Best Practices for Using Custom Events

What Are JavaScript Custom Events?

Custom events in JavaScript are developer-defined events that extend beyond the scope of standard browser-supported actions. They enable you to create unique event listeners and dispatchers that interact seamlessly with your application logic, offering more control and customization.

Comparing Built-In Events and Custom Events

Built-in events, like onclick or onload, cater to pre-defined user actions and system events. Custom events, however, allow you to define specific behaviors, such as tracking custom user interactions or orchestrating complex workflows. This flexibility makes them a valuable tool for developers.

When to Use Custom Events

Custom events are ideal when handling unique workflows, decoupling application logic, or managing interactions between loosely coupled components. They empower developers to maintain cleaner, modular, and more scalable codebases.

How to Create and Use a Custom Event

Custom events in JavaScript allow developers to define and manage unique event workflows. The process of creating and using custom events involves defining the event, dispatching it, and responding with an event listener.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Basic Custom Event</title>
</head>
<body>
  <button id="triggerButton">Trigger Event</button>
  <div id="output"></div>
  <script>
    const button = document.getElementById("triggerButton");
    const output = document.getElementById("output");
    // Add an event listener to respond to the custom event
    output.addEventListener("customAction", (event) => {
      output.textContent = `Custom Event Triggered: ${event.detail.message}`;
    });
    // Dispatch the custom event when the button is clicked
    button.addEventListener("click", () => {
      const customEvent = new CustomEvent("customAction", {
        detail: { message: "Hello from the custom event!" },
      });
      output.dispatchEvent(customEvent);
    });
  </script>
</body>
</html>

Key Points in This Example:

  • Event Creation: The CustomEvent constructor defines the customAction event and includes a detail object with custom data.
  • Event Dispatching: The custom event is dispatched on the output element when the button is clicked.
  • Event Handling: An event listener on the output element responds to the custom event and updates the content dynamically.

Use Cases for Custom Events with AI Assistance

Custom events can be creatively employed in AI-driven scenarios to enhance interactivity and functionality.

Preparing for Practice Files
This course takes a hands-on approach, allowing you to apply the techniques covered in real-world scenarios. We'll be using a structured folder layout. Before proceeding with the examples, please ensure the following files are prepared:

/your-project-folder/  
  |─07-14-javascript-custom-events/ (<- sub-folder)  
    |─ example-1.css  
    |─ example-1.html  
    |─ example-1.js  
    |─ example-2.css  
    |─ example-2.html  
    |─ example-2.js
    |─ example-3.css  
    |─ example-3.html  
    |─ example-3.js

For your convenience, these files are also available on our GitHub repository.

AI Case 1: Triggering Multiple Actions with One Click

Real-time feedback is crucial for modern applications. This example demonstrates triggering multiple actions with a single button click.

Sample AI prompt:

Create a button that triggers two custom events. Display messages for each event in separate areas when the button is clicked.

Include:

  • HTML (example-1.html) for a clean layout with two display areas. Instructional text above the button.
  • CSS (example-1.css) for a horizontally centered UI with modern styling.
  • JavaScript (example-1.js) to trigger and handle the custom events.

Sample code output:

07-14-javascript-custom-events/example-1.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Trigger Multiple Actions</title>
    <link rel="stylesheet" href="example-1.css" />
  </head>
  <body>
    <div class="container">
      <h2>Trigger Multiple Actions</h2>
      <p class="instructions">
        Click the button below to trigger two custom actions.
      </p>
      <button id="triggerButton">Click Me</button>
      <div id="message1" class="message"></div>
      <div id="message2" class="message"></div>
    </div>
    <script src="example-1.js"></script>
  </body>
</html>

07-14-javascript-custom-events/example-1.css
/* General Styles */
body {
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.container {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
  width: 300px;
}

h2 {
  margin-top: 0;
  color: #333333;
}

.instructions {
  font-size: 0.9em;
  color: #777777;
}

button {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1em;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.message {
  margin-top: 15px;
  padding: 10px;
  font-size: 0.9em;
  color: #444;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f8f9fa;
}

07-14-javascript-custom-events/example-1.js
const button = document.getElementById("triggerButton");
const message1 = document.getElementById("message1");
const message2 = document.getElementById("message2");

button.addEventListener("click", () => {
  const event1 = new CustomEvent("customAction1", {
    detail: { message: "Action 1 Triggered!" },
  });
  const event2 = new CustomEvent("customAction2", {
    detail: { message: "Action 2 Triggered!" },
  });

  message1.dispatchEvent(event1);
  message2.dispatchEvent(event2);
});

message1.addEventListener("customAction1", (e) => {
  message1.textContent = e.detail.message;
});

message2.addEventListener("customAction2", (e) => {
  message2.textContent = e.detail.message;
});

Instructions to see the results:
Save the code above in each file.
Open the HTML file in your browser to view custom updates on the webpage.
To see how the code works, you can also check out the link below.

Demo Web Page 36

AI Case 2: Triple-Click Behavior with Custom Events

This example demonstrates how to handle a triple-click interaction using custom events.

Sample AI prompt:

Create a button that triggers a special message after three consecutive clicks within one second.

Include:

  • HTML (example-2.html) for the button and a display area for the message. Instructional text explaining the interaction.
  • CSS (example-2.css) for a centered UI with modern styling.
  • JavaScript (example-2.css) to count clicks and dispatch a custom event when the triple-click is detected.

Sample code output:

07-14-javascript-custom-events/example-2.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Triple-Click Event</title>
    <link rel="stylesheet" href="example-2.css" />
  </head>
  <body>
    <div class="container">
      <h2>Triple-Click Event</h2>
      <p class="instructions">
        Click the button below three times in a row to trigger a special event.
      </p>
      <button id="tripleClickButton">Triple-Click Me</button>
      <p id="message" class="message"></p>
    </div>
    <script src="example-2.js"></script>
  </body>
</html>

07-14-javascript-custom-events/example-2.css
/* Same styles as case 1 for consistency */
body {
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.container {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
  width: 300px;
}

h2 {
  margin-top: 0;
  color: #333333;
}

.instructions {
  font-size: 0.9em;
  color: #777777;
}

button {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1em;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.message {
  margin-top: 15px;
  padding: 10px;
  font-size: 0.9em;
  color: #28a745;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f8f9fa;
}

07-14-javascript-custom-events/example-2.js
const button = document.getElementById("tripleClickButton");
const message = document.getElementById("message");

let clickCount = 0;
let clickTimer = null;

button.addEventListener("click", () => {
  clickCount++;
  clearTimeout(clickTimer);
  clickTimer = setTimeout(() => (clickCount = 0), 1000);

  if (clickCount === 3) {
    const tripleClickEvent = new CustomEvent("tripleClick");
    button.dispatchEvent(tripleClickEvent);
    clickCount = 0;
  }
});

button.addEventListener("tripleClick", () => {
  message.textContent = "Triple-click detected!";
});

Instructions to see the results:
Save the code above in each file.
Open the HTML file in your browser to view custom updates on the webpage.
To see how the code works, you can also check out the link below.

Demo Web Page 37

AI Case 3: Tracking Custom User Interactions with Custom Events

Custom events are highly effective for tracking and managing complex user interactions. In this example, we use custom events to track when a user hovers over a box three times and display a message.

Sample AI prompt:

Create a box that tracks when a user hovers over it three times. Each hover should increment a counter, and a custom event should be triggered when the count reaches three.

Include:

  • HTML (example-3.html) with instructional text.
  • CSS (example-3.css) to style a hover box UI and display the counter clearly.
  • JavaScript (example-3.js) to manage hover counts and trigger the custom event.

Sample code output:

07-14-javascript-custom-events/example-3.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hover Interaction Tracker</title>
    <link rel="stylesheet" href="example-3.css" />
  </head>
  <body>
    <div class="container">
      <h2>Hover Interaction Tracker</h2>
      <p class="instructions">
        Hover over the box below three times to trigger a custom event.
      </p>
      <div id="hoverBox" class="hover-box"></div>
      <p id="hoverCounter" class="hover-counter">Hover Count: 0</p>
      <p id="hoverMessage" class="hover-message"></p>
    </div>
    <script src="example-3.js"></script>
  </body>
</html>

07-14-javascript-custom-events/example-3.css
/* General Styles */
body {
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.container {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
  width: 300px;
}

h2 {
  margin-top: 0;
  color: #333333;
}

.instructions {
  font-size: 0.9em;
  color: #777777;
}

.hover-box {
  width: 150px;
  height: 150px;
  background-color: #007bff;
  margin: 20px auto;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.hover-box:hover {
  background-color: #0056b3;
}

.hover-counter {
  margin-top: 10px;
  font-size: 1em;
  font-weight: bold;
  color: #333333;
}

.hover-message {
  margin-top: 10px;
  font-size: 0.9em;
  color: #28a745;
  font-weight: bold;
}

07-14-javascript-custom-events/example-3.js
const hoverBox = document.getElementById("hoverBox");
const hoverCounter = document.getElementById("hoverCounter");
const hoverMessage = document.getElementById("hoverMessage");

let hoverCount = 0;

// Listen for hover events
hoverBox.addEventListener("mouseenter", () => {
  hoverCount++;
  hoverCounter.textContent = `Hover Count: ${hoverCount}`;

  // Trigger custom event on third hover
  if (hoverCount === 3) {
    const hoverEvent = new CustomEvent("threeHovers");
    hoverBox.dispatchEvent(hoverEvent);
  }
});

// Handle the custom threeHovers event
hoverBox.addEventListener("threeHovers", () => {
  hoverMessage.textContent = "You hovered 3 times! Event triggered!";
});

Instructions to see the results:
Save the code above in each file.
Open the HTML file in your browser to view custom updates on the webpage.
To see how the code works, you can also check out the link below.

Demo Web Page 38

Best Practices for Using Custom Events

Custom events are a powerful tool, but they should be used thoughtfully to maximize their effectiveness. Here are some best practices:

  • Use custom events for unique workflows: Leverage custom events to handle scenarios where built-in events cannot capture the specific behavior or interactions needed, such as orchestrating multiple component actions.
  • Avoid overcomplication: Rely on custom events only when built-in events fall short. Overusing custom events can make the code unnecessarily complex and harder to debug.
  • Maintain meaningful naming conventions: Use clear and descriptive names for your custom events to ensure their purpose is easily understood by other developers.
  • Document and communicate intent: Clearly document the use of custom events, including where and why they are used. This improves maintainability and aids collaboration in team environments.

By following these best practices, you can create maintainable, scalable, and efficient JavaScript applications that fully utilize the flexibility of custom events.

Reference links:

Creating and triggering events - Event reference | MDN

More Topics to Explore

Masking and Boolean Operations in Figma

Masking and Boolean Operations in Figma

Javascript Custom Events

Javascript Custom Events

Choosing Border Styles in CSS

border-style

nth-child

nth-child

Nesting Images in Hyperlinks

Add Hyperlinks to Images

Masking and Boolean Operations in Figma

Masking and Boolean Operations in Figma

Javascript Custom Events

Javascript Custom Events

Choosing Border Styles in CSS

border-style

nth-child

nth-child

Nesting Images in Hyperlinks

Add Hyperlinks to Images

Tags:

Event Handling

JavaScript Custom Events

AI Use Cases

Web Application Modularity

Best Practices for Developers

JavaScript Coding with AI
Course Content

Chapter 1. Key Javascript Concepts And Coding With AI

What Is Javascript?

Start Writing Javascript With AI Assistance

Javascript Basics

Chapter 2. Javascript Basic Syntax

Statements And Expressions

Variables

Case Sensitivity

Case Style For Javascript

Reserved Words

Escape Characters

Semi-Colons

Spaces And Indentation

Comments

Literals and Data Types

Arrays

Template Literal

Brackets

Chapter 3. Operators In Javascript

Arithmetic Operators

Increment And Decrement Operators

Assignment Operators

Comparison Operators

Conditional Operators

Logical Operators

Logical Assignment Operators

Nullish Coalescing Operator

Optional Chaining

Three Dots in JavaScript

Chapter 4. Control Statements In Javascript

If Statement

Switch Statement

While Statement

For Statement

Chapter 5. Functions In Javascript

How To Create A Function

Functions With Default Parameter

Return Values

Variable Scope

Function Hoisting

This in JavaScript

Anonymous Function

Arrow Function

Higher-Order Function

Chapter 6. Objects, Methods, And Classes In Javascript

Objects

Methods

Array Methods

Classes

Immutable and Mutable Data Types

What Is JSON?

Chapter 7. Manipulating Web Pages With Javascript

BOM And DOM

getElementBy vs. querySelector

Event Handler And Event Listener

Event Object

Mouse Events

Keyboard Events

Focus And Blur Events

Form Events

Window Events

Touch Events

Drag And Drop Events

Animation Events

Media Events, Network Events, and More

Javascript Custom Events

Chapter 8. Web API And Ajax Javascript Coding

What Are The HTTP Methods?

What Is Ajax?

Implementing Web APIs

Chapter 9. Modules And Libraries In Javascript

Javascript Libraries And Frameworks

NPM: Javascript Package Manager

How To Use jQuery

Chapter 10. Browser Storage in JavaScript

Local Storage

Session Storage

Cookies

Chapter 11. Building Web Applications in JavaScript

Node.js and Express.js

Database Integration: Mongo DB

Developing a Chat Application

Canvas HTML Tag and JavaScript

Creating an Online Drawing Tool

Chapter 1. Key Javascript Concepts And Coding With AI

What Is Javascript?

Start Writing Javascript With AI Assistance

Javascript Basics

Chapter 2. Javascript Basic Syntax

Statements And Expressions

Variables

Case Sensitivity

Case Style For Javascript

Reserved Words

Escape Characters

Semi-Colons

Spaces And Indentation

Comments

Literals and Data Types

Arrays

Template Literal

Brackets

Chapter 3. Operators In Javascript

Arithmetic Operators

Increment And Decrement Operators

Assignment Operators

Comparison Operators

Conditional Operators

Logical Operators

Logical Assignment Operators

Nullish Coalescing Operator

Optional Chaining

Three Dots in JavaScript

Chapter 4. Control Statements In Javascript

If Statement

Switch Statement

While Statement

For Statement

Chapter 5. Functions In Javascript

How To Create A Function

Functions With Default Parameter

Return Values

Variable Scope

Function Hoisting

This in JavaScript

Anonymous Function

Arrow Function

Higher-Order Function

Chapter 6. Objects, Methods, And Classes In Javascript

Objects

Methods

Array Methods

Classes

Immutable and Mutable Data Types

What Is JSON?

Chapter 7. Manipulating Web Pages With Javascript

BOM And DOM

getElementBy vs. querySelector

Event Handler And Event Listener

Event Object

Mouse Events

Keyboard Events

Focus And Blur Events

Form Events

Window Events

Touch Events

Drag And Drop Events

Animation Events

Media Events, Network Events, and More

Javascript Custom Events

Chapter 8. Web API And Ajax Javascript Coding

What Are The HTTP Methods?

What Is Ajax?

Implementing Web APIs

Chapter 9. Modules And Libraries In Javascript

Javascript Libraries And Frameworks

NPM: Javascript Package Manager

How To Use jQuery

Chapter 10. Browser Storage in JavaScript

Local Storage

Session Storage

Cookies

Chapter 11. Building Web Applications in JavaScript

Node.js and Express.js

Database Integration: Mongo DB

Developing a Chat Application

Canvas HTML Tag and JavaScript

Creating an Online Drawing Tool

FAQ: JavaScript Custom Events

What Are JavaScript Custom Events?

Custom events in JavaScript are developer-defined events that extend beyond the scope of standard browser-supported actions. They enable you to create unique event listeners and dispatchers that interact seamlessly with your application logic, offering more control and customization.

How Do Custom Events Differ from Built-In Events?

Built-in events, like onclick or onload, cater to pre-defined user actions and system events. Custom events, however, allow you to define specific behaviors, such as tracking custom user interactions or orchestrating complex workflows. This flexibility makes them a valuable tool for developers.

When Should You Use Custom Events?

Custom events are ideal when handling unique workflows, decoupling application logic, or managing interactions between loosely coupled components. They empower developers to maintain cleaner, modular, and more scalable codebases.

How Can You Create and Use a Custom Event?

Custom events in JavaScript allow developers to define and manage unique event workflows. The process involves defining the event, dispatching it, and responding with an event listener. For example, the CustomEvent constructor can define a custom event, which is then dispatched and handled by an event listener.

What Are Some Innovative Use Cases for Custom Events?

Custom events can be creatively employed in AI-driven scenarios to enhance interactivity and functionality. Examples include triggering multiple actions with one click, handling triple-click interactions, and tracking custom user interactions like hover counts.

What Are the Best Practices for Using Custom Events?

To maximize the effectiveness of custom events, use them for unique workflows, avoid overcomplication, maintain meaningful naming conventions, and document their use clearly. This approach ensures maintainable, scalable, and efficient JavaScript applications.