How to use jQuery Toggle Method – .toggle() effectively

How to use jQuery Toggle Method – .toggle() effectively

The jQuery Toggle method (.toggle())will toggle between hide() and show() properties for the selected elements. This means if an element is hidden then .toggle() will show it, similarly if the element is showing then .toggle will hide it.

.toggle() Syntax

$(selector).toggle(speed,easing,callback)
Parameter Description
speed Optional value.
Specifies the speed of the toggle effect.
It can be:
  • milliseconds – .toggle(1000)
  • “slow” – .toggle(“slow”)
  • “fast” – .toggle(“fast”)
easing Optional value.
Specifies the type of speed of the element during the toggling. Default value is “swing”.
It can be:
  • “swing” – beginning slow, faster in the middle & slow at the end.
  • “linear” – constant speed
callback Optional. A function to be executed after the toggle method is completed.
You can also use .toggle() method to create jQuery Tabs feature quite easily.

Example 1: Toggle a div

The following code toggles a div element with id called div1.

$("#div1").toggle();

Example 2: Toggle a div with speed

The code below toggles the div in 2 seconds.

$("#div1").toggle(2000);

Example 3: Toggle a div with speed & easing

Here I have passed the speed and easily parameters to the jQuery Toggle method.

$("#div1").toggle("slow", "linear");

Example 4: Toggle with callback function

In this code I have also passed a callback function that will show the alert message after the toggling is finished.

$("#div").toggle("slow", "linear", function () {
    alert("Toggling is finished!");
});

Download source codes:

DOWNLOAD

Next to read: jQuery toggleClass to toggle between adding and removing classes from an element.

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate