To check if an element is clicked or not, you can add an event listener to the element. The event listener will be fired every time you click the element.
To add an event listener to the target element, you can use the addEventListener()
method. This method needs two parameters, the event name, and a callback function to handle this event.
Here is the syntax of the addEventListener()
method:
element.addEventListener(event_name, callback_function);
Now, to add the event listener to the element, you have to first get this element using any DOM method such as getElementById()
, querySelector()
, etc. and then you can simply call the addEventListener() method on it.
See the following working example:
Example:
// Get the element let element = document.getElementById('myDiv'); // Add an event listener element.addEventListener('click', function(event){ alert('The div is clicked'); // Alert on click });
Alternatively, you can use the onclick
handler directly on the target element. Its working is also similar to the addEventListener() method.
See the following working example:
Example:
let element = document.getElementById('myDiv'); element.onclick = function(event){ alert('The div is clicked'); }