Skip to content

Introduction to Events and addEventListener

Every module until now has been JavaScript that runs once when the page loads, then stops. Events change that. An event is a signal the browser fires when something happens — a click, a keystroke, a form submission, the page finishing load. Event listeners are how JavaScript responds to those signals.

The browser fires events constantly. Some examples:

EventWhen it fires
clickUser clicks any element
keydownUser presses a key
submitUser submits a form
inputUser types in a text field
scrollUser scrolls the page
DOMContentLoadedThe DOM is fully parsed and ready

Events are signals, not code. Your code does not create them — you just listen for them.

Before you begin — verify the hamburger button

Section titled “Before you begin — verify the hamburger button”

In CSS Foundations M08 L02 you added <button class="hamburger-btn"> to every STO HTML file and wrote the CSS that hides the nav on mobile and shows it when .nav-open is present. The examples and exercise in this module depend on that work.

Before continuing, open index.html in Chrome at a narrow viewport and confirm:

  • The hamburger button is visible in the header
  • The nav links are hidden

If either is missing, go back to CSS M08 L02 and complete that lesson first.

addEventListener attaches a function to run when an event fires on an element:

element.addEventListener(eventType, handlerFunction);
  • eventType — a string: 'click', 'input', 'submit', etc.
  • handlerFunction — the function to run when the event fires
const btn = document.querySelector('.hamburger-btn');
btn.addEventListener('click', function() {
console.log('nav toggle clicked');
});

Or with an arrow function:

btn.addEventListener('click', () => {
console.log('nav toggle clicked');
});

Or with a named function defined separately:

function handleNavClick() {
console.log('nav toggle clicked');
}
btn.addEventListener('click', handleNavClick);

All three work. Named functions have one advantage: they can be removed later.

Inline HTML attributes vs addEventListener

Section titled “Inline HTML attributes vs addEventListener”

You may see event handlers in HTML like this:

<button onclick="handleClick()">Click me</button>

This is the older inline attribute approach. It mixes JavaScript into HTML, allows only one handler per event, and is harder to maintain. Use addEventListener instead:

  • Clean separation of HTML and JavaScript
  • Multiple listeners can be attached to the same element and event
  • Listeners can be removed programmatically

If your script runs before the DOM is parsed, selectors return null:

// In a script without defer
const btn = document.querySelector('.hamburger-btn');
btn.addEventListener('click', ...); // TypeError: btn is null

With defer on your script tag, the DOM is always ready when the script runs — this is not a concern. If you cannot use defer, wrap your setup code:

document.addEventListener('DOMContentLoaded', () => {
const btn = document.querySelector('.hamburger-btn');
btn.addEventListener('click', handleNavClick);
});

In the STO project with defer, your code in main.js always runs after the DOM is ready. You do not need DOMContentLoaded wrappers.

Remove a listener with removeEventListener. The handler must be a named function reference — anonymous functions cannot be removed because there is no way to reference the same function object:

function handleNavClick() {
console.log('nav toggle clicked');
}
btn.addEventListener('click', handleNavClick);
// Later, to remove it:
btn.removeEventListener('click', handleNavClick);

In most beginner projects, listeners are rarely removed — they persist for the life of the page. You will need removeEventListener when building cleanup logic or when conditionally disabling interactions.

On the STO site, open the Console and attach your first real listener:

const btn = document.querySelector('.hamburger-btn');
if (btn) {
btn.addEventListener('click', () => {
console.log('nav toggle clicked');
});
console.log('Listener attached. Click the hamburger button.');
} else {
console.log('Hamburger button not found — check the selector.');
}

Open index.html in Chrome, open DevTools → Console, and paste the code above. Click the hamburger button and confirm the message appears on every click.

  • An event is a signal the browser fires when something happens — click, keydown, scroll, submit, and many others.
  • element.addEventListener(type, handler) is the standard way to respond to events.
  • Prefer addEventListener over inline HTML onclick attributes — it separates concerns and allows multiple listeners.
  • With defer on your script, the DOM is always ready — no need for DOMContentLoaded wrappers.
  • removeEventListener requires a named function reference — anonymous functions cannot be removed.