O'Reilly logo

DOM Enlightenment by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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>

<script>
var elementDiv = document.querySelector('div');

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

//addEventListener method pattern
elementDiv.addEventListener ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required