JavaScript lesson · 24 min

JavaScript DOM Events

React to clicks with addEventListener and update the page after an event.

Code runs locally in your browser

What you will practice

  • Attach a click event listener to a button.
  • Update a variable when the event happens.
  • Reflect the new value back into the page.

What this means

An event is something that happens in the browser: a click, key press, form submit, mouse movement, page load, or input change.

`addEventListener` tells the browser which function should run when a specific event happens.

Events are what turn a static page into an interface people can use.

If this is your first time seeing this

Events are browser moments your code can react to.

The listener function waits quietly until the event happens.

Mini glossary

Event
Something that happens in the browser, such as a click or submit.
Event listener
A function registered to run when an event happens.
Handler
Another common name for the function that handles an event.

Example from everyday life

An event listener is like a doorbell. Nothing happens while everyone is quiet, but when someone presses the button, the listener reacts and runs the planned action.

How it works step by step

  1. The example creates a button and a counter paragraph.
  2. The click listener increases `count` by one each time the button is clicked.
  3. After changing the variable, the listener updates the page text.
  4. The code calls `button.click()` twice to simulate two real clicks in the lesson runner.

Where you will use this

  • A modal opens when a person clicks a settings button.
  • A calculator updates the result when a number button is clicked.
  • A lesson app marks a step complete when the learner clicks `Run code`.

Before you run the code

The function passed to `addEventListener` does not run immediately. It runs later, when the event happens.

For beginner code, keep event handlers small: read input, update state, then update the DOM.

Common beginner mistakes

  • Calling the handler immediately instead of passing a function to `addEventListener`.
  • Updating a variable but not updating the visible page.
  • Putting too much unrelated logic inside one event handler.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingRuns the click handler twice
WaitingUpdates the DOM after clicks

Code runs locally in an isolated sandboxed browser frame with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Click only once and check the output.
  • Change the counter to add 2 instead of 1.
  • Add a second event listener that logs `Saved`.