When someone interacts with a webpage, the browser sends events to the relevant JavaScript code. The click event happens when a control or element is activated, often by pointer or keyboard.
When click happens
A control or element is activated, often by pointer or keyboard.
You can listen for it using addEventListener(). That keeps event handling separate from HTML attributes such as onclick and works well with modern code organization.
A small working example
<button id="demo-target" type="button">Try this button</button>
<p id="event-status" role="status">Waiting for click...</p>
<script>
const eventTarget = document.getElementById("demo-target");
const eventStatus = document.getElementById("event-status");
if (eventTarget) {
eventTarget.addEventListener("click", (eventDetails) => {
eventStatus.textContent = "click event received";
console.log(eventDetails.type, eventDetails.target);
});
}
</script>
Reading the code
The browser listens for click on the relevant target. When the event occurs, the callback receives eventDetails, updates the status message and logs the event name and target in Developer Tools.
Activate a native button using mouse, Enter or Space.
For a native button, click can be generated by keyboard activation as well as pointer input.
Try it in your browser
Open the page, show the Console panel, and follow this test: Activate a native button using mouse, Enter or Space. Then change one thing in the example and observe whether the event still fires.
Common Beginner Mistakes
- Expecting
clickto fire without its required user action or browser condition. - Activate a native button using mouse, Enter or Space.
- Adding repeated event listeners without considering cleanup or unwanted side effects.
Key Takeaways
clickreports a control or element is activated, often by pointer or keyboard.addEventListener("click", ...)listens for the event on the appropriate target.- Activate a native button using mouse, Enter or Space.