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!
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
Coursera
Pros
  • Professional service
  • Flexible timetables
  • A variety of features to choose from
Main Features
  • Professional certificates of completion
  • University-level courses
  • Multiple Online degree programs
Datacamp
Pros
  • Great user experience
  • Offers quality content
  • Very transparent with their pricing
Main Features
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

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.

Latest Udacity Coupon Found:

Verified STAFF PICK

75% OFF COURSES

Udacity Black Friday Offer

The best time to save on Udacity courses is now - follow this coupon to access a 75% Udacity Black Friday discount & enjoy learning at a very low cost!

Expiration date: 28/01/2021
3176 People Used
Only 97 Left
Rating
5.0