Ben's Sandbox
  • Projects
  • Tags

Detecting and Binding to Click Events Outside an Element


View Blog   View Source  
Both of these examples are functionally equivalent. However, the difference is how the click outside of the element is detected. In the first case, I bind to the document click event and listen for all clicks to bubble up to the document. I can then check if it occurred in the any elements of interest. In the second case, I'm using Ben Alman's jQuery outside events plugin to bind to the "clickoutside" event directly on the element that I am interested about knowing if a click occurred outside its boundaries. The benefit of using the custom event is that I can bind to the elements I want to detect the event on and I don't have to do the iteration to find elements that are interested in knowing about the event.


Bind to document -> click

Click Me
I do nothing
Click Me
Click Me
I do nothing

Bind to .boxes -> clickoutside

I do nothing
Click Me
Click Me
I do nothing
Click Me

© Ben Olson 2012 with help from Jekyll Bootstrap and Twitter Bootstrap