Practice Event Handler in CS Thinking
Use these practice problems to test your method after reviewing the concept explanation and worked examples.
Quick 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.
Example 1
easyIn 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.
Example 2
mediumWrite 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
mediumA 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 4
hardExplain 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?