jQuery Event - toggle() Method
Example
Switch to different background colors:
$("p").toggle( function() { $("body").css("background-color","green"); function() { $("body").css("background-color","red");}, function() { $("body").css("background-color","yellow");} );
Definition and usage
The toggle() method is used to bind two or more event handler functions to respond to the click events of the selected elements in a rotating manner.
This method can also be used to toggle the hide() with show() Method.
Bind two or more functions to Toggle event
Toggle between two or more functions when the specified element is clicked.
If two or more functions are specified, the toggle() method will toggle all functions. For example, if there are three functions, the first click will call the first function, the second click will call the second function, the third click will call the third function. The fourth click will call the first function again, and so on.
Syntax
$(selector).toggle(function1(),function2(),functionN(),...)
Parameters | Description |
---|---|
function1() | Required. Specifies the function to be executed when the element is clicked an even number of times. |
function2() | Required. Specifies the function to be executed when the element is clicked an odd number of times. |
functionN(),... | Optional. Specifies other functions to be toggled. |
Toggle Hide() and Show()
Check if each element is visible.
If the element is already hidden, run show(). If the element is visible, hide() the element. This can create a toggle effect.
Syntax
$(selector).toggle(speed,callback)
Parameters | Description |
---|---|
speed |
Optional. Specifies the speed of the hide/show effect. The default is "0". Possible values:
|
callback |
Optional. Function to be executed when the toggle() method is completed. For more information on callbacks, please visit our Callback Function Tutorial. |
Show or hide elements
Specifies whether only the matched elements should be shown or hidden.
Syntax
$(selector).toggle(switch)
Parameters | Description |
---|---|
switch |
Required. Boolean value, specifying whether toggle() should only show or only hide all selected elements.
|