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 >neveropen</ h1 >       < h3 >         How to check a button is clicked         or not in JavaScript?     </ h3 >       < input type = "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 >neveropen</ h1 >       < h3 >         How to check a button is clicked         or not in JavaScript?     </ h3 >       < input type = "button" class = "button"         value = "Button"          onclick = "myGeeks()" >       < script >         function myGeeks() {             document.querySelector(".button")                 .addEventListener("click", function() {                     alert("Button Clicked");                 });         }     </ script > </ body >   </ html > |
Output:
Â