Close Hide DIV when Clicking outside in jQuery

Last Reply 5 months ago By chetan

Posted 5 months ago

I am working on alpha.dubaiexporters.com.

http://alpha.dubaiexporters.com/aboutus.aspx


There is go button and after clicking on go button,search panel appears where i can perform search keyword and category.

The issue is that after clicking on go button,search panel appears but if the user does not want to perform any search,he clicks outside anywhere but that search panel
does not go.

How to achieve that?

Posted 5 months ago

Hi chetan,

Check the below sample code.

HTML

<div id="div1" style="display: none;">
    <input id="txtKeyword" name="keyword" type="text" />
    <input id="txtCategory" name="search" type="text" />
</div>
<input id="btnGo" type="button" name="button" value="Go" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=btnGo]").click(function (e) {
            $("[id*=div1]").attr('style', 'display:block');
        });

        $(document).click(function (e) {
            if (!$(e.target).is('[id*=btnGo]')) {
                $("[id*=div1]").attr('style', 'display:none');
            }
        });
    });
</script>

Demo


Posted 5 months ago

Hi sir...This Worked for me:

 

        $(document).click(function (e) {
            if (e.target != $(".sb-icon-search")[0] && (e.target.parentElement.parentElement != $(".header-form-container")[0])) {
                $(".header-search-body")[0].style.display = 'none';
            }
        });

        $(".header_search").click(function (e) {
            $(".header-search-body")[0].style.display = 'block';
        });