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

How to Handle JavaScript Events in HTML ?

Last Updated : 12 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 different types of HTML event handler attributes. Basically, to handle events in HTML, you just need to add the function in the HTML tag which is going to be executed in JavaScript when any event in HTML is fired or triggered. There are many event attributes in HTML like keyboard event, mouse event, form event, etc. which are discussed briefly. 

Syntax:

Handle event in HTML :

<element onclick="myScript">
 

Various HTML event attributes:

Form Event

  • onblur: This event occurs when an object loses focus.
    <element onblur="myScript">
  • onchange: This event occurs when the value of an element has been changed.
    <element onchange="myScript">
  • onfocus: This event occurs when element get focus.
    <element onfocus="myScript">

Example 1: When the user selects the button from the select tag, onchange() event is fired and then OnChangeFunction() is called which is present in JavaScript. So an event handler defined in the HTML can call a function defined in a script

HTML
<!DOCTYPE html> <html>  <body>     <center>         <h1 style="color: green;">             GeeksforGeeks         </h1>          <input type="text" name="blur" id="blur"              onblur="BlurFunction()"              placeholder="Enter Name" />         <br /><br />          <select id="course" onchange="OnChangeFunction()">             <option value="Competitive Programming">                 Competitive Programming             </option>              <option value="Operating System">                 Operating System             </option>              <option value="Web Development">                 Web Development             </option>              <option value="Android Development">                 Android Development             </option>         </select>          <p id="demo"></p>         <br /><br />          <input type="text" id="focus"              onfocus="FocusFunction(this.id)"                  placeholder="Enter Your Semester" /><br />     </center>      <script>         function BlurFunction() {             let x = document.getElementById("blur");             x.value = x.value.toUpperCase();         }          function OnChangeFunction() {             let x = document.getElementById("course").value;             document.getElementById("demo")                 .innerHTML = "You selected: " + x;         }          function FocusFunction(x) {             document.getElementById(x)                 .style.background = "green";         }     </script> </body>  </html> 

Output:

blur,focus and onchange

Event

  • onclick: This event occurs when user clicks on an element.
<element onclick="myScript">
  • onmouseover: This event occurs when user hover mouse pointer over an element.
<element onmouseover="myScript">

Example 2:

HTML
<!DOCTYPE html> <html>  <body>     <center>         <h1 style="color: green;">             GeeksforGeeks         </h1>                  <button onclick="OnClickFunction()">             Click me         </button>                  <p id="demo"></p>         <br /><br />          <p onmouseover="MouseHover()">             Hover Mouse Here         </p>     </center>      <script>         function OnClickFunction() {             document.getElementById("demo")                 .innerHTML = "GeeksforGeeks";         }          function MouseHover() {             alert("Mouse move over");         }     </script> </body>  </html> 

Output:

Mouseover 

In above output, 'Click Me' button calls the OnClickFunction() function when it is clicked. The OnClickFunction() is a function defined in a separate <script> element.

Disadvantages of using HTML event handler attributes:

  • Assigning event handlers using HTML event handler attributes are considered a bad practice.
  • The event handler code is mixed with the HTML code, which will make the code more difficult to maintain and extend.
  • There is a problem with timing, as if the element is loaded fully before the JavaScript code, users can start interacting with the element on the webpage which will cause an error.

Next Article
How to trigger events in JavaScript ?
author
aksrathod07
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • HTML
  • HTML5
  • HTML-DOM
  • HTML-Questions
  • JavaScript-Questions
  • JavaScript-Events

Similar Reads

  • How to Remove Event Handlers in JavaScript ?
    In JavaScript, event handlers are functions attached to HTML elements to respond to specific events like clicks or mouse movements. Removing event handlers effectively detaches the specified function from listening to that particular event on that element. Table of Content Using removeEventListener(
    3 min read
  • How to Add JavaScript in HTML Document?
    To add JavaScript in HTML document, several methods can be used. These methods include embedding JavaScript directly within the HTML file or linking an external JavaScript file. Inline JavaScriptYou can write JavaScript code directly inside the HTML element using the onclick, onmouseover, or other e
    4 min read
  • How to call JavaScript function in HTML ?
    In HTML, you can easily call JavaScript functions using event attributes like onclick and onload. Just reference the function name within these attributes to trigger it. You can also call functions directly within script blocks using standard JavaScript syntax. Let's create an HTML structure with so
    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
  • How does inline JavaScript work with HTML ?
    Inline JavaScript refers to JavaScript code embedded directly within HTML elements using the onclick, onmouseover, or other event attributes. This allows you to execute JavaScript code in response to user interactions or specific events without needing a separate JavaScript file or script block. Syn
    2 min read
  • How are events handled in React?
    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 define a client-side script in HTML5 ?
    To define a client-side script in HTML5, we can do <script> tag or adding external script file by src attribute to the HTML file. <script> tag contains the JavaScript to be added for the client-side scripting. Syntax: <script> // JavaScript goes here console.log('GeeksforGeeks');
    1 min read
  • How to get/change the HTML with DOM element in JavaScript ?
    In order to get/access the HTML for a DOM element in JavaScript, the first step is to identify the element base on its id, name, or its tag name. Then, we can use inner.HTML or outer.HTML to get the HTML. Using the getElementById() method: This method gets/identifies the DOM elements using its ID an
    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
  • How to select DOM Elements in JavaScript ?
    Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or mo
    3 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