Buttons are an essential part of any website or application. Without buttons, users wouldn’t have the ability to interact with the application. In JavaScript, you often need to know if the user clicked the button or not. Here are 2 simple ways to check if the button is clicked by the user.
Method 1: Using onclick
to Check if The Button is Clicked
The first way is to use onclick
function in JavaScript to see if the button is clicked. You can run any code after the button is clicked. The following example is using JavaScript onclick
function to see if the user clicked the button.
1 2 3 4 5 6 |
<h1 id="header">JavaScript Button Example</h1> <button id="button">Click Me</button> |
1 2 3 4 5 6 7 |
document.querySelector("#button").onclick = function(){ alert("You clciked the button"); } |
Method 2: Using addEventListener
to Check Button Click (Recommended)
You can also use addEventListener
in JavaScript to check if the button is clicked. The following example uses the addEventListiner
with button
to run a code snippet when a user clicks the button.
1 2 3 4 5 6 7 8 |
const button = document.querySelector("#button"); button.addEventListener("click", function(){ alert("You Clicked the button"); }) |
You can read more about click event in JavaScript on mozzila documentation.
Conclusion
There are 2 ways to check if the user clicked the button in JavaScript. You can either use onclick
function or addEventListener
in JavaScript to check the button click. The best way to see if user clicked the button is to use addEventListener
in JavaScript.