The toggle method
The toggle method alternates between smooth display/hiding elements. If the element is shown, it will be hidden and vice versa.
Syntax
Show for a given time in milliseconds, 400ms by default:
.toggle(duration);
Time can be specified not only in milliseconds, but also using the keywords slow (600ms) and fast (200ms), the higher the value, the slower the animation:
.toggle('slow' or either 'fast');
You can use the display parameter to pass the value true or false. If true, the element will only be shown, false - hidden:
.toggle(display);
If you do not specify parameters, there will be no animation, the elements will be shown/hide instantly:
.toggle();
You can also pass the smoothing function as the second parameter, and the callback function as the third parameter - it will be triggered after the animation is completed. Both parameters are optional:
.toggle(duration, [smoothing function], [callback-function office]);
You can simply pass a callback function as the second optional parameter - it will be triggered after the animation is completed:
.toggle(duration, [callback-function office]);
You can pass various options to the method, in the form of a JavaScript object containing key:value pairs:
.toggle(options);
Such an object can pass the following parameters and functions - duration, easing, queue, specialEasing, step, progress, complete, start, done, fail, always. You can see the description of these parameters for the method animate. For example, let's set the duration and the smoothing function:
.toggle( {duration: 800, easing: easeInSine} );
Example
Let's smoothly show the hidden paragraph after pressing the button using the toggle method. By passing the keyword slow, we set the speed to 600ms. Hide on repeated pressing:
<button>show text</button>
<p style="display: none">text</p>
$('button').click(function() {
$('p').toggle('slow');
});
See also
-
method
fadeToggle,
which changes the transparency of elements -
method
slideToggle,
which alternates between smooth showing/hiding elements -
method
show,
which smoothly shows the elements -
method
hide,
which smoothly hides elements