Lesson 58 +15 XP

JavaScript Events

JavaScript Events

Events are things that happen in the browser: clicks, key presses, page loads. JavaScript can react to them.

Common events

EventHappens when
clickuser clicks an element
mouseovermouse moves over an element
keydowna key is pressed
submita form is submitted
loadthe page finishes loading

React with addEventListener

document.getElementById("myBtn").addEventListener("click", function() {
  alert("Button clicked!");
});

Inline onclick (avoid)

<button onclick="myFunction()">Click</button>

This mixes HTML and JavaScript. addEventListener is cleaner.

Multiple listeners

addEventListener lets you attach several handlers to the same element and event.

Event parameters

The handler receives an event object with details:

el.addEventListener("click", function(event) {
  console.log(event.target); // the clicked element
});

TL;DR

  • Events include click, keydown, submit, and load.
  • addEventListener attaches a handler.
  • Prefer addEventListener over inline onclick.
  • The event object holds details like target.