JQuery- hide a DIV when the user clicks outside of it

Topic:

Hide a DIV when the user clicks outside of it, anywhere on body.

Solution:

HTML

1
2
<label id="label-search">Search</label>
<input id="search" style="display: none;" name="q" value="" type="search">

Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
jQuery(document).ready(function() {
    jQuery("#label-search").click(function(e) {
        jQuery("#search").show();
        jQuery("#label-search").hide();
        e.stopPropagation();
    });
 
    jQuery(document).click(function(e) {
        if (!jQuery(e.target).is('#label-search, #search')) {
            jQuery("#search").hide();
            jQuery("#label-search").show();
        }
    });
});

Note: Make sure, jQuery library has been included for the page.

Enjoy the day :) :)

No comments:

Post a Comment