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 whether a button is clicked or not, these are:
Table of Content
- Using onclick Event
- Using click Event
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: In this example, we have used above explained approach.
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 >w3wiki</ h1 > < h3 > How to check a button is clicked or not in JavaScript? </ h3 > < input type = "button" class = "button" value = "Button" onclick = "myBeginner()" > < script > function myBeginner() { 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: In this example, we have use above explained approach.
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 >w3wiki</ h1 > < h3 > How to check a button is clicked or not in JavaScript? </ h3 > < input type = "button" class = "button" value = "Button" onclick = "myBeginner()" > < script > function myBeginner() { document.querySelector(".button") .addEventListener("click", function () { alert("Button Clicked"); }); } </ script > </ body > </ html > |
Output: