Index

Events and User Interaction

JavaScript for Beginners

10.1 The DOM Event Model

When you interact with a web page—by clicking buttons, typing in forms, or moving your mouse—these actions are called events. The browser detects these events and uses the DOM Event Model to respond and update the page accordingly.

Event Sources and Event Listeners

Every interactive element in a web page, such as buttons, links, or input fields, is represented by a DOM node (like a branch or leaf on a tree). When something happens to these nodes (a click, keypress, etc.), an event is fired.

To react to events, you attach event listeners to DOM nodes. An event listener is like a person standing at a branch, waiting to hear if something happens there.

Example:

button.addEventListener('click', () => {
  alert('Button clicked!');
});

Here, the button is listening for a "click" event and responds by showing an alert.

How Events Travel: Capturing and Bubbling

Events don't just happen on a single element—they travel through the DOM tree. Think of the DOM as a family tree:

When an event happens on a leaf, the event goes through three phases:

  1. Capturing phase (top-down): The event starts at the root and travels down through ancestors to the target element.
  2. Target phase: The event reaches the element that triggered it.
  3. Bubbling phase (bottom-up): The event then bubbles up from the target back to the root, passing through ancestors again.

Most events bubble by default, meaning after the target reacts, its parents get a chance to react too.

Why Propagation Matters

Propagation allows multiple parts of the page to respond to the same event. For example, clicking a button inside a form might trigger the button’s event and also the form’s event listener.

You can control propagation to prevent unwanted reactions by using methods like event.stopPropagation().

Summary

Think of events as messages traveling through a tree, allowing different parts of your webpage to communicate and react seamlessly!

Index

10.2 addEventListener

One of the most common ways to respond to user interactions in JavaScript is by using the addEventListener method. This method attaches event handlers to DOM elements, allowing your webpage to react to clicks, key presses, mouse movements, and many other events.

Attaching Event Listeners with addEventListener

Syntax:

element.addEventListener(eventType, callbackFunction);

Example: Listening for a Button Click

<button id="myButton">Click Me!</button>
const button = document.getElementById('myButton');

button.addEventListener('click', () => {
  alert('Button was clicked!');
});

When you click the button, the alert pops up.

Multiple Events on One Element

You can add listeners for different events on the same element:

button.addEventListener('mouseenter', () => {
  console.log('Mouse entered button');
});

button.addEventListener('mouseleave', () => {
  console.log('Mouse left button');
});

Each event triggers its own callback separately.

Removing Event Listeners

Sometimes, you may want to remove an event listener to stop reacting to an event. To do this, you must use a named function instead of an anonymous one:

function sayHello() {
  console.log('Hello!');
}

button.addEventListener('click', sayHello);

// Later, remove the listener
button.removeEventListener('click', sayHello);

Benefits over Inline Handlers or onclick

Multiple Listeners

addEventListener allows you to add multiple handlers for the same event on one element. Inline handlers (onclick) can only have one.

button.onclick = () => console.log('First'); 
button.onclick = () => console.log('Second'); 
// Only 'Second' runs

button.addEventListener('click', () => console.log('First'));
button.addEventListener('click', () => console.log('Second'));
// Both run

Separation of Concerns

Using addEventListener keeps JavaScript out of your HTML, making your code cleaner and easier to maintain.

More Control

addEventListener supports options like capturing/bubbling phases, passive listeners, and once-only listeners for better event handling.

Summary

By mastering addEventListener, you’ll gain fine-grained control over user interactions on your web pages.

Index

10.3 Handling Click, Keyboard, and Form Events

Handling user interactions is at the heart of dynamic web pages. In this section, we’ll explore how to respond to clicks, keyboard inputs, and form submissions using event listeners, along with practical tips like preventing default behaviors and validating inputs.

Handling Click Events

Click events are one of the most common ways users interact with a page.

Example – Toggle a class on a button click:

<button id="toggleBtn">Toggle Highlight</button>
<div id="box" style="width:100px; height:100px; background-color:lightgray;"></div>
const button = document.getElementById('toggleBtn');
const box = document.getElementById('box');

button.addEventListener('click', () => {
  box.classList.toggle('highlight');
});
.highlight {
  background-color: gold;
  border: 2px solid orange;
}

Clicking the button toggles the highlight style on the box.

Handling Keyboard Events

Keyboard events like keydown and keyup help capture user input from the keyboard.

Example – Detect when the user presses the "Enter" key:

document.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    alert('You pressed Enter!');
  }
});

Tip: Use event.key to detect which key was pressed. You can also handle specific keys like arrows or function keys.

Handling Form Submission and Validation

By default, submitting a form reloads the page. Often, we want to prevent this and validate inputs instead.

Example – Simple form validation:

<form id="signupForm">
  <input type="text" id="username" placeholder="Username" />
  <button type="submit">Sign Up</button>
</form>
<p id="message"></p>
const form = document.getElementById('signupForm');
const usernameInput = document.getElementById('username');
const message = document.getElementById('message');

form.addEventListener('submit', (event) => {
  event.preventDefault();  // Prevent page reload

  const username = usernameInput.value.trim();

  if (username.length < 3) {
    message.textContent = 'Username must be at least 3 characters long.';
    message.style.color = 'red';
  } else {
    message.textContent = `Welcome, ${username}!`;
    message.style.color = 'green';
    // You can proceed with further processing here
  }
});

Practical Tips

Summary

Event Type Common Use Case Key Properties/Methods
Click Button presses, toggling click event, classList
Keyboard Detecting key presses keydown, keyup, event.key
Form Submit Validate inputs, prevent reload submit, event.preventDefault()

By mastering these event handling techniques, you'll be able to create interactive and user-friendly web pages that respond intuitively to user actions.

Index

10.4 Event Object and Propagation

When an event occurs in the browser, an event object is automatically passed to the event handler. This object contains useful information and methods that help you understand and control what happens during the event.

The Event Object: Key Properties and Methods

When you add an event listener, you can access the event object as the first parameter in your callback function:

element.addEventListener('click', (event) => {
  // event is the event object
});

Here are some important properties and methods:

Property/Method Description
event.target The element where the event originated (clicked, typed, etc.)
event.currentTarget The element that the event listener is currently attached to
event.preventDefault() Stops the browser's default behavior (e.g., link navigation, form submit)
event.stopPropagation() Stops the event from moving further through the DOM (no more bubbling or capturing)

Understanding target vs. currentTarget

Suppose you have a button inside a container, both with click listeners:

<div id="container">
  <button id="btn">Click me</button>
</div>
const container = document.getElementById('container');
const button = document.getElementById('btn');

container.addEventListener('click', (event) => {
  console.log('container currentTarget:', event.currentTarget.id);
  console.log('container target:', event.target.id);
});

button.addEventListener('click', (event) => {
  console.log('button currentTarget:', event.currentTarget.id);
  console.log('button target:', event.target.id);
});

Event Propagation: Capturing and Bubbling Phases

When an event happens on a nested element, it flows through the DOM in phases:

  1. Capturing phase: The event travels down from the root (document) through ancestors to the target element.
  2. Target phase: The event reaches the element where it occurred.
  3. Bubbling phase: The event travels up from the target back through ancestors to the root.

Visual analogy: Imagine dropping a pebble in a tree’s leaves; the sound travels down branches first (capturing), hits the leaf (target), then echoes up through branches again (bubbling).

Controlling Propagation and Default Behavior

<div id="outer" style="padding:20px; background:#eee;">
  Outer Div
  <a href="https://example.com" id="myLink">Go to Example.com</a>
</div>
const outer = document.getElementById('outer');
const link = document.getElementById('myLink');

outer.addEventListener('click', () => {
  console.log('Outer div clicked');
});

link.addEventListener('click', (event) => {
  event.preventDefault();        // Prevent link navigation
  event.stopPropagation();       // Stop bubbling up to outer div
  alert('Link clicked but navigation prevented!');
});

Clicking the link will show the alert, won’t navigate away, and won’t trigger the outer div’s click handler.

Summary

Mastering these tools allows you to create precise and predictable interactive behaviors in your web apps.

Index