HTML Event Attributes and JavaScript Event Listeners
Recognize an inline handler
An event is a notification of an occurrence, such as button activation. HTML event attributes contain JavaScript that runs for the corresponding event. This example shows onclick for recognition; for maintainable code prefer a separate listener. A native button also supports keyboard activation.
<button type="button" onclick="document.getElementById('status').textContent = 'Saved'">Save</button><p id="status" role="status"></p>Activate Save; the status text becomes Saved. Nothing is sent to a server.
Register an event listener
addEventListener takes an event type and a function to run when the event occurs. Do not include the on prefix in the event type. Here the arrow function is the callback: its body runs when a click is delivered, not at registration time.
<button id="save" type="button">Save</button><p id="status" role="status"></p><script> const save = document.getElementById("save"); save.addEventListener("click", () => { document.getElementById("status").textContent = "Saved"; });</script>The button updates the status after activation; markup and behavior are separated.
Handle a form without navigation
The event parameter describes what happened. preventDefault cancels a cancelable event’s default action, not its propagation. A submit listener on the form covers ordinary submission from a button or keyboard. This local demo intercepts submission rather than contacting a server.
<form id="form"> <label> Topic <input name="topic" value="HTML" required> </label> <button type="submit">Preview</button></form><p id="status" role="status"></p><script> document.getElementById("form").addEventListener("submit", (event) => { event.preventDefault(); document.getElementById("status").textContent = "Preview ready"; });</script>Submitting a valid form updates the status locally without navigation.
Common mistakes and practice
A listener on a parent may receive events bubbling from descendants. event.target identifies the originating target (subject to retargeting); event.currentTarget identifies the object currently handling it. Avoid relying on inline handlers in production: a CSP may disallow them. Use textContent rather than injecting untrusted HTML. Do not replace native keyboard behavior with pointer-only handlers.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Event Attributes and JavaScript Event Listeners — Knowledge Check
Apply the integration concepts taught in this lesson.
Which event type is passed to addEventListener for a button activation?
When does the callback run?
What does preventDefault cancel on a cancelable event?
Which object does currentTarget identify during a listener?
Which is preferable for a keyboard-operable action?