From jQuery JavaScript Library
« Back to Events
toggle( fn, fn )
Toggle between two function calls every other click.
Whenever a matched element is clicked, the first specified function is fired, when clicked again, the second is fired. All subsequent clicks continue to rotate through the two functions.
Use unbind("click") to remove.
Arguments:| fn | Function | |
|---|
The function to execute on every even click.
function callback(eventObject) {
this; // dom element
}
|
| fn | Function | |
|---|
The function to execute on every odd click.
function callback(eventObject) {
this; // dom element
}
|
Examples:| Name | Type |
Click to toggle highlight on the list item.
$("li").toggle(
function () {
$(this).css("list-style-type", "disc")
.css("color", "blue");
},
function () {
$(this).css({"list-style-type":"", "color":""});
}
);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("li").toggle(
function () {
$(this).css("list-style-type", "disc")
.css("color", "blue");
},
function () {
$(this).css({"list-style-type":"", "color":""});
}
);
});
</script>
<style>
ul { margin:10px; list-style:inside circle; font-weight:bold; }
li { cursor:pointer; }
</style>
</head>
<body>
<ul>
<li>Go to the store</li>
<li>Pick up dinner</li>
<li>Debug crash</li>
<li>Take a jog</li>
</ul>
</body>
</html>
To toggle a style on table cells:
$("td").toggle(
function () {
$(this).addClass("selected");
},
function () {
$(this).removeClass("selected");
}
);