Modern JavaScript Essentials

Lesson 5 of 6

Events and the DOM

Beyond reading the DOM, real pages react to what the user does, clicks, typing, submitting forms, through events.

const button = document.querySelector('#save');
button.addEventListener('click', (event) => {
  event.preventDefault();
  console.log('Saved!');
});

const input = document.querySelector('#name');
input.addEventListener('input', (event) => {
  console.log('Typing:', event.target.value);
});

This needs a real web page with a #save button and #name input, so it's read-only here, you'll wire up real event handlers in the final project.

Key ideas

  • addEventListener(type, handler) attaches a handler for an event type ('click', 'input', 'submit', and many more) without overwriting any handlers already attached.
  • The event object passed to your handler describes what happened, event.target is the element the event fired on, event.target.value reads an input's current text.
  • event.preventDefault() stops the browser's default behavior, most commonly used to stop a form from reloading the page on submit.

📝 Events Quiz

Passing score: 70%
  1. 1.Which method attaches an event handler to an element?

  2. 2.Calling event.____() stops a form's default submit behavior.

  3. 3.An element can have more than one event listener attached to it at the same time.