Chapter 11. DOM Events

11.1 DOM Events Overview

An event, in terms of the DOM, is either a predefined or a custom moment in time that occurs in relationship to an element in the DOM, the document object, or the window object. These moments are typically predetermined and programmatically accounted for by associating functionality (i.e., handlers/callbacks) to occur when these moments in time come to pass. These moments can be initiated by the state of the UI (e.g., input is focused or something has been dragged), the state of the environment that is running the JavaScript program (e.g., a page is loaded or an XHR request has finished), or the state of the program itself (e.g., monitor all mouse clicks for 30 seconds after the page has loaded).

Setting up events can be accomplished using inline attribute event handlers, property event handlers, or the addEventListener() method. In the following code, I’m demonstrating these three patterns for setting up an event. All three patterns add a click event that is invoked whenever the <div> in the HTML document is clicked by the mouse.

Live code

<!DOCTYPE html>
<html lang="en">

<!-- inline attribute event handler pattern -->
<body onclick="console.log('fire/trigger attribute event handler')">

<div>click me</div>

var elementDiv = document.querySelector('div');

// property event handler pattern
elementDiv.onclick = function()
  {console.log('fire/trigger property event handler')};

//addEventListener method pattern
elementDiv.addEventListener ...

Get DOM Enlightenment now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.