$(document).ready(function(){ $('.zubr').click(function(){ var show = $('.mobile-head'); if(show.css('display', 'none')){ show.show('1000') } else{ show.hide('1000') } }) }); 
 .mobile-head{ width: 100px; height: 100px; background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="mobile-head">z</div> <button class="zubr">Click me</button> 

The usual animation does not work, the button and the block itself, when pressed, the block should be hidden if it is shown, and show if it is hidden. But only 1 condition works. Why?

  • JavaScript works as it should. Your condition is incorrectly written ... What do you want to check? maybe you meant if ( show.css('display') == 'none' ) { } - Mikhail Rebrov

3 answers 3

Perhaps better like this:

 $('.zubr').click(function(){ var show = $('.mobile-head'); if(!show.hasClass('show')){ show.addClass('show'); show.show('1000'); } else { show.removeClass('show'); show.hide('1000') } }); 
 .mobile-head{ width: 100px; height: 100px; background-color: red; display: none; } 
 <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <div class="mobile-head">z</div> <button class="zubr">Click me</button> 

Or so:

 $('.zubr').click(function(){ var show = $('.mobile-head'); show.slideToggle(); }); 
 .mobile-head{ width: 100px; height: 100px; background-color: red; display: none; } 
 <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <div class="mobile-head">z</div> <button class="zubr">Click me</button> 

    What do you think returns show.css( , ) in

     if(show.css('display', 'none')){ 

    It returns a jQuery show object, which in the Boolean sense means true .

    http://api.jquery.com/css/

     if (show.css('display') == 'none') { show.show('1000'); } else { show.hide('1000'); } 

    or

     if (show.css('display') != 'none') { show.hide('1000'); } else { show.show('1000'); } 

      To check whether an element is visible, jQuery has a special construct.

       if (show.is(':visible')) 

      but since you only need to change the visibility status to the opposite, then for this you just need to use the toggle() method

       $(document).ready(function(){ $('.zubr').click(function(){ $('.mobile-head').toggle(1000); }) }); 
       .mobile-head{ width: 100px; height: 100px; background-color: red; } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="mobile-head">z</div> <button class="zubr">Click me</button>