Event Listeners

Event Listeners are a special type of function in JavaScript that waits for a specified event, and then calls a callback function after that event has been triggered.

They are used in pretty much every single web application out there. They're how you make your page perform actions from clicking through links, to triggering animations when you scroll over a section of the page

Common Usage

Different Types of Events

And many, many more...

Event Listeners as HTML properties

You can set event listeners as properties directly on any HTML element. By adding an on[event] property, substituting the word [event] for the event of your choice you can fire a JavaScript function when that event happens.

For example you could create a <p> tag that turns the text red when clicked by adding an onclick property like so:

<p onclick="turnRed()">Turns red when clicked</p>
function turnRed(evt) {
  evt.target.style.color = 'red'

Some elements have default event properties already attached to them. Most commonly <a> (anchor) tags which go to a specified page or html fragment onclick, and <form>s which sent a request, and reload the page when an onsubmit event is fired

Lab: Event Listeners on Different Elements

Let's play around with setting event listeners on different elements!

<!DOCTYPE html>
<html lang="en">
  <a href="">I'm an anchor tag!</a>
  <div>Divs on divs on divs</div>
  <button>Click Me!</button>
    <input type=text />
    <input type=submit />

Adding Event Listeners with JavaScript

As well as adding event listeners inline with HTML you can also attach event listeners to elements using JavaScript

This can help keep your code organized, and makes it easier to attach complicated functionality to an element.

addEventListener is a method that can be called on HTML elements in JavaScript. To use it you will first need to add a <script> tag to your HTML file which will allow you to add JavaScript to your file. Then target the element you want to add the event listener to with a DOM query, and assign it to a variable. Finally call the addEventListener method on it

The Structure of the Event Listener in JavaScript



Lab: Highlighter

Now that you know a little about adding behavior to web pages let's create a website that allows you to highlight the text on the page!

The goal of this exercise is to create a simple webpage that contains a title, and a single block of text.

 Previous Next