DOM Events & Event Handling
What events are, common event attributes, and the ways to attach handlers.
HTML DOM Events
Events are actions or occurrences that happen in the browser. They can be triggered by the browser (page load) or by the user (click, type, hover). JavaScript code can be executed in response to any event.
| Event | Attribute | Triggered when |
|---|---|---|
click | onclick | User clicks an element. |
load | onload | Page or image finishes loading. |
mouseover | onmouseover | Mouse moves over an element. |
submit | onsubmit | Form is submitted. |
change | onchange | Input value changes. |
Common HTML Events & Event Attributes
abort (onAbort), blur (onBlur), change (onChange), click (onClick), error (onError), focus (onFocus), load (onLoad), mouseout (onMouseOut), mouseover (onMouseOver), reset (onReset), resize (onResize), select (onSelect), submit (onSubmit), unload (onUnload).
Three Ways to Specify Event Handlers
- Inline HTML attribute —
onclick="myFunction()" - DOM property assignment —
element.onclick = handler; - addEventListener() — recommended:
element.addEventListener('click', fn);
Assigning Events Using HTML Attributes
<button onclick="displayDate()">What time is it?</button>
<p id="demo"></p>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
Assigning Events Using the HTML DOM
Assign a function reference directly to the element's event property. This keeps HTML and JavaScript cleanly separated, and the handler can be swapped or removed at runtime.
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
document.getElementById("myBtn").onclick = displayDate;
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Complete the three ways of attaching an event handler.
<!-- 1. Inline HTML attribute --><button ="myFunction()">Click</button><!-- 2. DOM property assignment (function name, no parentheses) -->document.getElementById("myBtn"). = displayDate;<!-- 3. Recommended: addEventListener -->document.getElementById("myBtn").("click", displayDate);<!-- onload fires when the page finishes --><!-- -->