Listening to events in the DOM

Events

Events in Javascript usually happen when the user of your webpage does something. For example click a button on your webpage.

People often use the verb 'fire' when talking about events. We say that an event 'fires'.

Examples of events:

  • User clicks a button
  • User types into an input
  • The DOM finishes loading

Listener / Callback

In Javascript the idea of a 'listener' / 'callback' is a function which gets called when a something happens.

Some people say that the function is 'listening' for a thing to happen. When it happens, the function gets called, usually with parameters which include details of the thing that happened.

Similarly, some people say that the function gets 'called back' when the thing happens.

htmlElement.addEventListener("event", function)

HTMLElement has a key addEventListener which is a function with the parameters:

  • "event" is the event to listen to.
  • function is the callback which gets called when the event 'fires'.

Events:

  • "click" - when a DOM element is clicked
  • "DOMContentLoaded" - when the DOM has loaded
  • "mouseenter" - when the mouse 'enters' or goes over the DOM element
  • "keydown" - when the mouse 'enters' or goes over the DOM element

Examples:

If the DOM has the following HTML:

<div id="container">
  <p>a</p>
  <p class="red">b</p>
  <p>c</p>
  <button id="button1">Press me!</button>
</div>
document.querySelector('#container').addEventListener('click', (event) => {
  console.log('<div id="container"> was clicked!')
})
document.querySelector('#container').addEventListener('mouseenter', (event) => {
  console.log('Mouse entered <div id="container">')
})
document.addEventListener('DOMContentLoaded', (event) => {
  console.log('DOM is loaded!')

  // You should actually do your DOM stuff in one of these!
})

Resources:

Mozilla's full list of events