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:
JavaScript onclick Event
Next article icon

JavaScript Events

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself.

HTML
<html> <script>     function myFun() {         document.getElementById(             "gfg").innerHTML = "GeeksforGeeks";     } </script>  <body>     <button onclick="myFun()">Click me</button>     <p id="gfg"></p> </body> </html> 
  • The onclick attribute in the <button> calls the myFun() function when clicked.
  • The myFun() function updates the <p> element with id=”gfg” by setting its innerHTML to “GeeksforGeeks”.
  • Initially, the <p> is empty, and its content changes dynamically on button click.

Event Types

JavaScript supports a variety of event types. Common categories include:

  • Mouse Events: click, dblclick, mousemove, mouseover, mouseout
  • Keyboard Events: keydown, keypress, keyup
  • Form Events: submit, change, focus, blur
  • Window Events: load, resize, scroll

Common JavaScript Events

Event AttributeDescription
onclickTriggered when an element is clicked.
onmouseoverFired when the mouse pointer moves over an element.
onmouseoutOccurs when the mouse pointer leaves an element.
onkeydownFired when a key is pressed down.
onkeyupFired when a key is released.
onchangeTriggered when the value of an input element changes.
onloadOccurs when a page has finished loading.
onsubmitFired when a form is submitted.
onfocusOccurs when an element gets focus.
onblurFired when an element loses focus.
JavaScript
// Mouse Event document.addEventListener("mousemove", (e) => {     console.log(`Mouse moved to (${e.clientX}, ${e.clientY})`); });  // Keyboard Event document.addEventListener("keydown", (e) => {     console.log(`Key pressed: ${e.key}`); }); 
  • The mousemove event tracks cursor movement.
  • The keydown event captures key presses.

Event Handling Methods

1. Inline HTML Handlers

<button onclick="alert('Button clicked!')">Click Me</button>

2. DOM Property Handlers

let btn = document.getElementById("myButton");
btn.onclick = () => {
alert("Button clicked!");
};

3. addEventListener() (Preferred)

btn.addEventListener("click", () => {
alert("Button clicked using addEventListener!");
});

addEventListener() is the most versatile and recommended method as it supports multiple event listeners and removal of listeners.

Event Propagation

JavaScript events propagate in two phases:

  • Capturing Phase: Event travels from the root to the target element.
  • Bubbling Phase: Event travels from the target element back to the root.
JavaScript
document.querySelector("div").addEventListener("click", () => {     console.log("Div clicked"); }, true); // Capturing phase  button.addEventListener("click", (e) => {     console.log("Button clicked");     e.stopPropagation(); // Stops propagation }); 
  • Setting true in addEventListener makes it capture events during the capturing phase.
  • stopPropagation() halts further propagation.

Event Delegation

Event delegation allows you to handle events efficiently by attaching a single listener to a parent element.

JavaScript
document.querySelector("ul").addEventListener("click", (e) => {     if (e.target.tagName === "LI") {         console.log(`Clicked on item: ${e.target.textContent}`);     } }); 

Events are delegated to list, reducing the need to add listeners to each list items.

Preventing Default Behavior

Certain elements have default actions (e.g., links navigating to URLs). Use preventDefault() to override them.

JavaScript
document.querySelector("a").addEventListener("click", (e) => {     e.preventDefault();     console.log("Link click prevented"); }); 

preventDefault() stops the link from navigating.

Practical Applications

1. Form Validation

HTML
<html> <body>     <h2>Form Validation</h2>     <form id="example">         <input type="text" placeholder="Enter something" id="formInput" />         <button type="submit">Submit</button>     </form>     <script>         document.querySelector("#example").addEventListener("submit", (e) => {             let input = document.querySelector("#formInput");             if (!input.value) {                 e.preventDefault();                 alert("Input cannot be empty");             }         });     </script>  </body>  </html> 

2. Dynamic Content

HTML
<html>  <body>     <h2>Dynamic Content</h2>     <button id="button">Add Element</button>     <script>         document.querySelector("#button").addEventListener("click", () => {             let newDiv = document.createElement("div");             newDiv.textContent = "New Element Added";             newDiv.style.margin = "10px 0";             document.body.appendChild(newDiv);         });     </script>  </body>  </html> 

3. Interactive Lists

HTML
<html>  <body>     <h2>Interactive Lists</h2>     <ul id="lists">         <li>Interactive Item 1</li>         <li>Interactive Item 2</li>         <li>Interactive Item 3</li>     </ul>     <script>         let ul = document.querySelector("#lists");          ul.addEventListener("click", (e) => {             if (e.target.tagName === "LI") {                 e.target.style.backgroundColor = "yellow";             }         });     </script>  </body>  </html> 


Next Article
JavaScript onclick Event
author
mohit_negi
Improve
Article Tags :
  • JavaScript
  • Technical Scripter
  • Web Technologies
  • JavaScript-Events
  • JavaScript-Questions

Similar Reads

  • JavaScript Custom Events
    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
    3 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
  • 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 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
  • Event Queue in JavaScript
    JavaScript, being single-threaded, processes tasks sequentially, meaning it executes one task at a time. This can pose a challenge when dealing with operations that take time to complete, such as fetching data from a server or performing complex calculations. To handle such scenarios efficiently, Ja
    5 min read
  • Phases of JavaScript Event
    There are three different phases during the lifecycle of a JavaScript event. Capturing PhaseTarget PhaseBubbling Phase They follow the same order as listed above. Capturing Phase is when the event goes down to the element. The target phase is when the event reaches the element and the Bubbling phase
    2 min read
  • Pointer Events in Javascript DOM
    Pointer events are a set of DOM (Document Object Model) events that provide a unified way of handling inputs from a variety of devices, such as touchscreens, mouse, and pen/stylus. These events are supported by modern browsers and allow developers to write code that responds to user interactions wit
    5 min read
  • React Events
    In React, events are an integral part of the framework, allowing developers to build dynamic, interactive user interfaces. React events are very similar to DOM events in JavaScript but are handled in a way that is optimized for React's declarative approach to UI rendering. Understanding how React ev
    8 min read
  • JavaScript for IoT
    JavaScript (JS) is the most popular lightweight, interpreted compiled programming language. It can be used for both Client-side as well as Server-side developments. JavaScript is also known as a scripting language for web pages. However, it has become increasingly popular for building Internet of Th
    6 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
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