Codepath

DOM Events

An event notifies code with 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 strokes a key.

See a full list of Event references on MDN Docks.

In order to capture events, we need 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: DOM reference to an HTML element.
  • type: A string that represents an event type.
  • listener: This is the function that fires if the event is captured.
  • 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 arrow function to make implementation more concise!

target.addEventListner(type, (a)=>{
	//add function code here!
}
Fork me on GitHub