Java Reference
In-Depth Information
This code removes the myClass2 CSS class from the element, leaving myClass1 as the only CSS class
applied to the element. The arguments passed to the removeClass() method are optional; all CSS
classes are removed from the element if you do not pass an argument to the method. The following
code removes all CSS classes from the element:
$(“#myDiv”).removeClass();
Using the toggleClass Method
The next method is the toggleClass() method. Unlike the previous CSS class methods, this method
accepts only one class name. It checks if the specifi ed class is present, and removes it if it is. If the class
isn't present, then it adds the class to the element. Look at the following example:
$(“#myDiv”).addClass(“myClass1 myClass2”)
.toggleClass(“myClass2”)
.toggleClass(“myClass2”);
This code fi rst adds the myClass1 and myClass2 CSS classes to the element. The fi rst toggleClass()
call removes myClass2 from the element, and the second call adds it back. This method is handy when
you need to add or remove a specifi c class from the element. For example, the following code is plain
old JavaScript and DOM coding to add and remove a specifi c CSS class depending on the type of event:
if (e.type == “mouseover”)
{
eSrc.className = “mouseover”;
}
else if (e.type == “mouseout”)
{
eSrc.className = “”;
}
With the toggleClass() method, you can cut this code down to the following four lines:
if (e.type == “mouseover” || e.type == “mouseout”)
{
$(eSrc).toggleClass(“mouseover”);
}
Using the toggleClass() method can make your code more effi cient and quicker to download thanks
to a reduced size, which is always a noble goal to shoot for.
Using the hasClass Method
The last CSS class method is the hasClass() method, and it returns true or false value depending on
if the specifi ed CSS class is applied to the element.
$(“#myDiv”).addClass(“myClass1 myClass2”)
.hasClass(“myClass1”);
Like toggleClass(), this method accepts only one class name. In this code, hasClass() returns true
because the element does indeed have the myClass1 CSS class applied to it. This example isn't very
practical because you know exactly what classes are assigned to the element; it was merely provided to
demonstrate how it can be used.
Search WWH ::




Custom Search