This post is over 6 months old. Some details, especially technical, may have changed.

Outside Events jQuery Plugin

Outside Event Plugin doesn't have a great deal of uses but it does solve one very important issue in client side code - Diminishing Responsibility.  Before I explain how it does this I need to explain what it does.

Outside events are a new set of events provided by the plugin taht are fired on the registered element when the event happens OUTSIDE that element.  Imagine a click event

$("#somelement").bind("click", function(){
    // this element was clicked

Everytime that #somelement gets clicked the event fires.  An outside event is the opposite of that so,

$("#somelement").bind("outsideclick", function(){
    // some other element was clicked

This event fires when any other element is clicked that WASN'T #somelement (or whatever query you use - we are not stuck to a single element).  Outside events that are supported include (some more useful than others),

clickoutside, dblclickoutside, focusoutside, bluroutside, mousemoveoutside, mousedownoutside, mouseupoutside, mouseoveroutside,mouseoutoutside, keydownoutside, keypressoutside, keyupoutside, changeoutside, selectoutside, submitoutside.

Great, cool but what use is this?  I've already said it helps solve the Diminished Responsibility issue but what does that mean?

Diminished Responsibility

Imagine an example where there a popup notification on a web page.  It's not obtrusive but should go away when the user clicks off it.  How do you do this?  The simple answer would be to add a load of (or delegate) click events and hide the element so your handlers would start to look like this [very contrived BTW],

$("#somelement").bind("click", function(){
    // perform function

Starts to get a bit messy if we have a lot of handlers and is actually bad practise as the popup notification should be as self contained/self managing as possible.  Outside events solve this by allowing you to push responsibility back onto the widget/element that needs to "do something".  Neat.

The Magic

Funny thing is while this looks like it may be complicated to implement it's really not.  Thanks to the power of event delegation and event bubbling all the plugin does is attach the inverse of the outside event (outsideclick becomes click) to the document element and when a click event is fired the handler checks if the clicked element is an element registered with outsideclick and if not fires the event. 

Easy peasy though it does open up the possibility of infinite event triggers but that's not the fault of the plugin :-P. 

Published in JavaScript on October 11, 2010