Use jQuery to hide a DIV when the user clicks outside of it

This code snippet demonstrates how to track if a click is being made outside of an element. In this specific example we'll be fading out a div if a click action is registered outside of it.  

HTML

To start with we'll set up a demo div which will be our subject, and a containing div. Any clicks that are made outside of the demo div but inside the demo container will be registered as an 'outside' click. Later in this post we'll look at how you can register a click anywhere on the page outside of the subject div.

<div id="demoContainer">
    <div id="demo"></div>
</div>

CSS

The CSS is purely for demonstration purposes.

#demo
{
    border:2px solid #666;
    background-color:#eee;
    width:50%;
    height:100px;
    margin:auto; 
    margin-top:40px;
}

#demoContainer
{
    border:2px solid #666;
    width:100%;
    height:200px;
    position:relative;
}

JQUERY

The jquery registers a mouseup event on the container, and then checks if the id of the target that has been clicked is not the subject div itself. The subject div will be faded out if it is not the target.

$(document).ready(function()
{
    $("#demoContainer").mouseup(function(e)
    {
        var subject = $("#demo");

        if(e.target.id != subject.attr('id'))
        {
            subject.fadeOut();
        }
    });
});

Checking for children elements

If your subject element (in this case the demo div), is going to have elements inside of it, then you'll need to check if those element children belong to your subject, otherwise it will be considered an 'outside' click'. To account for this, make this modification to the jquery so that it uses the 'has' method:

$(document).ready(function()
{
    $("#demoContainer").mouseup(function(e)
    {
        var subject = $("#demo"); 

        if(e.target.id != subject.attr('id') && !subject.has(e.target).length)
        {
            subject.fadeOut();
        }
    });
});

You can see this in effect in the demo shown below.

Register a click anywhere outside of the subject div

To make this usable for the whole page, simply replace '#demoContainer' with 'document' for the mouseup event.

Demo 

Sign Up

NEXT: jQuery ubinding a click event after first click

This article looks at using jQuery unbind to remove a click event after the first click. As an example we'll be creating a simple search box the gets displayed on first click and would do the search on second click.

comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.