Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Programming Fundamentals · Grade 6-8

Event Handler

A function that is automatically called when a specific event occurs, such as a button click, key press, or timer tick.


Quick Answer

A function that is automatically called when a specific event occurs, such as a button click, key press, or timer tick. Use one whenever a program must wait for something it cannot predict: a player pressing the spacebar, a user tapping Buy, a timer reaching zero. You attach the handler to the event once; after that the system calls it every time the event fires, and your program never has to keep checking. Attach it by name, without parentheses, or it runs immediately instead of waiting.

Why This Matters

Every app with buttons, every game that responds to keys and every web page that reacts to a click is built from event handlers. They let a program sit idle and respond within moments to whatever the user does, in any order. Get them wrong and a button does nothing, a single click runs your code twice, or a slow handler freezes the whole screen until it finishes.

Intuitive Explanation

A doorbell is wired once. After that you go about your day, and whenever someone presses the button it rings; you never stand at the door checking. An event handler is that wiring for a program. In JavaScript, button.addEventListener('click', sayHi) tells the browser: whenever this button is clicked, call the function sayHi. That line runs once, during setup; sayHi runs later, once per click, perhaps zero times, perhaps a hundred.

This changes how you trace a program. Code outside handlers runs top to bottom when the page loads. Code inside a handler runs only when its event happens, so the order depends on the user. If a page has count = 0 and a click handler that runs count = count + 1, then after three clicks count is 3, wherever in the file the handler happens to be written.

Passing a function is not the same as calling it. button.addEventListener('click', sayHi()) has parentheses, so sayHi runs straight away during setup, and what gets attached is its return value, usually undefined; later clicks do nothing. Without the parentheses you hand over the function itself, to be called later. A loop that keeps asking 'has the key been pressed yet?' is also not an event handler; that is polling, and it burns effort that a handler avoids.

Think of it like this. A smoke alarm is an event handler for smoke: installed once, it waits silently and reacts only when smoke arrives, as many times as that happens. You never tell it when to sound; the event does. Unlike an alarm on the ceiling, a handler can be attached twice by mistake, and then one event sets it off twice.

Core idea. Event-driven programming reverses the usual flow — instead of your code deciding when to run, external events trigger it.


When to Use

Use an event handler when the program must respond to something that happens at an unknown time: a click, a key press, a swipe, a timer tick, a message arriving. Signals are phrases like when the user, whenever and on click. If code should run once, straight away, at a known point, just call the function. If it should repeat a set number of times or until a condition changes, use a loop; for an action that repeats on a clock, attach a handler to a timer.

Tip. Ask: Must code run whenever something happens at an unpredictable time, such as a click, key press or timer tick?

How to Recognize It

Ask what decides when the code runs: the program's own order of lines, or something outside it such as a user or a timer.

  1. Does the code have to wait for something the program cannot schedule, such as a tap, a key press or a message arriving?

    Yes means attach an event handler. If the program itself decides when the code runs, an ordinary Function call in sequence is enough.

  2. Is the question about the happening itself, such as which key was pressed or where the mouse was?

    Yes means you are describing the Event, the data handed to the handler. The handler is the function that responds to it.

  3. Does the code keep asking, on every pass of a loop, whether the space key is down yet?

    Yes means that is polling with a While Loop, not an event handler. A handler is registered once and then waits without any loop of yours.

  4. Is a function passed by name, without parentheses, to something like addEventListener or onClick?

    Yes means it is being registered to run later. With parentheses, the function runs straight away and only its result is attached.

Event Handler vs Event vs Function vs While Loop

An event handler is a function, it reacts to an event, and older games did the same job with a loop, so all four get muddled. Ask who decides when the code runs, and whether anything keeps checking.

Event Handler

Meaning
An event handler is a function registered once that the computer calls each time a chosen event happens.
Key test
Registered once, then runs whenever the event fires, at times nobody planned.
Example
canvas.onclick = drawDot makes a dot appear at every click, wherever and whenever it happens.

Event

Meaning
An event is the happening itself, such as a click or a key press, along with details like which key it was.
Key test
Something that occurs, not code; it carries data to the handler.
Example
Pressing the left arrow key creates a key event whose key value is 'ArrowLeft'.

Function

Meaning
A function is a named block of code that runs when a line of the program calls it.
Key test
The program's own lines decide when it runs.
Example
draw_tree() runs exactly where the main program calls it, on line 12, every time.

While Loop

Meaning
A while loop used to watch for input asks again and again whether something has happened, which is called polling.
Key test
Your own loop keeps asking; nothing is registered.
Example
while not key_down('space'): wait() checks the key many times a second until it is pressed.

Formula & Notation

Worked Examples

Example 1 — Trace a click counter

Easy

A web page runs this setup once: let count = 0; then button.addEventListener('click', addOne), where addOne runs count = count + 1 and then shows count on the screen. The user clicks the button 3 times. What is shown after each click, and how many times did the setup line run?
Show the steps and the answer
  1. Page load: count = 0, and addEventListener registers addOne. Nothing is shown yet.

    Registering stores the function for later; addOne itself has not run.

  2. Click 1: the browser calls addOne, so count = 0 + 1 = 1, and 1 is shown.

    The event, not the next line of the file, decides when the handler runs.

  3. Click 2 shows 2, and click 3 shows 3.

    The same handler runs once per click, and count keeps its value between clicks because it lives outside the handler.

  4. The setup line ran once, at load; addOne ran 3 times.

    One registration covers every future click.

Answer: The screen shows 1, then 2, then 3. The setup line ran once, and addOne ran 3 times.

Takeaway: Setup code runs once when the page loads; a handler runs once for every event, whenever it happens.

Example 2 — Same handlers, different click order

Standard

A calculator toy has value = 1 and two buttons. The Double button's handler runs value = value * 2; the Add 3 button's handler runs value = value + 3. In the file, the Double handler is written first. User A clicks Double, then Add 3. User B clicks Add 3, then Double. What value does each user end with?
Show the steps and the answer
  1. User A: Double runs first, value = 1 × 2 = 2; then Add 3 runs, value = 2 + 3 = 5.

    Handlers run in the order their events happen.

  2. User B: Add 3 runs first, value = 1 + 3 = 4; then Double runs, value = 4 × 2 = 8.

    The code is identical, but opposite clicks make the operations happen in the opposite order.

  3. Note that the order of the handlers in the file played no part in either result.

    Unlike a sequence of statements, handler code is not run top to bottom; registering only tells the system what to call later.

Answer: User A ends with 5; user B ends with 8.

Takeaway: With event handlers, the user's actions decide the order the code runs, so trace events in the order they happen, not the order they are written.

Example 3 — Find the mistake: parentheses that call too early

Application

Omar wants a message when a button is clicked. He writes button.addEventListener('click', showAlert()), where showAlert pops up the word Clicked. The message appears once as soon as the page loads, and clicking the button does nothing. Find the mistake and correct it.
Show the steps and the answer
  1. Look at showAlert(): the parentheses call the function right now, while the setup line is running.

    That call is why the message pops up at page load, before any click.

  2. What gets registered is showAlert's return value; it returns nothing, which in JavaScript is undefined.

    addEventListener is handed undefined instead of a function, so there is nothing to call when a click arrives.

  3. Fix: button.addEventListener('click', showAlert), with no parentheses.

    The bare name passes the function itself, for the browser to call later.

  4. Retrace: nothing appears at page load, and each click shows the message once.

    The function now runs only on the event, once per click.

Answer: Write button.addEventListener('click', showAlert) without parentheses. The message then appears on each click instead of at page load.

Takeaway: Pass the handler's name, not a call: with () the function runs immediately and its result, not the function, gets attached.

Where You'll See It

  • A doorbell

    You wire up the bell once; then every time someone presses the button it rings — the press is the event and ringing is the handler firing automatically.

  • Tapping a button in an app

    A developer attaches a handler to the 'Buy' button once, and the system runs that code every single time a user taps it, without the program constantly checking.

  • A game character that jumps on spacebar

    You register a key-press handler so that whenever the spacebar fires its event, the jump code runs — control flow is driven by the player, not a fixed line-by-line script.

Common Mistakes

  1. The slip: button.onClick(myHandler()) attaches my handler to the click.

    Why it's tempting: It mentions the handler and the click together, so it looks like a registration.

    Instead: The () calls the handler immediately and registers its return value. Pass the function by reference: button.onClick(myHandler) with no parentheses.

  2. The slip: Registering a handler twice just makes it 'more attached', no harm done.

    Why it's tempting: Attaching it again seems redundant but harmless, like setting the same setting twice.

    Instead: Each registration is separate, so the handler fires once per registration — if setup code runs twice and adds a new anonymous handler each time, a single click runs your code twice. (JavaScript's addEventListener does skip an exact repeat of the same named function.)

  3. The slip: It's fine for an event handler to do a long, slow task.

    Why it's tempting: It's your code reacting to a click, so it seems like it can take as long as it needs.

    Instead: Handlers usually run on the UI/main thread; a slow handler freezes the interface until it finishes. Do long work asynchronously or off the main thread.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. likes = 0, and the handler onLike adds 1 to likes. It is registered once with button.onClick(onLike). The user clicks 4 times. What is likes?

    Hint: The handler runs once for each click.

  2. In this system, each call to button.onClick(onLike) adds another copy of the handler. Setup accidentally calls it twice. likes starts at 0 and the user clicks 3 times. What is likes?

    Hint: How many copies of the handler run on each click?

  3. Setup code: print('A'); button.onClick(sayHi); print('B'). sayHi prints 'Hi'. The user clicks once after setup finishes. What is printed, in order?

    Hint: Does registering a handler run it?

  4. A timer handler runs every 2 seconds and adds 5 to score, which starts at 0. The first tick is at 2 seconds. What is score after 9 seconds?

    Hint: List the tick times up to 9 seconds.

  5. greet() is called directly on line 3 of a program. Later, greet is also passed to window.onLoad(greet). Which use makes greet an event handler?

    Hint: Who decides when greet runs in each case?

  6. A student writes button.onClick(showMenu()). The menu appears as soon as the page loads, and clicking does nothing. What is wrong?

    Hint: What do the brackets after showMenu do?

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

How does a handler know which button was clicked or which key was pressed?

The system passes it an event object as a parameter. In JavaScript, a handler written as function onKey(e) receives e, and e.key tells you the key, such as 'a' or 'Enter'; for a click, e.target is the element that was clicked. One handler can then serve many buttons by reading e.target, instead of you writing a separate function for each button.

Can a handler be removed once it is attached?

Yes. In JavaScript, removeEventListener('click', addPoint) detaches it, so later clicks do nothing. This only works with a named function: an anonymous function written inline cannot be referred to again, so it cannot be removed this way. Games use removal for things like disabling a fire button while a weapon reloads, and web pages use it to stop listening once a one-time task is done.

What happens if two events arrive at the same moment?

In a browser they are placed in a queue, and the handlers run one after another, never at the same time. Each handler finishes completely before the next one starts. That is why a click handler can safely update a score without a second click interrupting it halfway, and also why one slow handler delays every event waiting behind it.

Is Scratch's 'when green flag clicked' block an event handler?

Yes. The hat-shaped blocks in Scratch, such as 'when this sprite clicked' or 'when space key pressed', each attach the script below them to an event. Scratch runs the script every time the event happens, and if several scripts listen for the same event, they all start. It is the same idea as addEventListener in JavaScript, without the typing.

Learning Path

Event Handler

You are here

Next →

Nothing after this yet
You need Event (an occurrence such as a click or key press that a program can detect) and Function (Programming) (a named block of code you can call) first. An event handler links them: you register a function once, and the system calls it each time the event fires. With it you can build interactive programs: buttons, games controlled by keys, forms that check input as you type, and timers that update a clock.

See Also