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

Sometimes you wanna do something such as when you click a div a part that you hide, shown and when click outside of if you wanna hide again . Following code do what exactly you want.

        $(document).mouseup(function (e) {

            var container = $("your_selector");
       
            if (!container.is(e.target) // if the target of the click isn't the container...
                && container.has(e.target).length === 0) // ... nor a descendant of the container
            {
                // do something you want (hide,show,remove, change class anything you want) Ex: container.hide()
               
            }
        });
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s