jQuery API

.toggle()

.toggle( [duration] [, callback] ) Returns: jQuery

Description: Display or hide the matched elements.

  • version added: 1.0.toggle( [duration] [, callback] )

    durationA string or number determining how long the animation will run.

    callbackA function to call once the animation is complete.

  • version added: 1.4.3.toggle( [duration] [, easing] [, callback] )

    durationA string or number determining how long the animation will run.

    easingA string indicating which easing function to use for the transition.

    callbackA function to call once the animation is complete.

  • version added: 1.3.toggle( showOrHide )

    showOrHideA Boolean indicating whether to show or hide the elements.

Note: The event handling suite also has a method named .toggle(). Which one is fired depends on the set of arguments passed.

With no parameters, the .toggle() method simply toggles the visibility of elements:

$('.target').toggle();

The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown. The display property is saved and restored as needed. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.

When a duration is provided, .toggle() becomes an animation method. The .toggle() method animates the width, height, and opacity of the matched elements simultaneously. When these properties reach 0 after a hiding animation, the display style property is set to none to ensure that the element no longer affects the layout of the page.

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

As of jQuery 1.4.3, an optional string naming an easing function may be used. Easing functions specify the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

We will cause .toggle() to be called when another element is clicked:

$('#clickme').click(function() {
  $('#book').toggle('slow', function() {
    // Animation complete.
  });
});

With the element initially shown, we can hide it slowly with the first click:

A second click will show the element once again:

The second version of the method accepts a Boolean parameter. If this parameter is true, then the matched elements are shown; if false, the elements are hidden. In essence, the statement:

$('#foo').toggle(showOrHide);

is equivalent to:

if ( showOrHide == true ) {
  $('#foo').show();
} else if ( showOrHide == false ) {
  $('#foo').hide();
}

Additional Notes:

  • All jQuery effects, including .toggle(), can be turned off globally by setting jQuery.fx.off = true, which effectively sets the duration to 0. For more information, see jQuery.fx.off.

Examples:

Example: Toggles all paragraphs.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
<script>

$("button").click(function () {
$("p").toggle();
});
</script>

</body>
</html>

Demo:

Example: Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds.

<!DOCTYPE html>
<html>
<head>
  <style>
p { background:#dad;
font-weight:bold;
font-size:16px; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button>Toggle 'em</button>

<p>Hiya</p>
<p>Such interesting text, eh?</p>
<script>
$("button").click(function () {
$("p").toggle("slow");
});    
</script>

</body>
</html>

Demo:

Example: Shows all paragraphs, then hides them all, back and forth.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
<script>

var flip = 0;
$("button").click(function () {
$("p").toggle( flip++ % 2 == 0 );
});
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .toggle() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .toggle()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • Greg

    There are issues with toggle in IE8 table rows. See: http://www.code-styling.de/english/jquery-132-c…

    • http://twitter.com/zazaian Mike Zazaian

      Javascript manipulation of table rows in IE8 has proven enormously problematic in many instances. I'd try to stay clear of manipulating TRs with jquery in general if you're concerned about browser compatibility…

      • http://www.gbdesign.net/cms/loadpage/JQuery_Toggle garry taylor

        I had an issue where I wanted the toggle to fade in and out. I found a great plugin that allows toggle fades but I need to tweek it a little. I have posted the details here:
        JQuery Toggle Fade

        • http://twitter.com/nyuszika7h Nyuszika7H

          Since jQuery 1.4.4, you can use .fadeToggle() to do that. ;)

  • http://twitter.com/thegrump thegrump

    I found that the toggle method here does not actually work based on the current state of the element or property specified, but that it actually cycles between the various states you provide or boolean based on it’s own internal counter. This would be only useful for things in which you can count on the state remaining the same until the next toggle was called.

    If you were to use the toggle method and define custom anonymous functions which change css properties, then if you were coding a change to the same property elsewhere, you would have a big problem on your hands. The suggestions above don’t help as calling the toggle(true) or false would only show or hide the element, rather than running the anonymous functions you’ve defined. Calling click() would activate your custom click functions too, which would become a circus of mayhem as I’ve seen myself.

    Therefore, I suggest this method be renamed to “cycle”, and then a true toggle method be created that will actually check the existing state of the property, and toggle to the next one in the series appropriately.

  • Thorben

    toggling with any effect on a works not as expected in chrome 5.0.375.70 as it basically destroys the table by putting all the content of the toggled tr in just the first “td” (that’s how it looks like)

    • D Schoone

      I guess it has to do with what toggle does. Does toggle say to the td-element (in css) display:block ? Whilst for most of the users td's are display:table-cell

    • Noemail

      If you're not using animation, you can add/remove a class to the table and define class simply to be {display:none}. Since addClass does not replace existing css on the table, it should work.

  • Nux

    Duration specification is missing:
    * “slow”
    * “normal”
    * “fast”
    * [milliseconds]

  • Wherjh

    hjkhj

  • Madee4u

    toggle does n't work in IE 7 but works in IE 8 and Firefox. Does anyone came across this probelm? or any workaround to make it work in IE 7

  • Dick Adams

    Unless I'm missing something here, there's a form of toggle() that takes no arguments at all, & simply toggles the selected elements' visibility. The documentation above doesn't seem to address this.

    • http://twitter.com/itdoesawesome Victor Rehorst

      The second documented form of toggle() has two optional arguments.

      • Dick Adams

        Well, yes, but it doesn't say what happens if you don't supply the optional arguments. Maybe it's implied somewhere, but I sure don't see it. Even it IS implied, the documentation should be more explicit about the expected outcomes.

        • http://www.learningjquery.com/ Karl Swedberg

          Sorry about that. There was an XML parsing error in the entry that prevented the explanatory content from displaying. I just fixed it, so the documentation should be adequately explicit now. Please let me know, though, if it's still missing something.

          Thanks for bringing this to our attention!

  • molokoi

    hello. Is there a way to explicitely set toggle() state regardless of current state, I mean odd or even state. Something like $(“element”).toggle(even) or $(“element”).toggle(odd) ( $(“element”).click() wont do what I am looking for )

  • BananaAcid

    it seems that the 2 handler version does not work since 1.4.2. it just does not do anything… no error thrown. (i tried the example handlers, no luck. toggle itself works = no params)

    • Doc

      agreed – does not accept the 2 toggled callbacks. Will a a function, or two comma separated function calls, but one or both, respectively will be fired each time, not alternating like the documentation says. I also posted the example into my code as a test and it failed each time.

    • Asdasd

      seems i have the same problem

    • Jd

      It actually still support this signature, but the documentation is a bit messed-up. This behaviour is reported under http://api.jquery.com/toggle-event/.

  • Kcobblers

    Can anyone explain why you cannot use toggle() to change the state of a child element from visible to hidden when its parent element is itself hidden! However, you can use toggle to change a child element from hidden to visible when the parent itself is hidden! This seems inconsistent to me. Is there a good reason for this?

  • GG-boo

    Nice!

  • Tom

    My line saying “Aktion” is actually: <*span id=”act2_252″*>Aktion<*/span*>

  • Onique

    what if i have multiple divs and I want to toggle between them. One open and the rest closed. The next opened the previously opened one closes?

  • Laurence Tremblay

    Is there a way to change the default “display” activated by the toggle?

    Right now when I toggle my element… it put the css “display”:”block”…. i'd like to have my display set to “inline-table”…?

  • http://www.abea.se/ kilian_guntner

    nice one

  • http://www.raghibsuleman.com/ Raghib Suleman

    Very good tutorial….
    http://www.raghibsuleman.com/

  • Naby08

    hello people is there a script of the button being there first and after you press it then the text appears?

    Thanks

    • Guilllaume Thys

      I want to know that aswell… somebody with an answer? thx !

  • developer in php

    Its very much useful for my code….
    Thanks a lot …

  • hadi_p88

    baaaa

  • hadi_p88

    test

  • hadi_p88

    test

    • Adrian

      yeh great post – just what am after …need to walk first – thanks!

  • Christiansita

    I like it

  • Joe

    The toggle seems to track the last action , either a show or hide, not based on whether or not the element is showing or hidden. This is probably because a toggle can begin in either state. So here's an example. You show an element via clicking in it (fires a toggle). Now, you have another element that when clicked, will hide the original element that was shown with the toggle. When you return to the toggle to show the element via toggle, you will have to click it twice before the toggle “catches up”.

    Is there any function that can invoke a “click” on the original toggle, instead of hiding it manually and throwing off the toggle tracking.