Our Blog

Ongoing observations by End Point people

Handling outside events with jQuery and Backbone.js

By Greg Davidson · March 2, 2012

Tags: javascript, jquery

I recently worked on a user interface involving a persistent shopping cart on an ecommerce site. The client asked to have the persistent cart close whenever a user clicked outside or "off" of the cart while it was visible. The cart was built with Backbone.js, and jQuery so the solution would need to play nicely with those tools.

The first order of business was to develop a way to identify the "outside" click events. I discussed the scenario with a colleague and YUI specialist and he suggested the YUI Outside Events module. Since the cart was built with jQuery and I enjoyed using that library, I looked for a comparable jQuery plugin and found Ben Alman's Outside Events plugin. Both projects seemed suitable and a review of their source code revealed a similar approach. They listened to events on the document or the element and examined the event.target property of the element that was clicked. Checking to see if the element was a descendant of the containing node revealed whether the click was "inside" or "outside".

With this in mind, I configured the plugin to listen to clicks outside of the persistent cart like so:

    $('#modal-cart').bind('clickoutside', function(event) {

The plugin worked just like it said on the tin, however further testing revealed a challenge. The site included ads and several of them were