jQuery Effect - toggle() Method

Example

Toggle the display and hide state of the <p> element:

$(".btn1").click(function(){
  $("p").hide();
});

Try it yourself

Definition and Usage

The toggle() method toggles the visibility state of elements.

If the selected element is visible, hide these elements; if the selected element is hidden, display these elements.

Syntax

$(selector).toggle(speed,callback,switch)
Parameters Description
speed

Optional. Specifies the speed of the element from visible to hidden (or vice versa). The default is "0".

Possible values:

  • Milliseconds (e.g., 1500)
  • "slow"
  • "normal"
  • "fast"

When setting the speed, the element will gradually change its height, width, margin, padding, and opacity during the process from visible to hidden.

If this parameter is set, the switch parameter cannot be used.

callback

Optional. The function to be executed after the toggle function is executed.

For more information about callback, please visit our jQuery Callback chapter.

This parameter cannot be set unless the speed parameter is set.

switch

Optional. Boolean value. Specifies whether toggle hides or displays all selected elements.

  • True - Display all elements
  • False - Hide all elements

If this parameter is set, the speed and callback parameters cannot be used.

Tips and Notes

Note:This effect applies to elements hidden by jQuery or elements declared display:none in CSS (but not to elements with visibility:hidden).

More Examples

Use the speed parameter
Use the speed parameter to hide and display elements.
Use the switch parameter
Use the switch parameter to display all hidden paragraphs.