How to check whether a button is clicked or not in JavaScript?

by august.kutch , in category: JavaScript , 2 years ago

How to check whether a button is clicked or not in JavaScript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@august.kutch You can use addEventListener() on this element and listen "click" event to check whether a button is clicked, here is code as example in Javascript:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<html>
<head>
    <meta charset="utf-8"/>
</head>
<body>
<div class="wrapper">
    <button id="message">Click me</button>
</div>
</body>
<script>
    const element = document.querySelector("#message");
    element.addEventListener('click', () => {
        console.log("You clicked button!")
    })
</script>
</html>


Member

by deron , a year ago

@august.kutch 

You can use event listeners in JavaScript to check whether a button is clicked or not. Here's an example:


HTML code for the button:

1
<button id="myButton">Click me</button>


JavaScript code to check if the button is clicked:

1
2
3
4
const myButton = document.getElementById("myButton");
myButton.addEventListener("click", function() {
    console.log("Button clicked");
});


In the above code, we first get the button element using document.getElementById(). We then add an event listener to the button using the addEventListener() method. The first argument of addEventListener() is the event we want to listen for (in this case, "click"). The second argument is a function that will be called when the event is triggered (in this case, we are logging "Button clicked" to the console).


So, whenever the button is clicked, the function we passed to addEventListener() will be called, and we can perform any actions we want inside that function.