Skip to content

Events

If you have ever built a prototype in Figma, you already understand the core idea behind JavaScript events. When you set up a prototype interaction — “when the user taps this hotspot, go to frame X” — you are describing a trigger and a response. JavaScript works exactly the same way: you listen for something to happen, and when it does, you run some code.

An event is a moment something happens in the browser. The user clicks a button — that is an event. They press a key — that is an event. They hover over an image — also an event.

The browser is constantly watching for these moments. Your job as a developer is to tell it: “when this event happens on that element, run this code.”

The method that wires everything together is addEventListener. It takes two things:

  1. The name of the event you want to listen for (e.g. 'click')
  2. A function to run when that event fires — called a handler or callback
var btn = document.querySelector('#myButton');
btn.addEventListener('click', function() {
// this code runs every time the button is clicked
});

Think of addEventListener like the prototype panel in Figma. You select the element, choose the trigger (“On click”), and specify what happens next. Here, the trigger is 'click' and the “what happens next” is the function you pass in.

The function inside addEventListener is called a callback because the browser calls it back for you at the right moment — you do not call it yourself.

Here is a complete example. A button keeps track of how many times it has been clicked and updates the page to show the running total.

Walk through what is happening:

  • var count = 0 — a variable that starts at zero and grows with each click.
  • document.querySelector('#countBtn') — grabs the button from the page.
  • document.querySelector('#counter') — grabs the paragraph that shows the total.
  • addEventListener('click', function() { ... }) — every time the button is clicked, the function inside runs.
  • Inside the function, count increases by one, then counter.textContent is updated to reflect the new total using string concatenation (+).

Notice that textContent uses the + operator to join the number with the surrounding text. This is intentional: it keeps the code readable and avoids any special syntax inside the string.

FigmaJavaScript
Select a hotspotdocument.querySelector('#myElement')
Choose trigger: On ClickaddEventListener('click', ...)
Choose action: navigate / change variantThe function body — your custom code

In Figma, every prototype interaction is: trigger → action. In JavaScript, every event listener is: event → callback. The mental model is identical; only the syntax is new.

What is a browser "event"?
Which method attaches a function to run when an element is clicked?
In Figma terms, what is most like an event listener?