Technical Blog


Events and Event Handling in Javascript

Javascript, as isolating as it can be at times with its unexpected design choices, is beautiful because it can make web applications more receptive to user interaction. Javascript can detect user actions, such as mouse clicks or keystrokes, and respond in predetermined ways. We call these actions events and the code responsible for detecting them event handlers. Upon detecting an event, an event handler will execute some predetermined code that a developer has written to most likely make the software more engaging and pleasing.

An important thing that a developer must consider is the order of events. Suppose a user clicks on an element on a page and two different event handlers have been watching for this event. Perhaps we have some nested rectangles on a webpage that we've attached some event handlers to.

nested rectangles

If we click the inner rectangle, that click event is registered and we see some code execute, as instructed by our event handler. If we click the outer rectangle, not only is the outer rectangle click event registered, but the event attached to the inner rectangle is also registered. This means that two sets of code execute at the time of the click. Which one will execute first?

This question is about event order. There are a few models that describe this order once an event is registered and the way it can be described is in terms of event propagation direction, or in other words if subsequent events will be registered from innermost to outermost element or from outermost to inner. When event capturing is used, our outer rectangle event will be registered first, followed by our nested rectangle. When event bubbling is used, the propagation moves in the opposite direction.

Certain browsers default to certain models, but we may have different reasons for using one or the other. Event delegation is the method of using event bubbling to attach event handlers to outer elements of the target element. This comes in handy when the event we would like to attach an event handler to does not yet exist. We will dive into this scenario in a later post.

Until then, may your events be handled, ordered, propagated and delegated with joy!