how to check if a button is clicked in javascript
Hello Everyone, today I'm going to share how do you check a button is clicked or not in JavaScript. Suppose you have added a search icon on your website and when a user will click on the search icon, the search box will appear. So this is very important and you must know about that.
There are many ways to check if a button is clicked or not in JavaScript . I shall share some ways.
Answer 1 :- Using Click Event
In the first example, I shall use the click event to check whether a button is clicked. First of all create a button with an id attribute. Then write javascript code between the <script> </script> tag.
<script>
var seletBtn= document.getElementById('demoBtn');
selectBtn.onclick = function() {
alert("1st button is clicked");
}
</script>
Answer 2 :- Using addEventListener
You can use addEventListener instead of click event.
- id Attribute : document.querySelector("#demoBtn")
- class Attribute :document.querySelector(".demoBtn")
- tag name :document.querySelector("button")
Answer 3 :- Using onclick event
Answer 4 :- How many times a button is clicked?
First, create a html button with an id as id="demoBtn" .
<button id="demoBtn"></button>
Then add the js code between the <script> tag. First, store the button in a variable using js , create a variable and initialize it to 0.
In this post, I have explained how to check whether a Button is clicked using JavaScript. I hope you have learned something new in this tutorial.
<button id="btn">click</button>
<script>
$("#btn").on('click',function(){
alert("button clicked");
});
</script>