17

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?

2
  • @Vipin Soni: The timings are different for show and hide Commented Jan 3, 2015 at 12:21
  • Just put your title in google: how to check if one element is hide with jquery THX! Commented Jan 3, 2015 at 12:22

1 Answer 1

4

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);
        }
  });
Sign up to request clarification or add additional context in comments.

3 Comments

Regarding the second one using toggle(), you should stop() animation to handle mutliple click on #Div1
tanks.How hide div with clicking on page?
@mohsen: Added an example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.