Your files never leave your device
Advertisement

Event Listeners

Events are things that happen in the browser—like clicks, scrolls, or keystrokes. Event listeners let JavaScript react to them.

Adding an Event Listener

You attach an event listener to a DOM element, specifying the event type and a function to run.

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

button.addEventListener('click', function(event) {
  console.log("Button was clicked!");
  // 'event' contains data about the click
});
          

Input Events

You can listen to input fields to get user text as they type.

const input = document.querySelector('input');
input.addEventListener('input', (e) => {
  console.log("Current value:", e.target.value);
});
          

Practice

Challenge 1: Add a click listener to the window object that logs "Clicked!" anywhere on the page.

Related Guides

Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement