How to check if one element is hidden with jquery

I want to show and hide one div as shown 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 by clicking on the empty sapce page, how can I do this, and where is my code incorrect?

+4
source share
1 answer

hiddennot a property of a jQuery object. Tryis(':hidden')

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

  });

If the timings were the same, you can simply use toggle()one that does hideor showbased on current visibility.

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

And like @A. Wolf suggests, to allow several clicks, use stopto stop any existing animation:

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

Part 2:

div, , document:

.

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

, div1 , , stopPropagation() :

  $('#Div1').click(function (e) {
        e.stopPropagation();       // stop click propagating to document click handler
        if ($("#Div2").is(':hidden')) {
            $("#Div2").show(500);
        }
        else {
            $("#Div2").hide(1000);
        }
  });
+2

Source: https://habr.com/ru/post/1569811/


All Articles