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
easyAnswer
First step
Full solution
- 2 Step 2: The event is 'button clicked'. The handler is the code that outputs the message.
- 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.
Example 2
mediumExample 3
mediumExample 4
mediumExample 5
mediumExample 6
hardExample 7
hardExample 8
hardExample 9
hardExample 10
challengePractice Problems
Try these problems on your own first, then open the solution to compare your method.
Example 1
mediumExample 2
hardExample 3
easyExample 4
easyExample 5
easyExample 6
easyExample 7
easyExample 8
easyExample 9
easyExample 10
easyExample 11
mediumExample 12
mediumExample 13
mediumExample 14
mediumExample 15
mediumExample 16
mediumExample 17
mediumExample 18
mediumExample 19
mediumExample 20
challengeExample 21
challengeExample 22
challengeExample 23
easyExample 24
easyExample 25
easyExample 26
mediumExample 27
mediumExample 28
mediumExample 29
mediumExample 30
mediumExample 31
hardExample 32
hardExample 33
hardExample 34
hardRelated Concepts
Background Knowledge
These ideas may be useful before you work through the harder examples.