Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

510 LESSON 18: Using jQuery


You can use jQuery’s toggleClass() method to reverse the state of a particular class
on an element. In the following example, the elements in the list are highlighted the first
time the user clicks them, and the highlighting is removed the next time the user clicks
them. All that’s required is to toggle the highlighted class with each click:
<!DOCTYPE html>
<html>
<head>
<title>Altering Classes on the Fly</title>
<style>
li.highlighted { background: yellow; }
</style>
</head>
<body>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>

<script src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
$("li").click(function () {
$(this).toggleClass("highlighted");
});
});
</script>
</body>
</html>

Finally, jQuery can check for the presence of a class using the hasClass() method. If
I change the body of the event handler in the previous example to the following func-
tion, the first time the user clicks a list item, the highlighted class will be applied. The
second time, an alert (shown in Figure 18.7) will be di splayed indicating that the item is
already highlighted:
$("li").click(function () {
if (!$(this).hasClass("highlighted")) {
$(this).addClass("highlighted");
}
else {
alert("This list item is already highlighted.");
}
});
Free download pdf