JavaScript AcademyProfessional Engineering

Learning object 40 of 100

Event listener laboratory

Attach, trigger and remove listeners on a live preview, and read the event object that each listener receives.

Loading…

What it shows

addEventListener registers a function that runs every time the event happens. Several listeners can share an event and run in the order they were added. Each listener receives an event object with the type, the target where the event started, the currentTarget whose listener is running, key and modifier details, and preventDefault for cancelling the browser's own action.

Guided experiment

  1. In Listeners, click the button in the preview a few times and watch the console.
  2. In Event object, click the icon inside the button. Why do target and currentTarget differ?
  3. In Keyboard, click into the field and press Enter, Escape and Ctrl+S.

Predict

A listener is added twice with the same function. How many times does it run per click?

Related

Lessons: Lesson 56: Event listeners, Lesson 57: Event objects

Projects: Project 9: Shopping Cart Price Calculator

Source: web/assets/js/objects/object-040.js in the companion repository.