mc0de
JavaScript · Lesson 12 of 17

JavaScript Events

Make your website listen and respond! Learn how JavaScript detects clicks, keyboard input, mouse movements, and form activity to create interactive experiences.

Event Listeners Click Events Keyboard Events Event Objects
● ● ●   events.js
const button =
  document.getElementById(
    "myButton"
  );

button.addEventListener(
  "click", () => {
    console.log("Clicked!");
  }
);
LIVE EVENT MONITOR
> Waiting for an event… > Click the button below.
01 / Getting Started

What Is a JavaScript Event?

Imagine a webpage with a button labeled “Show Message.” The page looks perfectly normal until someone clicks that button. At that moment, JavaScript can respond by displaying a message, changing a color, or performing another action.

An event is a notification that something has happened. It might be a mouse click, a key being pressed, text being entered, or a form being submitted.

JavaScript can listen for these events and execute a function when they occur.

Listening for a button click
const button = document.getElementById("helloButton");

button.addEventListener("click", function() {
  console.log("Hello! You clicked the button.");
});

The browser waits for a click on the selected button. When the click happens, JavaScript runs the function provided to addEventListener().

Connection to Lesson 11: The DOM lets JavaScript find and change elements. Events tell JavaScript when to make those changes.
02 / Event Listeners

Meet addEventListener()

The most common way to respond to browser events is addEventListener(). It accepts an event type and a function that should run when that event occurs.

The basic structure
element.addEventListener("eventName", function() {
  // Code that runs when the event happens
});

You can use a named function instead of writing it directly inside the listener.

Using a named function
const button = document.getElementById("saveButton");

function showConfirmation() {
  console.log("Your changes were saved!");
}

button.addEventListener("click", showConfirmation);

Notice that showConfirmation is passed without parentheses. Writing showConfirmation() would call the function immediately instead of registering it as the event handler.

You can attach more than one event listener to an element. This makes it possible to keep different behaviors organized.

03 / Mouse Events

Respond to Clicks and Pointer Movement

Mouse and pointer interactions help make interfaces feel responsive. Buttons, cards, menus, and other interactive elements often respond to clicks or pointer movement.

Common mouse events
const card = document.getElementById("demoCard");

card.addEventListener("click", function() {
  console.log("Card clicked!");
});

card.addEventListener("mouseenter", function() {
  console.log("Pointer entered the card.");
});

card.addEventListener("mouseleave", function() {
  console.log("Pointer left the card.");
});

click fires when an element is activated with a pointer and can also fire from keyboard activation on native buttons. mouseenter occurs when the pointer enters an element, and mouseleave occurs when it leaves.

Accessibility tip: Use real <button> elements for actions. They support keyboard activation and other useful browser behavior automatically.
04 / Keyboard Events

Listen for Keys Being Pressed

Keyboard events allow websites to respond when visitors press keys. This is useful for shortcuts, games, and input-related features.

Detecting the Enter key
const input = document.getElementById("nameInput");

input.addEventListener("keydown", function(event) {
  if (event.key === "Enter") {
    console.log("Enter was pressed!");
  }
});

The keydown event fires when a key is pressed. The event.key property identifies the key, such as "Enter", "Escape", or "a".

For text fields, the input event is generally a better choice when your goal is to detect changes in the field’s value—including pasted text.

Reacting as someone types
input.addEventListener("input", function() {
  console.log("Current value:", input.value);
});
05 / The Event Object

Learn What Happened

When an event occurs, the browser passes an event object to your listener. This object contains information about the interaction.

Exploring event details
const button = document.getElementById("myButton");

button.addEventListener("click", function(event) {
  console.log(event.type);
  console.log(event.target);
  console.log(event.currentTarget);
});

event.type tells you which event occurred. event.target identifies the element where the event originated, while event.currentTarget identifies the element whose listener is currently running.

These can be different when events bubble from a child element to an ancestor.

Remember: The parameter doesn’t have to be named event. You may see e instead. Both are conventional names for the same event object.
06 / Forms and Event Behavior

Control Form Submission

HTML forms have a default behavior: when submitted, the browser usually navigates or reloads to process the submission. Sometimes you want JavaScript to handle the form instead.

Handling a form submission
const form = document.getElementById("contactForm");

form.addEventListener("submit", function(event) {
  event.preventDefault();

  const name = document.getElementById("name").value;

  console.log("Hello, " + name + "!");
});

preventDefault() prevents the browser’s default submission behavior when the event is cancelable. This allows you to display a confirmation or validate the input without immediately navigating away.

For example, you could update a message on the page using textContent.

Coming next: Lesson 13 explores form validation in depth, including required fields, email formats, and helpful error messages.
07 / Events in Action

Explore Different User Interactions

Let’s see several event types working together. The explorer below records clicks, text changes, keyboard actions, and pointer activity.

Live Event Explorer

Interact with the controls and watch the activity log.

Event log is ready.

Notice how the same page can respond differently depending on which event occurs. That’s the foundation of interactive interfaces.

Try this: Press Tab to focus the second button. Focus events make it possible to provide feedback for keyboard users as well as pointer users.
🚀 mC0de Challenge

Build an Interactive Event Playground

Create a webpage that responds to several types of user interactions and displays a live activity dashboard.

Your Mission

  1. Create a button that counts how many times it has been clicked.
  2. Add a text input that updates a live message as the visitor types.
  3. Detect when the visitor presses Enter inside the input.
  4. Add an interactive area that responds to pointer entry and exit.
  5. Display the most recent event in an activity log.
  6. Use addEventListener() for every interaction.
  7. Create a Reset button that clears the counters and log.
Extra challenge: Add an event history list and a counter for total interactions. Use an array to store event descriptions and render the list using DOM methods.
💻 Interactive JavaScript Sandbox

Build Your Event Playground!

Edit the code and test how your webpage responds. The starter includes clicks, live typing, Enter detection, and pointer interactions. Load Solution adds an event history, total counter, and a polished activity dashboard.

Live Result
Lesson 12 Recap

What You’ve Learned

You’re Building Truly Interactive Websites!

You’ve learned how to connect user actions to JavaScript functions and create interfaces that respond immediately.

  • Understand browser events and event listeners.
  • Use addEventListener() with named and anonymous functions.
  • Handle click, mouse, and keyboard interactions.
  • Respond to changes using the input event.
  • Inspect event details using the event object.
  • Control form submission with preventDefault().
  • Build an interactive Event Playground.

Next up: Form Validation — learn to check user input and display helpful messages before submitting forms!

Your Learning Journey

0 / 17 Completed

Twelve lessons completed in the pathway means you’re closing in on the final project!

🎉

You've Mastered JavaScript Events!

You can now make websites respond to clicks, keyboard input, pointer movement, and form activity. You've also built an Event Playground that tracks interactions in real time!