JavaScript Event Listeners

This screencast was created by V School.

Event Listeners are JavaScript objects that listens for a specific DOM Event to occur and executes a function when it does. Event Listeners can be created by using the addEventListener() method to a target element.

NOTE

While there are other techniques for interacting with DOM Events, the addEventListener() method is considered best practice. In this course, we will not be using inline events (onclick, etc.)

const button = document.getElementById('button')

// using an anonymous function
button.addEventListener('click', function () {
  console.log(`The button was clicked`)
})

The addEventListener() method takes two arguments, the event type and a function that will execute when the event occurs. In the example above, the event type is 'click' and the function is an anonymous function that logs a message to the console. However, a predefined function may be used instead of an anonymous as shown in the example below.

const button = document.getElementById('button')

// a predefined function
function handleButtonClick () {
    console.log('The button was clicked!')
}

// using a predefined function
button.addEventListener('click', handleButtonClick)

When using a predefined function inside a method, no parentheses are included with the function name. This is because we do not want to invoke the function at this time, but is instead just pass it as an argument, for the addEventListener() method will invoke the passed function for us.

While the 'click' event type is arguably the most common DOM event, there are many, many other event types. All of which, can be used with the addEventListener() method. For example, it is possible to listen for a double click on the page header.

const header = document.getElementById('header')

header.addEventListener('dblclick', function () {
  console.log("The header was double clicked!")
})

On the next page, we will learn more about the different event types.