Categories

.toggle()

Categories: Basics | Mouse Events

.toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] )Returns: jQuery

Description: Bind two or more handlers to the matched elements, to be executed on alternate clicks.

  • .toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] )

    version added: 1.0

    handler(eventObject)   A function to execute every even time the element is clicked.

    handler(eventObject)   A function to execute every odd time the element is clicked.

    handler(eventObject)   Additional handlers to cycle through after clicks.

The .toggle() method binds a handler for the click event, so the rules outlined for the triggering of click apply here as well.

For example, consider the HTML:
<div id="target">
  Click here
</div>

Event handlers can then be bound to the <div>:

$('#target').toggle(function() {
  alert('First handler for .toggle() called.');
}, function() {
  alert('Second handler for .toggle() called.');
});

As the element is clicked repeatedly, the messages alternate:

First handler for .toggle() called.

Second handler for .toggle() called.
First handler for .toggle() called.
Second handler for .toggle() called.
First handler for .toggle() called.

If more than two handlers are provided, .toggle() will cycle among all of them. For example, if there are three handlers, then the first handler will be called on the first click, the fourth click, the seventh click, and so on.

Note: jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.

  • Click to toggle highlight on the list item.

    HTML:
    <ul>
        <li>Go to the store</li>
        <li>Pick up dinner</li>
        <li>Debug crash</li>
    
        <li>Take a jog</li>
      </ul>
    CSS:
    
      ul { margin:10px; list-style:inside circle; font-weight:bold; }
      li { cursor:pointer; }
      
    Code:
    
        $("li").toggle(
          function () {
            $(this).css({"list-style-type":"disc", "color":"blue"});
          },
          function () {
            $(this).css({"list-style-type":"disc", "color":"red"});
          },
          function () {
            $(this).css({"list-style-type":"", "color":""});
          }
        );
    
    
  • To toggle a style on table cells:

    Code:
    $("td").toggle(
      function () {
        $(this).addClass("selected");
      },
      function () {
        $(this).removeClass("selected");
      }
    );

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

Description: Display or hide the matched elements.

  • .toggle( [ duration ], [ callback ] )

    version added: 1.0

    duration   A string or number determining how long the animation will run.

    callback   A function to call once the animation is complete.

  • .toggle( [ duration ], [ easing ], [ callback ] )

    version added: 1.0

    duration   A string or number determining how long the animation will run.

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

    callback   A function to call once the animation is complete.

  • .toggle( showOrHide )

    version added: 1.0

    showOrHide   A Boolean indicating whether to show or hide the elements.

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.

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

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();
}

Note:

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.
  • Toggles all paragraphs.

    HTML:
    <button>Toggle</button>
    <p>Hello</p>
    <p style="display: none">Good Bye</p>
    Code:
    
    
    $("button").click(function () {
    $("p").toggle();
    });
    
  • Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds.

    HTML:
    <button>Toggle 'em</button>
    
    <p>Hiya</p>
    <p>Such interesting text, eh?</p>
    CSS:
    
    p { background:#dad;
    font-weight:bold;
    font-size:16px; }
    
    Code:
    
    $("button").click(function () {
    $("p").toggle("slow");
    });    
    
  • Shows all paragraphs, then hides them all, back and forth.

    HTML:
    <button>Toggle</button>
    <p>Hello</p>
    <p style="display: none">Good Bye</p>
    Code:
    
    
    var flip = 0;
    $("button").click(function () {
    $("p").toggle( flip++ % 2 == 0 );
    });