HTML and CSS Reference
In-Depth Information
FIGURE 16.6
Paragraphs are
highlighted when
the mouse is over
them.
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>
<script src=”jquery-1.4.2.min.js” type=”text/javascript” charset=”utf-
8”></script>
<script type=”text/javascript” charset=”utf-8”>
$(function () {
$(“li”).click(function () {
$(this).toggleClass(“highlighted”);
});
});
</script>
<style type=”text/css” media=”screen”>
li.highlighted { background: yellow; }
</style>
</head>
<body>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
</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 function,
the first time the user clicks a list item, the highlighted class will be applied. The sec-
ond time, an alert (shown in Figure 16.7) will be displayed indicating that the item is
already highlighted:
Search WWH ::




Custom Search