...

/

Introduction to Event-Based Programming

Introduction to Event-Based Programming

Learn about event-based programming and click events.

Last chapter we were introduced to the DOMDocument Object Model and how it allows us to interact with the elements of a web page. Now, we’ll be looking at how events provide the link between user interactions and our program. That’s right—this section is where our code starts to become fully interactive and the fun really begins.

Event-based programming

Imagine boiling some water in a pan. The only way to tell if the water has boiled is to keep checking at regular intervals. This is annoying, because we have to keep stopping what we’re doing to check, and there’s also the chance that we might miss the point when the water boils and it will boil over, making a mess.

The better approach is to use a kettle that whistles when the water boils. This means we can go off and do something else, safe in the knowledge that we’ll be alerted as soon as the water has boiled.

Press + to interact
Different approach for making a tea
Different approach for making a tea

Event-based programming is a style of coding that reacts to events in a similar way to how we react to the whistle on the kettle. The events in a program are usually user actions, such as pressing a key, moving the mouse or tapping the screen, but they can also be other things, such as a timer, a notification, or a change in the state of the application.

Event listeners

An event listener is triggered when an event happens. Event listeners work in a similar way to the whistle on the kettle. Instead of the program having to constantly check to see if an event has occurred, the event listener sits in the background until the event happens and then lets the program know so ...