The jQuery toggle() method

The toggle() method is used to toggle between show and hide selected HTML elements. If elements are hidden then toggle method will show specified hidden element(s) and vice versa.

Note: If you only require to show the hidden elements then use the jQuery show method. For hiding visible elements, use the $.hide method.

Syntax of toggle jQuery method

$(selector).toggle(speed,callback)

Where

Selector = can be an element like div, p, etc.
Speed = Optional parameter that specifies the hidden speed with possible values of

  1. “slow”
  2. “fast”
  3. Or value in milliseconds

(See examples below with each option)

Callback = after the toggle() method is completed, an optional callback function to perform certain action can be given. An example is shown below with an alert.

Example of toggle() method

In this example, we will use the jQuery toggle method to show/hide DIV element with the name “text” after clicking “Toggle Yellow line” button.

Experience this example online

The example of jQuery toggle with ‘fast’ value

For the second example, I used the ‘fast’ value for showing the initially hidden element. Click on the button to display the div element containing text with red color:

Experience this example online

The code:

How to use time in milliseconds?

In the example, we used the third option for showing/hiding the specified element i.e. the time in milliseconds. For that, I used 3500 value which means 3.5 seconds.

Again, click the button to display the initially hidden div tag with green color and click again to hide it. In both cases, the process should complete in 3.5 seconds. Give it a try:

Experience this example online

Example of toggle method with callback function

The callback function is used in this example after the jQuery toggle method is executed. The slow value is given for speed and once the process is completed, an alert will trigger:

Experience this example online

Also see: jQuery show() method | jQuery hide() method