9

I want to show and hide one div as below:

$('#Div1').click(function () {
            if ($("#Div2").hidden) {
                $("#Div2").show(500);
            }
            else {
                $("#Div2").hide(1000);
            }

        });

this code does not work.

and i want to hide div2 with clicking on empty sapce of page how can i do that and where is my code is wrong?

Gone Coding
  • 88,305
  • 23
  • 172
  • 188
mohsen
  • 1,390
  • 1
  • 13
  • 37

1 Answers1

3

hidden is not a property of a jQuery object. Try is(':hidden')

  $('#Div1').click(function () {
        if ($("#Div2").is(':hidden')) {
            $("#Div2").show(500);
        }
        else {
            $("#Div2").hide(1000);
        }

  });

If the timings were the same you could simply use toggle() which does hide or show based on the current visibility.

  $('#Div1').click(function () {
       $("#Div2").stop().toggle(500);
  });

And as @A. Wolff suggests, to allow for multiple clicks, use stop as well to halt any existing animation in progress:

  $('#Div1').click(function () {
        if ($("#Div2").stop().is(':hidden')) {
            $("#Div2").show(500);
        }
        else {
            $("#Div2").hide(1000);
        }
  }); 

Part 2:

To hide the div when you click anywhere else on the page, listen for click on document:

e.g.

 $(document).click(function(){
     $("#Div2").stop().hide(1000);
 });

for this to work properly though, you cannot allow the click on div1 to propagate to document so change the first part to also use stopPropagation() on the first event argument:

  $('#Div1').click(function (e) {
        e.stopPropagation();       // stop click propagating to document click handler
        if ($("#Div2").is(':hidden')) {
            $("#Div2").show(500);
        }
        else {
            $("#Div2").hide(1000);
        }
  });
Gone Coding
  • 88,305
  • 23
  • 172
  • 188