Check out bidbear.io Amazon Advertising for Humans. Now publicly available ๐Ÿš€

Javascript: DOM Event Listeners

Intro

Events are actions taken by the user, not things that are executed on pageload. For example:

  • clicking on something
  • hovering over a link
  • dragging and dropping
  • pressing keys

In other words, events add interactivity. The way that this works roughly is that we select an element and then add an event listener.

There are over 200 recognized events. A full list of events is available on MDN Docs.

Basic Format

.addEventListener(event, function)

The basic formula is that you add an event listener to an element in the DOM that you have selected with a variable. Apply the event listener to that variable and then tell it what action you are watching for, and what to do when that happens.

Here is a quick sample where we just create a console log when a button is clicked:

//this is the basic format that we will follow
element.addEventListener(type, functionToCall);

//we select a button with .querySelector then add an event listener and log a message when it is clicked
var button = document.querySelector("button");
button.addEventListener("click", function() {
  console.log("SOMEONE CLICKED THE BUTTON!");
});

Here is another example where we change the content of a paragraph when a button is clicked:

//first we select the two elements that we need
var button = document.querySelector("button");
var paragraph = document.querySelector("p");

//add a listener to the button and a function that changes the paragraph text
button.addEventListener("click", function() {
  paragraph.textContent = "Someone Clicked the Button!";
});

You do not have to use an anonymous() function, you can also create a named function like this:

//using a named function instead of an anonymous function

var button = document.querySelector("button");
var paragraph = document.querySelector("p");

button.addEventListener("click", changeText);

function changeText() {
  paragraph.textContent = "Someone Clicked the Button!";
}

Common event include the following:

  • click
  • mouseover
  • dblclick
  • keypress
  • drag

Examples

Click

Here is a sample of DOM Event. A simple button that toggles the background color of the body.

Click + Change

And another more complicated example. A small program that tracks scores between two players. The โ€œchangeโ€ event listener is on the score input, because it can be changed with clicking, and also typing.

mouseover + mouseout

This example shows how to create a hover effect, and also to put that effect inside of a loop so that it only applies to the item currently being touched instead of all items stored in the element variable.

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart