1.7K Views

JS110 - Events & Event Listeners

Learn how JavaScript handles user interactions through events like click, input, and keydown using addEventListener.

Events allow your website to react to user actions such as clicks, scrolling, typing, or mouse movement.
JavaScript listens for these actions and runs specific functions when they occur.

What Is an Event?

An event is any interaction that happens in the browser.
Common events include:

  • click
  • input
  • submit
  • keydown
  • mouseover
  • scroll

addEventListener

The primary way to listen for events is using addEventListener.

const button = document.querySelector("button");
 
button.addEventListener("click", function() {
  console.log("Button clicked");
});

Using Arrow Functions

button.addEventListener("click", () => {
  console.log("Clicked!");
});

Getting Event Information

Every event listener receives an event object.

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

Common event properties:

  • event.target
  • event.type
  • event.key (for keyboard events)

Input Events

const input = document.querySelector("input");
 
input.addEventListener("input", function(e) {
  console.log("Typed: " + e.target.value);
});

Keydown Events

document.addEventListener("keydown", function(e) {
  console.log("Key pressed: " + e.key);
});

Preventing Default Behavior

Useful for forms and links.

const form = document.querySelector("form");
 
form.addEventListener("submit", function(e) {
  e.preventDefault();
  console.log("Form blocked");
});

Event Bubbling (Default Behavior)

Events bubble from the target element up through its parents.

<div id="parent">
  <button id="child">Click Me!</button>
</div>
document.getElementById("parent").addEventListener("click", () => {
  console.log("Parent clicked");
});
 
document.getElementById("child").addEventListener("click", () => {
  console.log("Child clicked");
});

Clicking the button triggers both listeners unless stopped.


Stopping Event Propagation

document.getElementById("child").addEventListener("click", function(e) {
  e.stopPropagation();
  console.log("Only child triggered");
});

Event Delegation

Efficient way to handle many similar elements.

document.addEventListener("click", function(e) {
  if (e.target.matches(".item")) {
    console.log("Item clicked: " + e.target.textContent);
  }
});

Summary

In this lesson, you learned:

  • What events are
  • How to use addEventListener
  • How to read event information
  • Input and keyboard events
  • How bubbling works
  • How to stop propagation
  • Event delegation techniques

In the next lesson, we will explore the Fetch API and learn how JavaScript communicates with external servers.