👂 Event Handler
5th Grade 💻 Coding
An event handler is a piece of code, usually a function, that runs automatically when a certain event happens, like when someone clicks a button.
In Scratch, every stack of blocks that starts with an event block is an event handler: whatever is attached under “when this sprite clicked” runs every time the sprite is clicked. One event can have several handlers. For example, two sprites can both respond to the green flag, each in its own way.
On a web page you can write <button onclick="sayHi()">, and then the function sayHi is the handler for the click event. The programmer doesn’t call that function directly. Instead, they “register” it, and the browser calls it the moment the event happens. It’s like leaving your neighbor a note: “If someone rings the bell, please open the door.”
For example
- A “like” button on a website: the click handler adds 1 to the counter and changes the button’s color.
- In Scratch, “when space key pressed → jump”: the whole stack is an event handler.
- In a piano game in the browser, every key has its own event handler that plays its note.
📌 Remember: An event handler = “When this happens, do that.”
Quick quiz
What is an event handler?
Who calls the event handler for a button on a website?
Can one event have several handlers?