Detecting when to notify users

Most of us are familiar with the concept of event handlers, and how we can use them to provide scripted responses to events that occur in the program. But there is a lot more to think about when working out how to determine when a certain set of conditions is true, from the point of view of a user's environment. This article shares some thoughts about the subject.

A series of fortunate events

Events are the standard programmatic way in which we respond to the various happenings in an application. Event handlers can be attached to objects so that when an occurrence of an event is detected, we can respond to that event with some kind of code. Some events have been around forever, and can be regarded as old classics. For example, a simple onclick handler to run a function when a button is pressed:

deleteButton.onclick = function(event) {

A simple onload handler to only run the application code once the window is properly loaded:

window.onload = function() {

And so on, with onblur, onresize, onkeypress, etc.

The new crop of Web APIs bring a whole new batch of event handlers to the table, to check for more specific cases of events occurring. For example:

In addition, many APIs have access to event handlers on callback functions that allow us to respond appropriately when a request succeeds or fails (onerror and onsuccess). This is incredibly useful, and can allow us a lot of control over our apps and changes in surrounding conditions. You can find documentation of a large number of events and APIs on MDN; see the Event reference.

Responding to other conditions in your app

Events are great, but unfortunately it is not always that simple — an event might not always exist that perfectly suits your condition. In such a case, you'll have to be a bit more inventive, possibly using a combination of events that point to the condition being met, or perhaps using a method like window.setInterval() to periodically check for a given condition to be true. In the next article — Checking when a deadline is due — we'll explore a fairly complex example illustrating a common requirement, for you to draw inspiration from.

Document Tags and Contributors

Contributors to this page: chrisdavidmills, xfq, teoli, Sheppy, kscarfone
Last updated by: chrisdavidmills,