Events 101

JavaScript on the web revolves around events. When the user interacts with the page or something about the page changes, the browser will "fire" an event on the element that was interacted with or changed. JavaScript allows registering listeners for events on an element, which are functions that are run on these events whenever they fire. Partly out of necessity and partly for backwards-compatibility with multiple browsers, the event model is quite complex.

When an event is fired on an element, it propagates down from the top level of the document until it reaches that element, in what is called the capturing phase. Some events will then also bubble up from the element until they reach the top level of the document again. Listeners can be registered so that they handle events either during the capture phase or the bubbling phase. This allows a listener registered on an element to handle events fired on its children, so for example a listener registered on the document can handle any event. Sometimes—such as when designing re-usable components—it is desirable to override such global listeners, or alternatively, to have global listeners override listeners on elements lower in the DOM. Listeners can do this by calling event.stopPropagation(), which stops the event from propagating past the element the listener is registered on. If the listener is registered using useCapture, this stops the event during the capturing phase so that it will never reach the child elements and never bubble. For example, a listener registered on the document using useCapture can prevent events from being handled by any other element. If the listener is registered on the bubbling phase (the default), the event will go through its capture phase normally but will stop bubbling up, and so can prevent the event from being handled by a listener on the document that is registered on the bubbling phase.

Mouse Events

Mouse events in particular are surprisingly complex and easy to handle incorrectly. There are many different events that can be fired as a result of mouse interactions, including:

For more information, I recommend consulting the Mozilla Development Network.

Interactive Demo

Click around inside the three containers to see the types and orders of events fired. The events will be added to a queue to the right as they are received by listeners on each element, and played back in order.

Event types:

Listener options:

Animation speed:

#outer
#middle
#inner