Updated 8 days ago | GitHub

DOM Events

An event notifies code when something “interesting” changes that might affect code execution or program flow. Some examples of events include:

  • The user clicks the mouse.
  • When the page is loaded.
  • When the mouse hovers over an element.
  • When an input field changes.
  • When an HTML form is submitted.
  • When the user presses a key.

See a full list of Event references on MDN Docs.

In order to capture events, we need to use the addEventListener() method.

Event Listeners

The addEventListener() method listens for a specific event and if the event is sensed, it executes a function. Let’s take a look at the syntax:

target.addEventListener(type, listener);
target.addEventListener(type, listener, options);
  • target: The object that will receive the event — most often a DOM element, but it can also be document, window, or any other object that supports events.
  • type: A string that represents an event type.
  • listener: This is the function that runs when an event of the specified type occurs. (Avoid thinking of this as the event being “captured”: in DOM terminology, capturing is a specific phase of event propagation that you opt into with the capture option.)
  • options: This is an optional parameter that allows customization of specific characteristics of the event listener. Review all of the parameters on the addEventListener() MDN Docs.

The listener can also be combined with an arrow function to make implementation more concise! When the event fires, the browser calls the listener with a single argument: an Event object describing what happened (conventionally named event or e).

target.addEventListener(type, (event) => {
	//add function code here!
});