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.

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.

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.

Solution

  1. 1
    Step 1: An event handler is a function that runs automatically when a specific event occurs.
  2. 2
    Step 2: The event is 'button clicked'. The handler is the code that outputs the message.
  3. 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.

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.
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?

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?

Background Knowledge

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

eventfunction programming