Search code examples
jqueryslidetoggle

is(':hidden') always false after slideToggle()


I am unable to detect slide up/down of the slideToggle() function of jQuery. I have used this article for reference Demo of slideToggle in StackOverflow

$('#ToogleMe').click(function(e) {
  e.preventDefault();
  $('#toogleResult').slideToggle();
  var check = $('#toogleResult').is(':hidden');
  if (check == true) {
    console.log('up');
  } else {
    console.log('down');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="button" id="ToogleMe" value="Toogle" />
<div id="toogleResult">Random Message</div>

#toogleResult is being toggled successfully however the var check is always false. Why is this?

Image of my Output

Image of my Output


Solution

  • To fix this you need to execute your code within the callback parameter of the slideToggle() method. This ensures it runs after the animation has completed and the element is in its final state. Try this:

    $('#ToogleMe').click(function(e) {
      e.preventDefault();
    
      $('#toogleResult').slideToggle(function() {
        var check = $('#toogleResult').is(':hidden');
        if (check) {
          console.log('up');
        } else {
          console.log('down');
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="button" id="ToogleMe" value="Toogle" />
    <div id="toogleResult">Random Message</div>