Hide a div when you click outside of it using jQuery

Posted in Uncategorized on December 8th, 2009

I found this sweet little jQuery tip while working on a project the other day.

My Scenario

I was building out a jQuery calendar that would let users add information to the calendar via a popup div that displays when any day is clicked. Sticking with standard calendar UI, I wanted there to be three ways to dismiss the popup:

  1. clicking “close” on the popup itself
  2. clicking on another day, which would hide the current popup and display a new one on the day clicked
  3. clicking anywhere off of the calendar

The first two were simple enough, but I wasn’t sure what the best way to handle the third was. The jQuery tip suggested something along the lines of this:

var mouse_is_inside = false;

$(document).ready(function()
{
    $('#calendar').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $(body).mouseup(function(){ 
        if(!mouse_is_inside) $('.event-popup').hide();
    });
});

Nothing too complicated here. The first portion sets up a variable that will let us store a true/false value and then sets that variable to true when the mouse is hovering on top of the calendar. For our purposes this is the equivalent to saying that the cursor is “inside” the calendar; which is what we want to know. If the mouse is not “inside” the calendar, we set the variable to false.

$(body).mouseup(function(){ 
        if(!mouse_is_inside) $('.event-popup').hide();
    });

This next bit of code fires on the mouseup event (this can fire on any event obviously). Now we have a conditional that checks if our mouse_is_inside variable is true and if so, it hides the popup event. Nothing crazy, but a simple solution if you ever need this functionality.