← Back to all tutorials

Events

Listen for and respond to DOM events — attach event listeners to elements and handle clicks, mouse movements, and more.

Events

Events make web pages interactive. When a user clicks a button, types in an input, or scrolls the page, the browser fires an event. You can listen for these events and run JavaScript code in response.

addEventListener

var button = document.querySelector('button');

button.addEventListener('click', function() {
    console.log('Button was clicked!');
});

addEventListener takes two arguments: the event type (string) and a callback function that runs when the event fires.

The Event Object

button.addEventListener('click', function(e) {
    console.log(e);           // The event object
    console.log(e.type);      // "click"
    console.log(e.target);    // The element that was clicked
    console.log(e.target.textContent); // Button text
    console.log(e.clientX);   // Mouse X position
    console.log(e.clientY);   // Mouse Y position
});

The event object (e) contains details about the event — what element triggered it, mouse coordinates, which key was pressed, and more.

Common Event Types

EventFires When
clickElement is clicked
dblclickElement is double-clicked
mouseoverMouse enters the element
mouseoutMouse leaves the element
keydownA key is pressed down
keyupA key is released
submitA form is submitted
focusAn input gains focus
blurAn input loses focus
scrollThe page or element is scrolled

Removing an Event Listener

function handleClick(e) {
    console.log('Clicked!', e.target);
}

button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);

To remove a listener, you must pass the same function reference. Anonymous functions cannot be removed because there is no reference to pass.

Multiple Listeners

var items = document.querySelectorAll('li');

items.forEach(function(item) {
    item.addEventListener('click', function(e) {
        console.log('Clicked:', e.target.textContent);
    });
});

Key Takeaways

  • addEventListener(type, callback) attaches an event listener to an element
  • The callback receives an event object with details about the event
  • e.target is the element that triggered the event
  • Use removeEventListener with a named function to detach listeners