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 use Ejs in JavaScript ?
Next article icon

How to trigger events in JavaScript ?

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

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 that happen in the browser, such as user interactions.

What is an Event?

An event is an interaction between JavaScript and HTML. Common HTML events include:

  • onload: Triggered when the browser finishes loading a page.
  • onchange: Triggered when the value of an HTML element changes.
  • onclick: Triggered when an HTML element is clicked.
  • onmouseover: Triggered when the mouse hovers over an HTML element.
  • onmouseout: Triggered when the mouse moves out of an HTML element.

Handling Events in JavaScript

Events can be handled in two main ways:

  • Using the addEventListener() Method: This method attaches an event handler to an element.
  • Triggering Events on Individual Elements: Specific JavaScript functions can be defined to handle events for individual elements.

Using document.addEventListener() Method

Syntax: 

document.addEventListener(event, function, phase);

Example 1: This example uses the document.addEventListener() method to trigger events in Javascript.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport">     <title>Document</title> </head>  <body>     <h3>Click on the page to         trigger click event</h3>     <h3>Click on the page to         trigger mouseover event</h3>     <h3>Click on the page to         trigger mouseoutevent</h3>      <script type="text/javascript">         document.addEventListener("click",             function () {                 alert("You clicked inside the document");             });          document.addEventListener("mouseover",             function () {                 document.body.style.backgroundColor = "lavender";             });          document.addEventListener("mouseout",             function () {                 document.body.style.backgroundColor = "white";             });     </script> </body>  </html> 

Output

Explanation:

  • When the mouse moves over the document, the background color changes to lavender.
  • When the mouse leaves the document, the background color reverts to white.
  • Clicking anywhere in the document triggers an alert.

Example 2: Triggering events on individual elements.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport">     <title>Document</title> </head>  <body>     <button onclick="clickFunction()">         Click Me     </button>     <br><br>      <div class="container" id="myDiv"           onmouseenter="enterFunction()"           onmouseleave="leaveFunction()">         Hello World...How are you     </div>      <script type="text/javascript">         function clickFunction() {             document.body.style                 .backgroundColor = "pink";         }          function enterFunction() {             document.getElementById("myDiv")                 .style.border = "1px solid black";         }          function leaveFunction() {             document.getElementById("myDiv")                 .style.border = "2px solid blue";         }     </script> </body>  </html> 

Output:

Explanation:

  • When the button is clicked, the background color of the webpage changes to light green.
  • When the mouse enters the myDiv container, its border changes to black.
  • When the mouse leaves the myDiv container, its border reverts to blue.


Next Article
How to use Ejs in JavaScript ?

S

Shreyasi_Chakraborty
Improve
Article Tags :
  • JavaScript
  • Technical Scripter
  • Web Technologies
  • JavaScript-Questions
  • Technical Scripter 2020

Similar Reads

  • How to use Ejs in JavaScript ?
    EJS or Embedded Javascript Templating is a templating engine used by Node.js. The template engine helps to create an HTML template with minimal code. Also, it can inject data into the HTML template on the client side and produce the final HTML. Installation StepsInstall the module using the followin
    3 min read
  • Timing Events in Javascript
    Timing events are the events that help to execute a piece of code at a specific time interval. These events are directly available in the HTML DOM (Document Object Model) Window object, i.e., they are present in the browser. So, these are called global methods and can be invoked through the 'window'
    5 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
  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 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
  • How to Set Time Delay in JavaScript?
    Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
    2 min read
  • How to use events in ReactJS ?
    Modern webpages rely on user interactions, triggering events like clicks or keypresses. React facilitates event handling with built-in methods, allowing developers to create listeners for dynamic interfaces and responses. JavaScript events, inherent to the DOM, use bubbling propagation by default, m
    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
  • How to use the alert() method in JavaScript ?
    In this article, we will learn how to use the alert() method in JavaScript. The alert() method is used to show an alert box on the browser window with some message or warning. We can use it as a message or as a warning for the user. Approach: To show an alert on the browser window, we make a button.
    2 min read
  • How to Create an Alert in JavaScript ?
    The alert() method in JavaScript displays an alert box with a message and an OK button. It's used when you want information to come through to the user, providing immediate notifications or prompts for user interaction during program execution. Note: Alert boxes interrupt user interaction, shifting
    1 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