Handling Events

Learn to handle DOM events with listeners, delegation, propagation, and default prevention.

Events in the DOM represent interactions like clicks, keypresses, or mouse movements. Using JavaScript, we can respond to these events dynamically.

Adding event listeners

The addEventListener() method attaches an event handler to an element without overwriting existing listeners.

The above JS code adds a click event listener to a button. When the button is clicked, a message is logged to the console.

Handling user actions

Event listeners can respond to a variety of user actions:

The above JS code logs the key pressed by the user in an input field.

Other commonly used events include:

  • click: Triggered when an element is clicked.

  • mouseover: Triggered when the mouse hovers over an element.

  • keydown ...

Access this course and 1400+ top-rated courses and projects.