Black friday

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

Using jQuery .toggle() Method for Showing and Hiding Elements

Reading time 2 min
Published Jan 16, 2018
Updated Sep 27, 2019

jQuery toggle: Main Tips

  • The .toggle() jQuery method alternates between the .hide() and .show() methods each time it is applied.
  • Depending on the parameters defined, you can make jQuery toggle visibility by animating elements or showing and hiding them without any effects.
  • This is an animation method - don't confuse it with the jQuery .toggle() method for event handling which was deprecated in jQuery 1.8 and removed completely in jQuery 1.9!
Theory is great, but we recommend digging deeper!

Learn to Use .toggle()

The jQuery .toggle() method toggles between .hide() and .show() methods. In the example below, the same button makes an element appear and reappear:

Syntax for jQuery .toggle()

Here is the syntax you would use to make jQuery toggle visibility:

$("selector").toggle(time, easing, callback);

Note: all three parameters for jQuery .toggle() are optional: you can skip them if the default values suit you.

First, time defines the duration of the animation. You can specify it in two ways:

  • Define the duration in a number of milliseconds (the default value is 400)
  • Use a keyword: slow for 600 ms, or fast for 200 ms.

To indicate the changes in animation speed, you can specify easing. This argument takes one of two keywords:

  • swing (the default value)
  • linear (progressing gradually)

To add a function to be executed after you toggle jQuery animation, define callback. Developers mostly use this for creating effect sequences.

In the example below, time and callback arguments are added to slow the transition down and make additional text appear after it ends:

Example
$("#toggle").click(function(){
   $(".target").toggle('slow', function(){ 
       $(".log").text('You have successfully toggled!');
   });
  });
});

Tip: you can use both named and anonymous functions to be executed after toggling.