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 Events
Next article icon

JavaScript onclick Event

Last Updated : 08 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 two ways as listed below:

Table of Content

  • Applying onclick function as an attribute
  • Applying onclick using addEventListener() method

Applying onclick event as an attribute

The onclick event can be passed as an attribute to an HTML element which makes it trigger a specified functionality on the web page when the user clicks on it.

Syntax:

<HTMLElement onclick = "callbackFunction">
<!-- Content of HTML element -->
</HTMLElement>

Example: The below code example implements the onclick function when it is passed as an attribute to an element.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width,                     initial-scale=1.0">     <title>         JavaScript onclick Function     </title>     <style>         #container {             text-align: center;         }          #toggler {             display: none;         }     </style> </head>  <body>     <div id="container">         <h1 style="color: green;">             GeeksforGeeks         </h1>         <h2>             The below button uses the onclick function             to perform some functionality on click to it.         </h2>         <button onclick="clickHandler()">             Click me to see changes         </button>         <h3 id="toggler">             Hey Geek, <br />             Welcome to GeeksforGeeks         </h3>     </div>      <script>         function clickHandler() {             const toggler = document.getElementById('toggler');             console.log(toggler.style.display)             if (toggler.style.display === "block") {                 toggler.style.display = "none";             }             else {                 toggler.style.display = "block";             }         }     </script> </body>  </html> 

Output:

onclickGIF

Applying onclick using addEventListener() method

There is a in-bulit method addEventListener() provided by JavaScript to attach events with the HTML elements. It takes the name of the event and the callback function as arguements to attach them.

Syntax:

selectedHTMLElement.addEventListener('eventName', callbackFunction);

Example: The below code implements the addEventListener() method to applying the onclick function.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width,                     initial-scale=1.0">     <title>         JavaScript onclick Function     </title>     <style>         #container {             text-align: center;         }          #toggler {             display: none;         }     </style> </head>  <body>     <div id="container">         <h1 style="color: green;">             GeeksforGeeks         </h1>         <h2>             The below button uses the onclick function             to perform some functionality on click to it.         </h2>         <button id="myBtn">             Click me to see changes         </button>         <h3 id="toggler">             Hey Geek, <br />             Welcome to GeeksforGeeks         </h3>     </div>      <script>         const myBtn = document.getElementById('myBtn');         function clickHandler() {             const toggler = document.getElementById('toggler');             console.log(toggler.style.display)             if (toggler.style.display === "block") {                 toggler.style.display = "none";             }             else {                 toggler.style.display = "block";             }         }         myBtn.addEventListener('click', clickHandler);     </script> </body>  </html> 

Output:

onclickGIF


Next Article
JavaScript Events

A

abhish8rzd
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • 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
  • 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 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
  • HTML DOM onclick Event
    The HTML DOM onclick event occurs when the user clicks on an element. In HTML: <element onclick="myScript">[GFGTABS] HTML <!DOCTYPE html> <html> <body> <button onclick="myFunction()">Click me</button> <p id="gfg"></p> <script>
    1 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
  • Call multiple JavaScript functions in onclick event
    Calling multiple JavaScript functions in an onclick event means executing several functions sequentially when a user clicks an element, like a button. This approach allows you to trigger multiple actions or behaviors with a single click, enhancing interactivity and functionality in web applications.
    2 min read
  • How to Use JavaScript: void(0) and onClick?
    Using javascript:void(0) in combination with the onClick attribute is a technique used in HTML to create links or clickable elements that perform actions without navigating away from the page. This is common when you want to attach a JavaScript function or event handler to a clickable element but pr
    2 min read
  • HTML DOM ondblclick Event
    The HTML DOM ondblclick event occurs on a double click by the user. In HTML: <element ondblclick="myScript">[GFGTABS] HTML <!DOCTYPE html> <html> <body> <button id="demo" ondblclick="myFunction()"> Double-click </button> <script> function
    1 min read
  • JavaScript contextmenu MouseEvent
    When we click the right mouse button on our desktop, a menu-like box appears and this box is called the context menu. In JavaScript, a context menu event runs when a user tries to open a context menu. This can be done by clicking the right mouse button. This article demonstrates executing any operat
    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