jQuery Niceties - Dismissing Lightboxes

Blake Walters, Former Viget

Article Category: #Design & Content

Posted on

Lightboxes have been the all the rage for years now; especially since frameworks like jQuery make them fairly easy to accomplish. One little piece that I always find lacking, though, is even the tiniest bit of keyboard support. Want to help your power users out a bit? Bind the escape key to dismissing lightboxes.

The most straightforward way is simply to bind the escape key to trigger a click on the lightbox close button once the lightbox is open.

$(document).bind('keyup', function(e) {   if(e.keyCode == 27) {     $('.lightbox a.close').click();   } }); 

 

 

If you don’t want it permanently bound, you can always bind the event when the lightbox opens and unbind the event when the lightbox closes. Unfortunately this is a little brittle as it depends on the functionality of closing the lightbox to be bound to the close button (or for the close button to in turn trigger the closing of the lightbox). We can use custom event binding to make it all a little more elegant.

First, bind a custom event to the lightbox that can be triggered when it needs to be dismissed:

$('.lightbox').bind('dismiss', function() {   // code to dismiss lightbox }); 

And then just trigger that event when escape it pressed:

$(document).bind('keyup', function(e) {   if(e.keyCode == 27) {     $('.lightbox').trigger('dismiss');   } }); 

The nice thing here is that the dismiss code can now be executed by any event that needs it (saving a form in the lightbox, clicking the close button, pressing escape, etc.) without code being duplicated.

Some further reading that might be of interest:

 

Related Articles