JavaScript: click
The click event runs a handler when a button, link, or other activatable element is clicked, tapped, or activated from the keyboard.
What you will learn
- How to register a click handler with
addEventListener() - How default actions such as navigation or form submission affect a click
- How to keep keyboard and assistive-technology interaction usable
Minimal example
<button id="toggle" type="button" aria-expanded="false">
Show details
</button>
<p id="details" hidden>Details are visible.</p>
<script>
const button = document.querySelector("#toggle");
const details = document.querySelector("#details");
button.addEventListener("click", () => {
const open = details.hidden;
details.hidden = !open;
button.setAttribute("aria-expanded", String(open));
});
</script>Use a real <button> for an action and a real <a> for navigation. These elements already provide expected keyboard behavior; adding a click handler does not replace accessible HTML.
Common mistakes
- Prefer
addEventListener("click", handler)over inlineonclickattributes. - Call
event.preventDefault()only when intentionally replacing a link or form's default action. - Do not make a plain
<div>look like a button without reproducing its keyboard, focus, and state behavior. - When using event delegation, find the intended control with
event.target.closest("button")and guard againstnull.