Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 6

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.

EventAttributeTriggered when
clickonclickUser clicks an element.
loadonloadPage or image finishes loading.
mouseoveronmouseoverMouse moves over an element.
submitonsubmitForm is submitted.
changeonchangeInput 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

  1. Inline HTML attribute — onclick="myFunction()"
  2. DOM property assignment — element.onclick = handler;
  3. 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 -->
<!-- -->