Lesson 13 of 18

Events & Interactivity 🖰

🎯 Grades 9–12 ⏱ ~35 minutes 💚 Intermediate

What You'll Learn

  • Add event listeners to elements
  • Handle click, input, and keyboard events
  • Build an interactive UI

addEventListener

Events fire when users interact with your page — clicking, typing, hovering. Use addEventListener to respond:

JavaScript
const btn = document.getElementById('myBtn');

btn.addEventListener('click', () => {
  console.log('Button was clicked!');
  btn.textContent = 'Clicked!';
  btn.style.background = '#00C853';
});

Common Events

JavaScript
// Click
btn.addEventListener('click', handleClick);

// Input changes
const input = document.getElementById('search');
input.addEventListener('input', (e) => {
  console.log('User typed:', e.target.value);
});

// Form submit
const form = document.getElementById('myForm');
form.addEventListener('submit', (e) => {
  e.preventDefault();  // stop page reload!
  const name = document.getElementById('name').value;
  alert(`Hello, ${name}!`);
});

// Keyboard
document.addEventListener('keydown', (e) => {
  console.log('Key pressed:', e.key);
});
💡
e.preventDefault()

Always call e.preventDefault() in form submit handlers. Without it, the browser reloads the page and you lose all your JavaScript state.

🖰">Interactive Dark Mode Toggle

Add a "Toggle Dark Mode" button. When clicked, it should toggle a dark-mode class on the body element. In your CSS, define body.dark-mode with a dark background and light text. Now your page has a real dark mode!

Quick Check

What method adds an event listener to an element?

Aelement.on()
Belement.addEventListener()
Celement.attach()

Why do we call e.preventDefault() in a form submit handler?

ATo make the form submit faster
BTo prevent the page from reloading
CTo add a border to the form

Which event fires every time a user types in an input?

Achange
Bkeydown
Cinput