Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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

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 trigger events in JavaScript ?

S

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

Similar Reads

    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
    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 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
    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
    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
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