๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript DOM Events

An event is something that happens on the page, like a click on an element. A script can attach a function that runs when a chosen event happens.

Attach a click handler

The handler changes the element text and logs a line. The click call at the end fires the event.

const demo = document.getElementById("demo");
demo.addEventListener("click", function () {
  demo.textContent = "Clicked";
  console.log("Handler ran");
});
demo.click();

The handler changes the page

The log line inside the handler reads the text it just set. That read-back is the proof the click worked.

const demo = document.getElementById("demo");
demo.addEventListener("click", function () {
  demo.textContent = "Thanks for clicking";
  console.log(demo.textContent);
});
demo.click();

Two handlers, one event

Both handlers are attached to the click event. They run in the order they were attached.

const demo = document.getElementById("demo");
demo.addEventListener("click", function () {
  console.log("First handler");
});
demo.addEventListener("click", function () {
  console.log("Second handler");
});
demo.click();

Example

const demo = document.getElementById("demo");
demo.addEventListener("click", function () {
  demo.textContent = "Paragraph clicked";
  console.log(demo.textContent);
});
demo.click();
console.log(demo.textContent);

Key points

  • addEventListener attaches a handler to an element for one event.
  • A handler is a function that runs when the event happens.
  • Array iteration earlier in this course used the same idea, passing a function to be run later.
  • One element can hold several handlers for the same event, and all of them run.
  • A real click from a reader runs the same handler, and the script clicks itself here so the result can be shown.

In this example, the script attaches a click handler that replaces the paragraph text and logs it. The script then clicks the paragraph itself, so the handler runs during the run. The final line reads the text back as proof.

Note

the handler can receive an event object that describes what happened.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does addEventListener do?