Showing posts with label Hide div on clicking anywhere on page. Show all posts
Showing posts with label Hide div on clicking anywhere on page. Show all posts

Sunday 20 May 2012

Hide div when clicking outside the div Or anywhere on the page

Android blog with example
Hello Friends,
Yesterday while creating a web application in Java ,Jsp and Jquery I trapped
in a really weird situation. I make a div which show and hide on clicking
the down arrow icon as shown in the image.


My code is this:
1. JSP CODE:
     <div class="header">
            <div id="logo">
                <div id="emailAddress">
                    <a id="home" href="home.html">
                         mukesh@gmail.com
                    </a>
                    <div id="showSettingBox" class="dwnArrow ">&nbsp;
                    </div>
                    <div class="settingBox">
                        <a href="editProfile.html">Profile</a>
                        <a href="#.">Setting</a>
                        <a href="main.html">Logout</a>
                    </div>
                </div>
            </div>
        </div>
2. Java Script | JQuery Code:
     $("#showSettingBox").click(function(){
                    if($("#showSettingBox").hasClass("showBox"))
                    {
                        $("#showSettingBox").removeClass("showBox");
                        $(".settingBox").hide();
                    }
                    else
                    {
                        $("#showSettingBox").addClass("showBox");
                        $(".settingBox").show();
                    }
                }); 
    
But the div doesn't hide when we are clicking outside it or anywhere on the Page.
As shown in the below image.



Solution:
 If anyone else has this problem, here's a quick solution.  

  $("#showSettingBox").click(function(){
                    if($("#showSettingBox").hasClass("showBox"))
                    {
                        $("#showSettingBox").removeClass("showBox");
                        $(".settingBox").hide();
                    }
                    else
                    {
                        $("#showSettingBox").addClass("showBox");
                        $(".settingBox").show();
                    }
                }); 
                $('html').click(function() {
                //Hide the menus if visible
                $("#showSettingBox").removeClass("showBox");
                              $(".settingBox").hide();
                });

                $('#showSettingBox').click(function(event){
                    event.stopPropagation();
                })

I added the above selected(5-6 line) code in my java script code and its 
working for me. :)
Just Use event.stopPropagation(); with the Id of div.

Hope this will helps you !!!
Happy Coding.... :)
Enjoy :)


 

Copyright @ 2013 Android Developers Blog.