Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 27, 2022 › #Button #css

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.

Demo Using Click Event
You could set the button in a variable.
<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.

Demo Using addEventListener
You can select the button :-
  1. id Attribute : document.querySelector("#demoBtn")
  2. class Attribute :document.querySelector(".demoBtn")
  3. tag name :document.querySelector("button")

Answer 3 :- Using onclick event

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.

How many times a button is clicked

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.

save
listen
AI Answer
1 Answer
Write Your Answer
  1. You can check a button is clicked or not in jQuery.

    <button id="btn">click</button>
    <script>
    $("#btn").on('click',function(){
    alert("button clicked");
    });
    </script>
    Reply Delete
    Share
loading
back
View All