.toggleClass()
In this chapter you will learn:
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) {//from j av a2 s . c o m
$('#foo').addClass(className);
}
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() {/*from j a v a2 s . c o m*/
if ($(this).parent().is('.bar') {
return 'happy';
} else {
return 'sad';
}
});
Toggle single class
The following code toggles single class for paragraph during the click event.
<html><!-- j a v a 2 s .com-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("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><!--from j a va2 s. c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#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>
Next chapter...
What you will learn in the next chapter: