How to handle click events
Listen for a click
Use a real button so keyboard behavior and semantics work automatically. The listener function runs after each click.
<button id="count-button" type="button">Count: 0</button>
<script>
const button = document.querySelector("#count-button");
let count = 0;
button?.addEventListener("click", () => {
count += 1;
button.textContent = `Count: ${count}`;
});
</script>
Inspect the event
The event object describes what happened. currentTarget is the element whose listener is running.
const button = document.querySelector("button");
button?.addEventListener("click", event => {
console.log(event.type);
console.log(event.currentTarget.id);
});
Handle a form submission
Form submission is a meaningful event for both clicking and pressing Enter. Prevent navigation when JavaScript will process the form.
const form = document.querySelector("#signup");
form?.addEventListener("submit", event => {
event.preventDefault();
const data = new FormData(form);
console.log(data.get("email"));
});
Manage listeners responsibly
- Prefer
addEventListenerover inlineonclickattributes - Use semantic controls and do not recreate button behavior on a
div - Keep handlers small and move reusable logic into named functions
- Remove long-lived listeners when their owning interface is discarded