🚨 $100K in Sight: Follow Bitcoin’s Final Push Live! TRACK NOW

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!
DataCamp
Pros
  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
Udacity
Pros
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
Main Features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion
edX
Pros
  • A wide range of learning programs
  • University-level courses
  • Easy to navigate
  • Verified certificates
  • Free learning track available
Main Features
  • University-level courses
  • Suitable for enterprises
  • Verified certificates of completion

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.