Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

Event Handling Basics

Author: Sophia

what's covered
In this lesson, you will learn how JavaScript responds to user interactions through events. Events are the foundation of interactive web pages, allowing your code to react when visitors click buttons, type in forms, move their mouse, and more. Specifically, this lesson will cover the following:

Table of Contents

1. Events

Every time a user interacts with a web page, the browser generates a signal called an event. These signals notify your JavaScript code that something has happened, giving you the opportunity to respond. Without events, web pages would remain static, with no way to react to user input.

An event is a signal from the browser indicating that something has occurred on the page. Events can be triggered by user actions like clicking a button, typing in a form, or pressing a key. They can also be triggered by browser actions, such as when a page finishes loading or when the window is resized.

Think of events as notifications. When a user clicks a button, the browser sends a “click” notification to that element. Your JavaScript code can listen for these notifications and run specific functions when they occur.

The flow from action to response follows a consistent pattern:

  • The user performs an action (such as clicking a button).
  • The browser detects the action and creates an event.
  • The browser checks whether any code is listening for that event.
  • If a listener exists, the browser calls the associated function.
  • The function executes and creates a response.
This process happens almost instantly, which is why modern web pages feel responsive and interactive. As seen in the diagram, an event moves from a user action to a JavaScript response.

Diagram showing an event flow: user action triggers browser detection, an event is created, a listener detects it, and a handler function runs.

key concept
Events create a communication channel between the user and your code. The browser detects the user action, generates an event, and your JavaScript responds by executing a function. This pattern—action, event, response—is the foundation of all interactive web applications.

The browser can detect many different types of events. Choosing the correct event type allows you to create interactions that match user expectations.

Mouse events occur when users interact with a mouse or trackpad:

Event Type Triggered When
click User clicks an element
dblclick User double-clicks an element
mouseenter Mouse pointer enters an element
mouseleave Mouse pointer leaves an element
mousemove Mouse pointer moves over an element

Keyboard events occur when users press keys:

Event Type Triggered When
keydown User presses a key down
keyup User releases a key

Form events relate to user input:

Event Type Triggered When
submit Form is submitted
change Input value changes and the element loses focus
input Input value changes immediately
focus Element receives focus
blur Element loses focus

Document and window events relate to the page itself:

Event Type Triggered When
load Page and resources finish loading
scroll User scrolls the page
resize Browser window is resized

Different event types are suited to different interactions. The following examples show how common scenarios map to specific events:

Scenario Event
Showing a dropdown menu when clicked click
Validating a form field after the user leaves it blur
Updating a character count as the user types input
Enlarging an image when the mouse hovers over it mouseenter
Reacting when the user presses “Escape” keydown

try it
A designer wants the page to highlight a search result row whenever the user moves their mouse over it.
Which event type should you listen for?
The mouseenter event is the right choice. It fires once when the mouse pointer enters the element, which is exactly when you want the highlight to appear. You would pair it with a mouseleave listener to remove the highlight when the pointer exits.

big idea
Events are signals generated by the browser when actions occur on a web page. By choosing the correct event type, you can design interactions that respond naturally to user behavior.

term to know
Event
A signal from the browser indicating that something has occurred, such as a user clicking, typing, or the page finishing loading.


2. Event Listeners

Now that you understand what events are, the next step is learning how to respond to them. When a user clicks a button or types into a form, the browser detects the event but does not take action on its own. You need to tell it what to do.

This is where event listeners come in. An event listener “listens” for a specific event on a specific element and runs code when that event occurs.

JavaScript provides the addEventListener() method to set this up. It allows you to connect an event, such as a click, with a function that should run in response.

terms to know
Event Listener
Code that waits for a specific event to occur on an element and triggers a function in response.
addEventListener Method
A JavaScript method that attaches an event listener to an element, specifying what event to detect and what function to run.

2a. 'addEventListener()'

An event listener connects an event to a specific action. It tells the browser, “When this event happens on this element, run this code.”

JavaScript provides the addEventListener() method to create this connection. This method allows you to specify both the event to watch for and the function to run when it occurs.

The basic syntax is:

element.addEventListener('eventType', handlerFunction);

In this syntax:

  • element is the DOM element you want to watch.
  • 'eventType' is a string naming the event (like 'click' or 'keydown').
  • handlerFunction is the function the browser will call when the event fires.
The following diagram shows how each part of the addEventListener() syntax connects an element, an event, and a function.

Diagram of addEventListener: It shows button.addEventListener('click', handleClick) with parts—target element, method, event type, and handler function—and notes the common mistake of calling handler immediately.

Now that you understand how each part of the addEventListener() method fits together, you can see how it works.

EXAMPLE

Responding to a button click:

const button = document.querySelector('#myButton');

button.addEventListener('click', function() {
alert('Button was clicked!');
});
In this code:

  • document.querySelector('#myButton') selects the button element.
  • addEventListener() attaches a listener to that element.
  • 'click' tells the browser which event to watch for.
  • The function defines what happens when the click occurs—in this case, showing an alert.

You can attach multiple event listeners to the same element. Each listener operates independently, so a single button can respond to clicks, hovers, and other events at the same time.

EXAMPLE

Listening for two different events on one button:

const button = document.querySelector('#myButton');

button.addEventListener('click', function() {
console.log('Click detected');
});

button.addEventListener('mouseenter', function() {
console.log('Mouse entered button area');
});
In this code:

  • The first listener fires when the button is clicked.
  • The second listener fires when the mouse pointer enters the button.
  • Both listeners are active at the same time and operate independently.

key concept
The addEventListener() method takes two main arguments: the event type as a string (like 'click' or 'keydown') and a function that executes when the event fires. The function is often called an event handler or callback function.

try it
In index.html, make sure a button with id="demo-btn" is present. If not, add it:

Copy
<button id="demo-btn">Click me</button>
Open the browser console in your Codespace preview.

In js/scripts.js, select the button with document.querySelector('#demo-btn') and store it in a variable.

  • Add an event listener to the button that listens for a 'click' event.
  • Inside the event handler, use console.log() to display the message "Button clicked!".
  • Click the button several times and observe when the message appears.
When does the message “Button clicked!” appear?
The message appears only when the button is clicked. The function does not run when the code is written. It runs later, when the click event occurs.
What would happen if you ran the same addEventListener() line three times in a row?
The button would have three separate click listeners attached, each running independently. Clicking the button once would log “Button clicked!” three times, once for each listener. Each call to addEventListener() adds a new listener and does not replace existing ones.

2b. Handler Functions

The function you pass to addEventListener() is called an event handler (also known as a callback function). This function defines what should happen when the event occurs. There are several ways to write event handler functions, depending on how you want to organize your code.

key concept
An event handler is the function that runs in response to an event. It is not executed immediately. Instead, the browser runs it later when the specified event occurs.

You can define event handlers in three common ways.

Anonymous functions are written directly inside addEventListener(). This approach is useful for a short, simple behavior that does not need to be reused.

EXAMPLE

button.addEventListener('click', function() {
console.log('Clicked!');
});
In this code:

  • addEventListener() attaches a click event listener to the button.
  • 'click' tells the browser to listen for a click event.
  • The anonymous function defines what happens when the button is clicked.
  • When the button is clicked, the message “Clicked!” is logged to the console.

Instead of writing the function directly inside addEventListener(), you can define the function separately and then use it as the event handler.

EXAMPLE

function handleClick() {
console.log('Clicked!');
}

button.addEventListener('click', handleClick);
In this code:

  • The function handleClick is defined separately and given a name.
  • addEventListener() attaches a click event listener to the button.
  • Instead of writing the function inline, the function name handleClick is passed as the event handler.
  • When the button is clicked, the browser runs the handleClick function, logging “Clicked!” to the console.

Arrow functions provide a shorter way to write functions. They are commonly used when you want a concise, inline event handler without creating a separate named function.

This approach is useful for simple, one-time behaviors where readability and brevity are more important than reuse.

EXAMPLE

button.addEventListener('click', () => {
console.log('Clicked!');
});
In this code:

  • The arrow function () => { ... } defines the event handler directly inside addEventListener().
  • 'click' tells the browser to listen for a click event.
  • The function runs only when the button is clicked.
  • This creates the same behavior as the previous examples, but with a shorter and more concise syntax.

try it
Consider this code:

const heading = document.querySelector('h1'); heading.addEventListener('click', function() {
heading.style.color = 'blue';
});
What happens when a user clicks the h1 element?
When the user clicks the heading, the event listener detects the click and runs the handler function. The function changes the heading’s text color to blue by setting its style.color property.

term to know
Event Handler
A function that executes in response to an event, also called a callback function.


3. Event Object

When an event occurs and your handler function runs, the browser also provides additional information about that event.

This information is stored in an object called the event object. It is automatically passed to your handler function, giving you access to details such as which element triggered the event or which key was pressed.

The following diagram highlights how the event object is passed into your handler and some of the most commonly used properties it provides.

Diagram showing how the event object is passed into an event handler and examples of common properties such as type, target, key, clientX and clientY, and preventDefault.

term to know
Event Object
An object automatically created by the browser when an event occurs, containing properties and methods with information about the event.

3a. Accessing Event Information

To access the event object, you add a parameter to your handler function. When the event occurs, the browser automatically passes the event object into that function as an argument. By convention, this parameter is often named event, e, or evt.

EXAMPLE

Displaying the event object in the console:

const button = document.querySelector('#myButton');

button.addEventListener('click', function(event) {
console.log(event);
});
In this code:

  • The handler function includes a parameter named event.
  • When the button is clicked, the browser passes the event object into that parameter.
  • console.log(event) displays the event object so you can explore its properties.

The event object contains properties that describe the event, such as which element triggered it, where it occurred, or which key was pressed. These details allow your code to respond differently based on what happened.

EXAMPLE

Reading multiple event properties:

const button = document.querySelector('#myButton');

button.addEventListener('click', function(event) {
console.log('Event type:', event.type);
console.log('Target element:', event.target);
console.log('Mouse X position:', event.clientX);
});
In this code:

  • event.type returns the name of the event (here, 'click').
  • event.target returns the actual element the user interacted with.
  • event.clientX returns the horizontal pixel position of the click in the viewport.

By accessing specific properties, you can use event data to create more dynamic behavior.

EXAMPLE

Tracking click coordinates anywhere on the page:

document.addEventListener('click', function(event) {
const x = event.clientX;
const y = event.clientY;
console.log(`Clicked at position: ${x}, ${y}`);
});
In this code:

  • The listener is attached to document, so it fires for clicks anywhere on the page.
  • event.clientX and event.clientY give the click position relative to the viewport.
  • The values are displayed in the console to show where the user clicked.

This approach allows your code to respond differently based on where and how the user interacts with the page.

3b. Common Properties

The event object includes many properties, but you do not need to memorize all of them. Instead, focus on a few key properties that help your code respond to user actions in meaningful ways.

Some properties are available for most events. For example, event.type tells you what kind of event occurred, such as a click or key press, which allows your code to handle different types of interactions. The event.target property identifies the element that triggered the event, while event.currentTarget refers to the element where the event listener is attached. You may also see event.timeStamp, which records when the event occurred.

Among these, event.target is especially important because it tells you exactly which element the user interacted with. This allows your code to respond differently depending on what was clicked.

Other properties depend on the type of event. For mouse interactions, properties like event.clientX and event.clientY provide the position of the pointer within the viewport, which can be used for features like tracking clicks or positioning elements on the screen. The event.pageX and event.pageY properties give the position relative to the full document, and event.button indicates which mouse button was pressed.

For keyboard interactions, event.key identifies the key that was pressed, such as “Enter” or “a,” allowing your code to trigger actions based on specific keys. The event.code property refers to the physical key on the keyboard, and properties like event.shiftKey, event.ctrlKey, and event.altKey indicate whether modifier keys were held, which is useful for handling keyboard shortcuts.

key concept
The event.target property identifies the element that triggered the event. This allows a single event listener to handle interactions from multiple elements by checking which element was clicked.

try it
  • In index.html, make sure several clickable elements are present (two or three buttons or links).
  • In js/scripts.js, add an event listener on document that listens for a click event.
  • Inside the handler function, log event.target and event.target.tagName to the console. (Hint: Use console.log() to display values in the console.)
  • Open the preview in your Codespace.
  • Click on different elements on the page.
  • Observe how the console output changes depending on what you click.
  • Notice that event.target identifies the exact element that triggered the event.
Examine this code.

document.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
closeModal();
}
});
What does this event listener do?
This event listener detects key presses anywhere on the page. Each time a key is pressed, the browser passes an event object into the handler function. The code checks the value of event.key to determine which key was pressed. If the key is 'Escape', the closeModal() function is called. This pattern is commonly used to allow users to close menus or popups using the keyboard.

big idea
The event object provides detailed information about each event, including which element triggered it, where it occurred, and what keys or buttons were involved. By examining event properties, your handler functions can make intelligent decisions about how to respond to different situations.

summary
In this lesson, you explored events and how user actions trigger changes in a web page. You learned how to use event listeners, including addEventListener() and handler functions, to respond to those actions with JavaScript. You also examined the event object, including accessing event information and using common properties, to understand details about each event. Together, these concepts allow you to build interactive features that respond dynamically to user input.

Source: THIS TUTORIAL WAS AUTHORED BY SOPHIA LEARNING. PLEASE SEE OUR TERMS OF USE.

REFERENCES

Mozilla Developer Network. (n.d.). How the web works. developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works

Terms to Know
Event

A signal from the browser indicating that something has occurred, such as a user clicking, typing, or the page finishing loading.

Event Handler

A function that executes in response to an event, also called a callback function.

Event Listener

Code that waits for a specific event to occur on an element and triggers a function in response.

Event Object

An object automatically created by the browser when an event occurs, containing properties and methods with information about the event.

addEventListener Method

A JavaScript method that attaches an event listener to an element, specifying what event to detect and what function to run.