Lesson 1: Event Listeners

Learning Objectives

By the end of this lesson, learners will be able to:

  • Understand what an event listener is in JavaScript
  • Use addEventListener() to respond to user interactions
  • Work with common event types like click, submit, keydown, etc.
  • Know the basic structure of an event listener
  • Begin building interactive behaviors with just a few lines of code

What Is an Event Listener?

An event listener is JavaScript code that waits for something to happen—like a user clicking a button, typing into a field, or submitting a form—and then runs a function in response.

In other words:
📣 “Hey browser, when this element is clicked (or hovered or typed into), do this!”


The addEventListener() Method

The most common way to attach an event listener in JavaScript is:

element.addEventListener("event-type", functionToRun);
  • element – the HTML element you’re listening to
  • "event-type" – a string (e.g. "click", "submit", "keydown")
  • functionToRun – the code that runs when the event happens

Example: Button Click

HTML:

<button id="myButton">Click me</button>

JavaScript:

let button = document.getElementById("myButton");

button.addEventListener("click", function () {
  alert("Button clicked!");
});

This will show a pop-up only when the button is clicked.


Common Event Types

Event TypeDescription
clickWhen the user clicks an element
submitWhen a form is submitted
keydownWhen a key is pressed down
keyupWhen a key is released
mouseoverWhen the mouse hovers over an element
inputWhen the user types into an input field

Two Ways to Define the Event Handler

1. Inline Anonymous Function (most common)

element.addEventListener("click", function() {
  // code to run
});

2. Named Function (recommended for reuse and clarity)

function handleClick() {
  alert("Clicked!");
}

element.addEventListener("click", handleClick);

Important Notes

  • You can add multiple event listeners to the same element.
  • Event listeners can be added to any HTML element, including buttons, forms, inputs, and even the whole document.

Example: keydown Event

Let’s display what key the user presses:

HTML:

<input id="type-here" placeholder="Type something..." />
<p id="output"></p>

JavaScript:

let input = document.getElementById("type-here");
let output = document.getElementById("output");

input.addEventListener("keydown", function(event) {
  output.textContent = "You pressed: " + event.key;
});

Summary

ConceptDescription
addEventListener()Adds an event listener to an element
click, submit, keydownCommon event types
Function to runCalled the event handler
Multiple listenersAllowed per element