JavaScript Events - Exercise 1

Use addEventListener() with the click event. The callback runs every time the button is clicked.

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

The event object describes what happened. Its target property points to the element that dispatched the event.

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

Listen for focus and update the input or a nearby message.

const input = document.querySelector('#name');
input.addEventListener('focus', () => {
  input.classList.add('is-active');
});

Use the mouseenter event for a handler that runs when the pointer enters the element.

const card = document.querySelector('.card');
card.addEventListener('mouseenter', () => {
  card.classList.add('highlight');
});

The input event fires whenever the value changes, including typing, pasting, or autofill.

input.addEventListener('input', (event) => {
  document.querySelector('#preview').textContent = event.target.value;
});

Listen for submit on the form. Call preventDefault() when JavaScript should handle the data instead of navigating.

form.addEventListener('submit', (event) => {
  event.preventDefault();
  console.log('Form handled in JavaScript');
});

Keyboard events expose the pressed key through event.key.

document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') console.log('Closed');
});

Keep a reference to the named handler, then pass that same reference to removeEventListener().

function handleClick() { console.log('Clicked'); }
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);