How to check a button is clicked or not in JavaScript ?

In this article, we will see how to check whether a button is clicked or not using JavaScript. There are two methods to check a button is clicked, i.e. using onclick, and click events.
Method 1: Using onclick Event: First, we will create a button, then use document.querySelector() to select the button element, and after that apply onclick event to check whether the button is clicked or not.
Example:
HTML
| <!DOCTYPE html> <html>  <head>     <title>         How to check a button is clicked          or not in JavaScript?      </title>      <style>         body {             text-align: center;         }          h1 {             color: green;         }                  input[type="button"] {             padding: 5px 10px;             margin-top: 10px;         }     </style> </head>  <body>     <h1>zambiatek</h1>      <h3>         How to check a button is clicked          or not in JavaScript?      </h3>      <inputtype="button"class="button"        value="Button"        onclick="myGeeks()">      <script>         function myGeeks() {             document.querySelector(".button").onclick = function() {                 alert("Button Clicked");             }         }     </script> </body>  </html> | 
Output:
 
Method 2: Using click Event: First, we will create a button, then use document.querySelector() to select the button element, and after that apply addEventListener() and click event to check whether the button is clicked or not.
Example:
HTML
| <!DOCTYPE html> <html>  <head>     <title>         How to check a button is clicked          or not in JavaScript?      </title>      <style>         body {             text-align: center;         }          h1 {             color: green;         }          input[type="button"] {             padding: 5px 10px;             margin-top: 10px;         }     </style> </head>  <body>     <h1>zambiatek</h1>      <h3>         How to check a button is clicked          or not in JavaScript?      </h3>      <inputtype="button"class="button"        value="Button"        onclick="myGeeks()">      <script>         function myGeeks() {             document.querySelector(".button")                 .addEventListener("click", function() {                     alert("Button Clicked");                 });         }     </script> </body>  </html> | 
Output:
 
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
 
				 
					


