jQuery .toggleClass() method adds or removes the class for selected elements
Syntax and Description
.toggleClass()
adds or removes a class from
each element in the set of matched elements.
.toggleClass(className)
className
: A class name to be toggled in the class attribute of each element in the matched set.toggleClass(className, addOrRemove)
addOrRemove
: A Boolean indicating whether to add or remove the class.toggleClass(function[, addOrRemove])
function
: A function that returns a class name to be toggled in the class attribute of each element in the matched set.
addOrRemove (optional)
: A Boolean indicating whether to add or remove the class
Its return value is the jQuery object, for chaining purposes.
For example, we can apply .toggleClass()
to a simple <div>
as follows:
<div class="tumble">Some text.</div>
The first time we apply $('div.tumble').toggleClass('bounce')
, we get:
<div class="tumble bounce">Some text.</div>
The second time we apply $('div.tumble').toggleClass('bounce')
, we get:
<div class="tumble">Some text.</div>
$('#foo').toggleClass(className, addOrRemove);
is equivalent to
if (addOrRemove) {
$('#foo').addClass(className);
}/*from ww w. j av a 2 s.c o m*/
else {
$('#foo').removeClass(className);
}
The .toggleClass()
method allows us to
indicate the class name to be toggled by passing in a function.
$('div.foo').toggleClass(function() {
if ($(this).parent().is('.bar') {
return 'happy';
} else {// w ww . j a v a 2 s. c o m
return 'sad';
}
});
Toggle single class
The following code toggles single class for paragraph during the click event.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w w w. j a v a2s . c om-->
$("p").click(function () {
$(this).toggleClass("blue");
});
});
</script>
</head>
<style>
.blue { color:blue; }
</style>
<body>
<body>
<p class=blue>java 2s.com</p>
</body>
</html>
Toggle div element color
The following code toggles DIV element color.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w w w.j a v a2 s .c o m-->
$("#run").click(function(){
$("div").toggleClass("colored");
});
});
</script>
<style>
div { background:yellow;
width:80px; height:80px; margin:5px; float:left; }
div.colored { background:green; }
</style>
</head>
<body>
<button id="run">Run</button>
<div>java2s.com</div>
<div id="mover">java2s.com</div>
<div>java2s.com</div>
</body>
</html>