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!
- 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
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- 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, orfast
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:
$("#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.