Event Handler Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Event Handler.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

A function that is automatically called when a specific event occurs, such as a button click, key press, or timer tick. The handler is registered (attached) to an event source once, and then the system invokes it every time that event fires.

An event handler is like setting a trap β€” you define what should happen, then wait. When the event fires, your code runs automatically.

Read the full concept explanation β†’

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

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

Common stuck point: An event handler is registered (set up) once but can fire many times. Setting it up doesn't run it immediately.

Sense of Study hint: When creating an event handler, write the function that should run when the event occurs, then register it with the event source (e.g., button.onClick(myHandler)). The handler function does not run at registration timeβ€”it waits until the event actually fires.

Worked Examples

Example 1

easy
In a web page, a button has this event handler: WHEN button.clicked: OUTPUT 'Button was clicked!'. Explain what an event handler is and when this code runs.

Answer

An event handler is a function triggered by an event. This code runs only when the button is clicked, not when the program starts.

First step

1
Step 1: An event handler is a function that runs automatically when a specific event occurs.

Full solution

  1. 2
    Step 2: The event is 'button clicked'. The handler is the code that outputs the message.
  2. 3
    Step 3: This code does NOT run when the program starts. It only runs when the user clicks the button. The program must be running and listening for events.
Event handlers connect events (user actions, system signals) to code that responds. This is the foundation of interactive programming β€” programs respond to what the user does.

Example 2

medium
Write pseudocode for a simple calculator with buttons for digits 0-9 and an '=' button. How would you use event handlers to build this?

Example 3

medium
You register two click handlers on the same button: handler A logs 'A' and handler B logs 'B'. What does one click print?

Example 4

medium
You attach a handler that prints `event.target.value` to an input. The user types `cat`. How many times does the handler fire and what does it print on the third fire?

Example 5

medium
In a counter app, you write `let n = 0; button.onclick = () => { n++; render(n); }`. Trace `n` after 33 clicks.

Example 6

hard
Same loop but with `var i` (function-scoped). Clicking any button after the loop finishes logs what?

Example 7

hard
Why is it bad practice to call `addEventListener` inside a render function that runs frequently?

Example 8

hard
A debug log shows the same click handler firing twice per click. What two registration mistakes most commonly cause this?

Example 9

hard
A button increments a counter on click. After deploying, you discover that double-clicks sometimes only increment by 11 instead of 22. List two plausible causes.

Example 10

challenge
Design a click handler that ignores repeated clicks within 500500 ms (anti-spam). Sketch the pseudocode.

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
A form has a text input and a submit button. Write pseudocode for event handlers that: (1) validate the input is not empty when submit is clicked, and (2) clear any error message when the user starts typing.

Example 2

hard
Explain the problem of attaching an event handler inside a loop: FOR i = 0 TO 4: WHEN buttons[i].clicked: OUTPUT i. If you click button 3 after the loop finishes, what might be output and why?

Example 3

easy
Which registers a handler correctly: `button.onClick(handler)` or `button.onClick(handler())`?

Example 4

easy
When does an event handler's code run?

Example 5

easy
A button has one click handler that prints 'hi'. The user clicks 3 times. How many times does 'hi' print?

Example 6

easy
If the SAME handler is registered twice on one button, how many times does it run per single click?

Example 7

easy
Trace: `count=0; def onClick(): global count; count+=1`. After 4 clicks (handler registered once), what is count?

Example 8

easy
True or false: registering a handler runs the handler's body immediately.

Example 9

easy
Which is an event source/trigger: a button click, or a return statement?

Example 10

easy
A timer fires its handler every 1 second. After 5 seconds, how many times has the handler run (first fire at t=1s)?

Example 11

medium
Trace: `log=[]; def onKey(k): log.append(k)`. Keys 'a','b','a' are pressed (handler registered once). Final log?

Example 12

medium
A handler is registered, then UNregistered (removed), then the event fires twice. How many times does it run?

Example 13

medium
Two handlers A then B are registered for the same click (order preserved). A prints 1, B prints 2. One click output?

Example 14

medium
Trace: `total=0; def onScroll(amt): global total; total+=amt`. Scroll events deliver 10, then 5, then -3. Final total?

Example 15

medium
Why does `btn.onClick(greet())` where `def greet(): return 'hi'` fail to react to clicks?

Example 16

medium
A handler runs a 5-second blocking computation. While it runs, the user clicks a different button. What happens to the second click on a single-threaded UI?

Example 17

medium
Trace: `clicks=0; def h(): global clicks; clicks+=1; print(clicks)`. Registered ONCE but accidentally registered AGAIN. One click prints what?

Example 18

medium
An event handler for 'submit' is registered. The form is submitted. Inside the handler, what is the correct way to keep the form from also doing its default reload?

Example 19

medium
A button has handlers A and B; A is removed before any click. A would print 1, B prints 2. One click output?

Example 20

challenge
A button registers handler H inside a function `setup()` that is called every time the page re-renders. The page re-renders 3 times, then the user clicks once. How many times does H run on that click, and what is the bug?

Example 21

challenge
Two handlers are bound to a click: A increments a shared counter then B reads and prints it. Counter starts at 0. After two clicks, what does B print on the second click (A runs before B each time)?

Example 22

challenge
A debounce wraps a handler so it only fires after 300ms of no new events. The user triggers events at t=0,100,200ms (then stops). At what time does the handler actually run, and how many times?

Example 23

easy
A button has one click handler. The user clicks it 44 times. How many times does the handler run?

Example 24

easy
Which form registers a handler correctly: `button.onClick(handler)` or `button.onClick(handler())`?

Example 25

easy
True or false: a handler can change variables in the surrounding scope (closures).

Example 26

medium
Trace: `count = 0; def onClick(): count += 1`. After registering once and clicking 77 times, what is `count`?

Example 27

medium
What does it mean to 'unregister' or 'remove' an event handler?

Example 28

medium
A button has a click handler `function() { x = x + 1 }`. After 00 clicks, what was the handler's effect?

Example 29

medium
Two buttons share the same handler function. The handler prints a fixed string 'hi.' How does the handler tell which button was clicked?

Example 30

medium
What happens if an event handler throws an unhandled exception?

Example 31

hard
A handler is registered inside a loop: `for (let i = 0; i < 3; i++) { buttons[i].onclick = () => log(i); }`. Clicking button 11 logs what?

Example 32

hard
A handler runs for 500500 ms blocking the UI thread. During that time, the user clicks 44 more times. How many handler invocations remain queued at the moment the first one finishes?

Example 33

hard
How do you guarantee a handler runs only once, then auto-removes itself?

Example 34

hard
In a single-threaded event loop, can two handlers ever execute simultaneously?

Background Knowledge

These ideas may be useful before you work through the harder examples.

eventfunction programming