Search code examples
jqueryjquery-effects

When would toggle be better than slideToggle in jQuery?


I've been racking my mind and searching the internet furiously on this simple question: When would I ever want to use toggle instead of slideToggle? For everything I've done with jQuery effects (mostly toggling tables and table rows), slideToggle provides the superior visual effect IMO. So I am interested in finding a use case when toggle might be superior.

Anybody have any experience in preferring toggle over slideToggle for better visual effect?


Solution

  • There is a subtle difference between .toggle and .slideToggle

    .toggle()

    Display or hide the matched elements.

    .slideToggle()

    Display or hide the matched elements with a sliding motion.

    In the following example, there is no parameter provided, so .toggle instantly hides the element, whereas .slideToggle slides it up

    $("#toggle").toggle();
    $("#slide").slideToggle();
    #toggle {
      width: 100px;
      height: 100px;
      background-color: red;
    }
    
    #slide {
      width: 100px;
      height: 100px;
      background-color: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="toggle">
    
    </div>
    <div id="slide">
    
    </div>

    Whereas in this example, I've specified the toggles to take 1000ms, and you can see the difference in their animations

    $("#toggle").toggle(1000);
    $("#slide").slideToggle(1000);
    #toggle {
      width: 100px;
      height: 100px;
      background-color: red;
    }
    
    #slide {
      width: 100px;
      height: 100px;
      background-color: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="toggle">
    
    </div>
    <div id="slide">
    
    </div>

    As for which one you want to use, obviously, it's context dependent.