Sometimes, we want to check whether a button is clicked by using JavaScript.
In this article, we’ll look at how to check whether a button is clicked by using JavaScript.
How to check whether a button is clicked by using JavaScript?
To check whether a button is clicked by using JavaScript, we add a click listener to the button.
For instance, we write
document.getElementById("button").onclick = () => {
console.log("button was clicked");
};
to select the button with getElementById
.
Then we set its onclick
property to a function that’s called when the button is clicked.
Conclusion
To check whether a button is clicked by using JavaScript, we add a click listener to the button.