How to use toggle in jQuery
Toggle in jQuery simply refers to a built-in method that can be applied to any element on a page; it is used to hide or show that particular element. The button that is used to toggle moves over the text to hide it.
Once clicked again, the button goes back to its original position and reveals the text.
Syntax
The toggle method has the syntax as shown below:
$(selector).toggle(speed,easing,callback);
Parameters
-
speed: This can either be given in milliseconds or in the textual input as “slow” or “fast”. The speed determines the rate at which thetogglewill hide or show the text. -
easing: This has two possible input values,“swing” or “linear”, with the former being the default value. This value determines whether the entiretogglewill run at the same pace (i.e. linearly) or if it will increase speed in the middle (i.e. swinging). -
callback: This is simply a method that can be called to execute once thetogglemethod has run.
Note: All three of these parameters are optional.
Now that we know how the method works, let’s look at different implementations of the method below!
Examples
1. Simple toggle
The example below shows how to simply use the toggle method
2. Adding delay
The example below shows how to add a delay to the toggle method. In this example, we have added a delay of 2 seconds
3. Adding delay without using numbers
The example below shows how to use the delay functionality, using built-in textual values, instead of giving it a time-limit
4. Using the easing property
The example below shows how to change the easing property of the toggle method to linear, and how to add a time-delay of a few seconds.
5. Using callback
The example below shows how a callback method can be implemented in the toggle method upon its execution
Free Resources