Last updated: Mar 5, 2024
Reading time·2 min
To check if an element was clicked, add a click
event listener to the
element.
The click
event is dispatched every time the element is clicked.
Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <button id="btn" style="width: 100px; height: 100px"> Click me </button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const button = document.getElementById('btn'); button.addEventListener('click', function handleClick() { console.log('element clicked'); });
We added a click event listener to the button element.
handleClick
function is invoked.If you need to detect if an element has already been clicked before, declare a variable in the outer scope and keep track of its value.
const button = document.getElementById('btn'); let elementClicked = false; button.addEventListener('click', function handleClick() { console.log('element clicked'); if (elementClicked) { console.log('button has already been clicked before'); } elementClicked = true; });
We declared the elementClicked
variable and initialized its value to false
.
true
.You can use this approach to only run the handleClick
function the first time
you click the element.
const button = document.getElementById('btn'); let elementClicked = false; button.addEventListener('click', function handleClick() { if (elementClicked) { return; } console.log('element clicked'); elementClicked = true; });
Once the handleClick
function gets invoked, the value of the elementClicked
variable is set to true
.
If you try the example above, you will only see the element clicked
message
logged once to your console.
Note that you can add a click
event listener to any type of element, it
doesn't have to be a button.
You can also use the setInterval() method to periodically check if an element has been clicked.
const button = document.getElementById('btn'); let elementClicked = false; button.addEventListener('click', function handleClick() { console.log('element clicked'); elementClicked = true; }); setInterval(() => { if (elementClicked) { console.log('element was clicked'); } else { console.log("element hasn't been clicked yet"); } }, 1500); // 👉️ invoke every 1500 milliseconds
The function we passed to the setInterval
method runs every 1.5 seconds and
checks if the element has been clicked or not.
However, note that it is more efficient to use specific events, like click
,
that only get dispatched when the element gets clicked.