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:
HTML DOM addEventListener() Method
Next article icon

JavaScript addEventListener() with Examples

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The addEventListener() method is used to attach an event handler to a HTML document.

Syntax:

element.addEventListener(event, listener, useCapture);

Parameters:

  • event: event can be any valid JavaScript event. Events are used without “on” prefixes like using “click” instead of “onclick” or “mousedown” instead of “onmousedown”.
  • listener(handler function): It can be a JavaScript function that responds to the event occurring.
  • useCapture: It is an optional parameter used to control event propagation. A boolean value is passed where “true” denotes the capturing phase and “false” denotes the bubbling phase.

Why Use addEventListener()?

  • Multiple Event Handlers: Unlike the traditional way of assigning events directly (e.g., element.onclick = function() {}), addEventListener() allows multiple handlers for the same event.
  • Flexibility: You can easily remove event listeners or add them dynamically based on conditions.
  • Control Over Event Propagation: With the useCapture parameter, you can manage how events propagate through the DOM tree.

Example 1: In this example, we will display text on the webpage after clicking on the button.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width,                     initial-scale=1.0">     <title>JavaScript addEventListeners</title> </head>  <body>     <button id="try">Click here</button>     <h1 id="text"></h1>     <script>         document.getElementById("try").addEventListener("click", function () {             document.getElementById("text").innerText = "GeeksforGeeks";         });     </script> </body>  </html> 

Output: 

JavaScript addEventListener() with Examples

JavaScript addEventListener() with Examples

Example 2: In this example, two events “mouseover” and “mouseout” are added to the same element. If the text is hovered over then “mouseover” event occurs and the RespondMouseOver function is invoked, similarly for “mouseout” event RespondMouseOut function is invoked. 

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width,     initial-scale=1.0">     <title>JavaScript addEventListeners</title> </head>  <body>     <button id="clickIt">Click here</button>      <p id="hoverPara">Hover over this Text !</p>       <b id="effect"></b>      <script>         const x = document.getElementById("clickIt");         const y = document.getElementById("hoverPara");          x.addEventListener("click", RespondClick);         y.addEventListener("mouseover", RespondMouseOver);         y.addEventListener("mouseout", RespondMouseOut);          function RespondMouseOver() {             document.getElementById("effect").innerHTML +=                 "MouseOver Event" + "<br>";         }          function RespondMouseOut() {             document.getElementById("effect").innerHTML +=                 "MouseOut Event" + "<br>";         }          function RespondClick() {             document.getElementById("effect").innerHTML +=                 "Click Event" + "<br>";         }     </script> </body>  </html> 

Output: 

JavaScript addEventListener() with Examples

JavaScript addEventListener() with Examples

Understanding Event Propagation with useCapture

In JavaScript, events propagate in two phases: the capturing phase and the bubbling phase.

  • Capturing Phase (useCapture = true): The event is captured as it descends from the document root towards the target element.
  • Bubbling Phase (useCapture = false): The event bubbles up from the target element back to the document root.

By specifying true for the useCapture parameter, you can handle the event in the capturing phase rather than the bubbling phase. This gives you control over how events are managed in nested elements.



Next Article
HTML DOM addEventListener() Method

V

vivekkothari
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Methods

Similar Reads

  • Nashorn JavaScript Engine in Java with Examples
    Nashorn: Nashorn is a JavaScript engine which is introduced in JDK 8. With the help of Nashorn, we can execute JavaScript code at Java Virtual Machine. Nashorn is introduced in JDK 8 to replace existing JavaScript engine i.e. Rhino. Nashorn is far better than Rhino in term of performance. The uses o
    4 min read
  • HTML DOM addEventListener() Method
    The addEventListener() method attaches an event handler to the specified element. Syntax: element.addEventListener(event, function, useCapture) Note: The third parameter use capture is usually set to false as it is not used. Below program illustrates the DOM addEventListener(): Example: <!DOCTYPE
    1 min read
  • Difference between addEventListener and onclick in JavaScript
    In JavaScript, both addEventListener() and onclick are used to handle events like clicks, but they function differently. While addEventListener() allows multiple event listeners and better control over event propagation, onclick is limited to a single event handler and gets overwritten. addEventList
    4 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
  • Explain about EventHandler with Example
    Event handlers are the properties in the browser or DOM API that handles the response to an event. Let us understand this with an example when we click on any virtual button of the browser a particular task gets executed for us, and eventually, the browser responds to your trigger with some result,
    3 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
  • 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
  • How to Fix "Error Message: addEventListener is Not a Function" in JavaScript?
    The "addEventListener is not a function" error in JavaScript typically occurs when you're trying to use the addEventListener() method on something that isn’t an event target, like a null value or an object that doesn’t have this method. Here's how you can troubleshoot and fix it: 1. Check the DOM El
    2 min read
  • Manipulating HTML Elements with JavaScript
    JavaScript is a powerful language that can be used to manipulate the HTML elements on a web page. By using JavaScript, we can access the HTML elements and modify their attributes, styles, and content. This allows us to create dynamic and interactive web pages. Methods to Identify the elements to man
    5 min read
  • JavaScript Programming Examples
    JavaScript is a dynamic, widely-used programming language that plays a pivotal role in modern web development. Whether you're a beginner or an experienced developer, practicing JavaScript programming examples is an excellent way to refine your coding skills, enhance your problem-solving abilities, a
    15 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