Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to trigger events in JavaScript ?
Next article icon

JavaScript Custom Events

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Events are used in almost every web application, such as the onclick event is used to execute some code when the user clicks on something. There are already numerous built-in events available to be used, but what if we want our custom event? Let us suppose we are creating a chat application, and we want to execute some code when the end-user sends some message. There is no built-in event to detect that. Here we need a custom event that can handle such custom scenarios.

Creating a Custom Event:

To create a custom event we use the Event constructor or CustomEvent interface. The Event constructor creates an Event and CustomEvent creates an Event with more functionality.

The below steps are followed to create one using a new Event.

  • We create an event using the Event constructor.
  • We listen to this event using the addEventListener() method.
  • We trigger or dispatch the event using element.dispatchEvent(eventName) method.
  • A custom Event named start has now been created.

Syntax: 

// To assign event
const startEvent = new Event("start");
// To trigger the event Listener
document.addEventListener("start", () => {
console.log("The start event was triggered")
});
// To trigger the Event
document.dispatchEvent(startEvent);

Example: We are creating an event that is triggered when the value of x is 5.

HTML
<!DOCTYPE html> <html>  <head>     <title>JavaScript custom Events</title> </head>  <body>     <script>         let x = 5;         const event = new Event("start");          document.addEventListener('start', () => {             console.log("Start event triggered")         });          if (x == 5) {             document.dispatchEvent(event);         }     </script> </body>  </html> 

Output:

"Start event triggered"

Creating a custom event using CustomEvent:

Creating custom events using the CustomEvent interface has an advantage as it can send custom data. The below steps are followed in order to create a new CustomEvent.

  • We create a custom event using the CustomEvent constructor.
  • This takes two arguments, the first is the name of the event and the second is an object that contains the data. The property name inside the object name should be named detail otherwise it won’t work.
  • We create a listener for this event.
  • We trigger or dispatch the event.
  • A custom event that contains data has been created.

Syntax: 

// To assign event
const event = new CustomEvent("start", {
detail: {
platform : "GeeksforGeeks"
}
});
// To trigger the event Listener
document.addEventListener('start', (e)=>{
console.log(
`start event triggered on platform :
${e.detail.platform}`
);
});
// To trigger the Event
document.dispatchEvent(event);

Example: In this example, we are creating a custom event that triggers when the value of x is 5. 

HTML
<!DOCTYPE html> <html>  <head>     <title>JavaScript custom Events</title> </head>  <body>     <script>         let x = 5;         const event = new CustomEvent("start", {             detail: {                 platform: "GeeksforGeeks"             }         });          document.addEventListener('start', (e) => {             console.log(                 `Start event triggered on platform          ${e.detail.platform}`             );         })          if (x == 5) {             document.dispatchEvent(event);         }     </script> </body>  </html> 

Output:

Start event triggered on platform GeeksforGeeks

Note: We are dispatching the event directly from the document using document.dispatchEvent(‘start’), but one can dispatch the event from any needed element like myBtn.dispatchEvent(‘start’).



Next Article
How to trigger events in JavaScript ?
author
devi_johns
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Intellipaat
  • JavaScript-Properties
  • TCS-coding-questions

Similar Reads

  • JavaScript Events
    JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself. [GFGTABS] HTML <html> <script> function myFun() { document.getElementById( "gfg").innerHTML = "GeeksforGeeks"; } </
    3 min read
  • What are JavaScript Events ?
    JavaScript Events are the action that happens due to the interaction of the user through the browser with the help of any input field, button, or any other interactive element present in the browser. Events help us to create more dynamic and interactive web pages. Also, these events can be used by t
    7 min read
  • JavaScript onmouse Events
    The onmouse event is used to define the operation using the mouse. JavaScript onmouse events are: onmouseover and onmouseoutonmouseup and onmousedownonmouseenter and onmouseleave JavaScript onmouseover and onmouseout: The onmouseover and onmouseout events occur when the mouse cursor is placed over s
    1 min read
  • JavaScript onclick Event
    The onclick event generally occurs when the user clicks on an element. It's a fundamental event handler in JavaScript, triggering actions or executing functions in response to user interaction, facilitating dynamic and interactive web functionality. In JavaScript, we can use the onclick function in
    2 min read
  • How to trigger events in JavaScript ?
    JavaScript is a high-level, interpreted, dynamically typed client-side scripting language. While HTML is static and defines the structure of a web page, JavaScript adds interactivity and functionality to HTML elements. This interaction is facilitated through events, which are actions or occurrences
    2 min read
  • JavaScript contextmenu MouseEvent
    When we click the right mouse button on our desktop, a menu-like box appears and this box is called the context menu. In JavaScript, a context menu event runs when a user tries to open a context menu. This can be done by clicking the right mouse button. This article demonstrates executing any operat
    1 min read
  • React Events
    In React, events are actions that occur within an application, such as clicking a button, typing in a text field, or moving the mouse. React provides an efficient way to handle these actions using its event system. Event handlers like onClick, onChange, and onSubmit are used to capture and respond t
    8 min read
  • How to Add event listener to Button in JavaScript ?
    In web development adding an event listener to a button is a common task that allows us to execute JavaScript code in response to user interactions, such as clicks. This helps us to create interactive and flexible web pages. Using addEventListener()The addEventListener method is a versatile and wide
    1 min read
  • How to Handle JavaScript Events in HTML ?
    An Event is an action or occurrence recognized by the software. It can be triggered by the user or the system. Mostly Events are used on buttons, hyperlinks, hovers, page loading, etc. All this stuff gets into action(processed) with the help of event handlers. In this article, you will learn about d
    3 min read
  • What is the best way to add an event in JavaScript ?
    Javascript has events to provide a dynamic interface to a webpage. These events are hooked to elements in the Document Object Model(DOM). There are three ways to assign an event handler:  HTML event handler attributeHTML DOM propertyHTML DOM addEventListener() methodThe best way to add an event in J
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences