Hiding a div by selecting anywhere outside of it

I'm trying to find a way to display a hidden div via clicking a button, and hiding it the same div if the button is clicked again, or if the user clicks anywhere outside of the div. The function is very similar to the function seen in notifications icon in Facebook.

    $('.button').click(function() {
        if($(".div").css('visibility') == 'visible') 
            $(".div").css('visibility', 'hidden');
        else
            $(".div").css('visibility', 'visible');
    });

    $(".button").click(function() {
        event.stopPropagation();
    });

    $('html:not(.div)').click(function() {
        //Hide the div if visible
        if($(".div").css('visibility') == 'visible') 
            $(".div").css('visibility', 'hidden');
    });

However, this doesn't seem to work in Firefox/IE, only in Chrome. The div fails to display at all in firefox/IE. Does anyone have an idea of a better way to go about this?

Thanks!


UPDATED: the button now show and hide div, and also clicking outside div hide it
Here the demo : http://jsfiddle.net/jL2cU/2/

$(document).ready(function(){
  $('.form-container').click(function(event){
    console.log('click - form');
    event.stopPropagation();
  });
  $('html').click(function(event){
    console.log('click - body');
    //hide the form if the body is clicked
    $('.form-container').css('display','none');
  });
  $('button').click(function(event){
    $('.form-container').toggle();
    event.stopPropagation();
  });

});

and

   <div class="button-container">
        <button>Show div</button>    
      </div>
      <div class="form-container">
          <fieldset id="" class="">
            Here is the TEXT
          </fieldset>
      </div>  

and

.button-container
{
  width:300px;
  margin:0 auto;
  text-align: center;
  padding:0px 0px 25px 0px;
}
.form-container
{
  display:none;
  width:300px;
  margin:0 auto;
  text-align: center;
  background: #777;     
}​

Use the jQuery toggle method.

With no parameters, the .toggle() method simply toggles the visibility of elements.

$(function() {
    $('.button').on('click', function() {
        $('.div').toggle();
    }
})();
链接地址: http://www.djcxy.com/p/83956.html

上一篇: 隐藏并关闭隐藏的div

下一篇: 通过选择它以外的任何地方来隐藏div