Skip to content

Event Listeners

An event is a signal that something has happened in the browser. There are several triggers for events, some that occur automatically (e.g., the load event fires when the page has finished loading), and others that occur in response to user interactions (e.g., the click event fires when the user clicks on a page element).

To respond to an event, you can attach an event listener to the relevant HTML element in JavaScript.

Adding an Event Listener

The recommended procedure for this class is as follows:

  1. Declare a variable in JavaScript to reference the interactive HTML element.
  2. Write a function that defines what should happen when the interaction occurs.
  3. Add an event listener that calls the function in response to the intended event.

Step 1: Declare a variable in JavaScript to reference the interactive HTML element.

When an HTML element is assigned to a variable using document.querySelector(), it is treated as an object data type. More specifically, it is a class of object called HTMLElement.

<button id="my-button">Click Me</button>
const myButton = document.querySelector("#my-button");

Note that the naming convention for the id attribute in HTML (and how i's used in querySelector) is kebab-case, while the variable name in JavaScript is camelCase. Although they are the same words, they represent different things in different contexts. This is also a valid way to assign an HTML element to a variable:

const button1 = document.querySelector("#my-button");

However, using the same words for both the id and the variable name (styled appropriately in kebab-case or camelCase), simplifies the process, as it reduces the number of names you need to create and remember.

Step 2: Write a function that defines what should happen when the interaction occurs

function wasClicked() {
  console.log("Button was clicked!");
}

Step 3: Add an event listener that calls the function

The event listener should be added to the element that fires the desired event - in this case, the button that the user interacts with.

myButton.addEventListener("click", wasClicked);

Notice that the statement begins with the variable name that we created in step 1. The addEventListener() method takes 2 arguments: the event type to listen for ("click") and the name of the function we created in step 2 (wasClicked).

When using the console with embedded CodePen examples, you should open the Pen in its own window by clicking Edit On CodePen and then clicking the Console button in the CodePen editor.

See the Pen Event Listener (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.