Here you should pay attention to the color of the paragraph, it works like this: when the block is hidden - the paragraph is red, when the block appears - the paragraph is black. The paragraph changes color only after the slideToggle() function completes. But such a problem: when the block is opened, and at the same time, click on the paragraph 2 times, the block remains open, and the paragraph has red color, not black. Long solved the problem is an extreme case.

 $('p').click(function() { if ($('.q1').is(':hidden')) { $('.q1').stop().slideToggle(function() { $('p').css({ background: 'black' }); }); } else { $('.q1').stop().slideToggle(function() { $('p').css({ background: 'red' }); }); } }); 
 .q1 { height: 300px; width: 100px; background: black; display: none; } p { float: right; background: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>123312 <div class="q1"></div> 

    1 answer 1

    Obviously, the error is that you use 2 different conditions that determine whether the object is hidden or not.

    is(':hidden') determines if the object is completely hidden

    slideDown() determines whether the object is hidden or has already begun to hide.

    But instead of trying to predict how slideDown() will behave, is it not easier to make a check after the animation, in order to determine the state already defacto?

    Work code:

     $('p').click(function() { $('.q1').stop(true).slideToggle(function() { if ($('.q1').is(':hidden')) { $('p').css({ background: 'red' }); } else { $('p').css({ background: 'black' }); } }); }); 
     .q1 { height: 300px; width: 100px; background: black; display: none; } p { float: right; background: red; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>123312 <div class="q1"></div> 

    • Oh, that's it, thank you very much! Now it is clear that the visibility of the object is determined after the completion of the animation. - PeGaS