Events and event listeners

Coding with JavaScript

🕑 This lesson will take about 15 minutes

In this lesson, you will learn how to run JavaScript code when events occur on a webpage. Events include when the user clicks an HTML element (such as a button, an image, or some text) or moving the mouse over or away from an element, pressing a key on the keyboard, when an element on the page changes, or when the page has finished loading.

These are the different types of events:

  • onclick (when the mouse clicks an HTML element)

  • onmouseover (when the mouse hovers over an HTML element)

  • onmouseout (when the mouse leaves an HTML element)

  • onkeydown (when a key on the keyboard is pressed)

  • onload (when the page has finished loading)

  • onchange (when an HTML element on the page has changed)

In this example, we will add a button to a web page (using HTML code) and display an alert message when the button is clicked (using the onclick event). We will also experiment with other events including onload (when the page loads) and event listeners.

Watch the video below and scroll down for the sample code.

Sample HTML and JavaScript code

Here is the sample code. You might need to open the codepen snippet in a new tab/window and click Console to view the output of any console.log() messages.

Event listeners

You can also use an event listener in JavaScript code (instead of HTML code) to ‘listen’ for events such as the page loading, a user scrolling down the page, the user clicking an element such as a button, or the user pressing a keyboard or mouse button. Below is an example of a web page written in HTML code that contains a button (that has an ID of ‘myButton’). The JavaScript code has an event listener that calls a function named ‘displayMessage’ when a click event occurs on an element with the ID ‘myButton’.

Next lesson: Functions