Introduction

To recap, in the previous lesson, we discussed simple ways to manipulate the HTML code using JavaScript. Let’s look at some real examples of event listeners using JavaScript to access DOM elements.

What is an event listener?

An event listener is a function or logic set to be executed when a particular event occurs. This event could be a click on the button, the pressing of a key on the keyboard, and so on.

In this lesson, we will perform three tasks to understand how we can add interactivity to our web pages using event listeners.

Example 1: Change the text on a button click

In this task, we will add an event listener that is triggered when a particular button is clicked. Once the event listener is triggered, the text of the paragraph will be changed.

To do this task, we will perform the following steps:

  1. Access the button using the id attribute.

  2. Attach a click event on the button using the addEventListener() method.

  3. Add the functionality when the click event is triggered.

Now let’s see how this can be implemented below:

Get hands-on with 1200+ tech skills courses.