JQuery Tutorials

Toggle the CSS Class Name

Toggle the CSS Class Name with JQuery

Here are two examples of how to toggle the CSS class name of an HTML element using JQuery.

The JQuery File

Create a new page and add a link to the JQuery file.

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

CSS styles

Create CSS styles for your elements on the page (as they should display initially) and create another class name you want to use for the toggle.

<style type="text/css">
<!--
td {
font:12px Verdana, Geneva, sans-serif;
background-color: #f0f0f0;
padding: 4px;

}
.myTableHeaders {
background: #222 url(toggle_class_header.gif);
color: #fff;
}
.myToggleClass {
background-image: url(toggle_class_content.gif);
color: #fff;
}
-->
</style>

 

First Example

In this first example I will show you how to toggle the class name of a table cell, inside the layer with the ID #myFirstDemo, which has the initial class name .myTableContent, using the JQuery hover function.

<script type="text/javascript">
$(document).ready(function() {
$("#myFirstDemo .myTableContent").hover(function() {
$(this).toggleClass("myToggleClass")
});
});
</script>

The HTML code

This is the HTML code for the layer myFirstDemo and for the table:

<div id="myFirstDemo">
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td class="myTableHeaders">Title</td>
<td class="myTableHeaders">Title</td>
</tr>
<tr>
<td class="myTableContent">Lorem Ipsum</td>
<td class="myTableContent">Lorem Ipsum</td>
</tr>
<tr>
<td class="myTableContent">Lorem Ipsum</td>
<td class="myTableContent">Lorem Ipsum</td>
</tr>
</table>
</div>

Demonstration

Title Title
Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum

 

Second Example

In this second example I will show you how to toggle the class name the whole table row, inside the layer with the ID #mySecondDemo, using the same hover function as in the first example.

<script type="text/javascript">
$(document).ready(function() {
$("#mySecondDemo tr").hover(function() {
$(this).toggleClass("myToggleClass")
});
});
</script>

The HTML code

This is the HTML code for the layer and for the table:

<div id="mySecondDemo">
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td class="myTableHeaders">Title</td>
<td class="myTableHeaders">Title</td>
</tr>
<tr>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
</tr>
<tr>
<td>Lorem Ipsum</td>
<td>Lorem Ipsum</td>
</tr>
</table>
</div>

Demonstration

Title Title
Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum

 

Background images

toggle_class_header.gif (original size 1 x 1px)       toggle_class_content.gif (original size 1 x 1px)

 

JQuery Tutorials
Other Tutorials