Description
The .toggle() method is used to bind two or more event handler functions to toggle between for the click event for selected element.
This method can also be used to toggle between hide() and show() for the selected element.
Bind Two or More Functions to a Toggle Event
Toggle between two or more functions when the specified element is clicked.
Note: If more than two functions are specified, the toggle() method will toggle between all of them. For example, if there are three functions, the first function will be called on the first click, the second function on the second click, the third function on the third click. On the fourth click the first function will be called again, and so on.
This method has the form:
.toggle(function(),function(),function(),...)
Parameter | Description |
---|---|
function() | (required) Specifies a function to run every EVEN time the element is clicked |
function() | (required) Specifies a function to run every ODD time the element is clicked |
function(),... | (optional) Specifies additional functions to toggle between |
Return Value
This form returns a jQuery object.
Examples
Toggle between different background colors:
$("p").toggle(function(){
$("body").css("background-color","green");},
function(){
$("body").css("background-color","red");},
function(){
$("body").css("background-color","yellow");}
);