
In this lesson I want to illustrate you how to use some useful jQuery methods that allow you to manipulate easily CSS classes. In particular I prepared some examples to explain the following methods: toggleClass(), hasClass(), addClass() and removeClass().
For a printable reference guide to the jQuery API I suggest you to download my jQuery Visual Cheat Sheet or take a look at the official jQuery documentation.
Highlight content
Start taking a look at this basic example. Here is a list of items. You can highlight each item of the list by clicking over it and return to the original status with a second click. Try to click on the items listed below:
- Smashing Magazine
- Woork Up
- Mashable
This effect is very simple to implement using the jQuery toggleClass() method. This method adds to the selected element a specified class if it is not present and removes the specified class if it is present. In this example I created the following class to highlight a selected item:
.selected{background:#ffffcc;}Here is the HTML code, a simple ul list with the class attribute set to selectList:
<ul class="selectList">
<li>Smashing Magazine</li>
<li>Woork Up</li>
<li>Mashable</li>
</ul>Here is the javascript code that uses the toggleClass() method:
$(document).ready(function() {
$(".selectList li").click(function (){
$(this).toggleClass('selected');
})
});In this way you can apply this effect to all li elements contained into an ul list with the class attribute set to .selectList.
Highlight content with animation
This example illustrates how to improve the previous effect adding a custom animation when an element is selected. Here is the result (click on a item below):
- Smashing Magazine
- Woork Up
- Mashable
The HTML code is the same of the previous example: an ul list with the class attribute set to selectList. Here is the javascript code:
$(document).ready(function() {
$(".selectList li").click(function (){
$(this).toggleClass('selected');
margin = $(this).css('margin-left');
if(margin=='0px'){
leftmargin='20px';
} else {
leftmargin='0px';
}
$(this).animate({
marginLeft: leftmargin,
}, 400 );
})
});I used animate() to animate the selected item. Take a look at this lesson about the animate() method.
Animated expandable sections
This example illustrates how to implement expandable sections using hasClass() and slideToggle() methods. In particular, hasClass() checks the current selection against a class and returns true if at least one element of the selection has the given class. Take a look at the following example and click on “About Us” or “Popular Now”:
Here is the CSS code:
.expand-header{
background:url(pic/plus.gif) #DFDFDF no-repeat;
cursor:pointer;
}
.expand-header-no{
background:url(pic/minus.gif) #DFDFDF no-repeat 4px 4px;
cursor:pointer;
}Here is the HTML code:
<div class="expand-header-no" id="e1">About Us</div>
<div class="expand" id="e1-s">
HTML code here...
</div>
<div class="expand-header-no" id="e2">Popular Now</div>
<div class="expand" id="e2-s">
HTML code here...
</div>Here is the JavaScript code:
$("div[class^='expand-header']").click(function (){
if($(this).hasClass('expand-header-no')){
$(this).removeClass('expand-header-no');
$(this).addClass("expand-header");
} else {
$(this).removeClass('expand-header');
$(this).addClass("expand-header-no");
}
el = $(this).attr("id");
el = el+"-s";
$("#"+el).slideToggle(300);
});In this example I also used the addClass() and removeClass() methods to add/remove the specified class (expand-header or expand-header-no) to each matched element.
The selector $("div[class^='expand-header']") matches all elements with the class attribute that starts with "expand-header".
Check box list simulation
In this example I used addClass() and removeClass() methods to simulate a check box list (try to click on an item to select it):
- Smashing Magazine
- Woork Up
- Mashable
- TechCrunch
To implement this effect you have to create two CSS class .unchecked and .checked that represent the checked and unchecked status:
.unchecked{
background:url(ui-radio-button-uncheck.png) no-repeat;
padding-left: 20px;
cursor:pointer;
}
.checked{
background:url(pic/ui-radio-button.png) no-repeat;
padding-left: 20px;
font-weight: bold;
}
Here is the HTML code:
<ul class="checkboxList">
<li class="unchecked">Smashing Magazine</li>
<li class="unchecked">Woork Up</li>
<li class="unchecked">Mashable</li>
<li class="unchecked">TechCrunch</li>
</ul>Here is the JavaScript code:
$(".checkboxList li").click(function (){
if($(this).hasClass('unchecked')){
$(this).removeClass('unchecked');
$(this).addClass('checked');
} else {
$(this).removeClass('checked');
$(this).addClass('unchecked');
}
});
That’s all for this lesson! If you have suggestions or specific requests for the next lesson leave a comment. For a printable reference guide to the jQuery API I suggest you to download my jQuery Visual Cheat Sheet or take a look at the official jQuery documentation.
by
Antonio Lupetti is an italian engineer, pro blogger, Mac user, founder of woorkup.com. He lives in Rome, Italy. Follow Antonio on 

November 6, 2009 at 7:20 pm
Thank a lot I don’t have much knowledge but the tutorial of yours are inspiring me lot. I am learning everyday new things.
November 6, 2009 at 7:50 pm
really nice article. helps me brainstorm some ideas for future work and contact form/list building. Thanks for all of the kick ass content!
November 6, 2009 at 9:41 pm
Man! Antonio – this stuff has been demonstrated and explained across sites but how come only you get it right? I get engaged the minute you start explaining. Loving this series- more! more!
November 6, 2009 at 11:38 pm
gr8 article … the jquery has really been impressive in every aspect … i love to learn more and more on jquery
November 7, 2009 at 12:21 am
This is a very nice primer tutorial for people (like me) who know CSS and just do a little dabbling in jQuery. Thanks a lot! I’m curious though, if you’d be willing to extend this to show us how to toggle only one element. For example, if one item is already highlighted, the other one will return to its original state?
November 7, 2009 at 1:40 am
Loved this post. Especially the second one is the best. However,I’m confused where should I place the JS code? In CSS?
November 7, 2009 at 12:09 pm
@Aminul: You put the JS in the HTML-code. You must also have the jQuery-files linked in your HTML HEAD-tag.
November 7, 2009 at 10:21 am
OOps very nice && easy !
November 7, 2009 at 3:57 pm
Hello! these series of CSS classes manipulation using jQuery are nice! Recently, I use a common javascript toggle to hide and show my long blog post at the front page. Your tutorial showed that expandable sections can be animated too. So maybe I’ll implement it later ;) Thanks!
November 8, 2009 at 2:54 am
> el = $(this).attr(”id”);
> el = el+”-s”;
> $(”#”+el).slideToggle(300);
You could’ve just used $(this).children(”.expand”). But great examples anyway :)
November 8, 2009 at 5:48 am
Very wonderfull script, i like the Highlight content with animation
November 8, 2009 at 11:05 pm
This was very useful! I hope you continue this series :)
November 9, 2009 at 6:30 am
jQuery is very nice, i like it too!
November 9, 2009 at 3:16 pm
whooa…!!
i like j query….
it so smooth…
:-)
thank’s antonio fo sharing…
November 10, 2009 at 2:07 am
Simple and good article. Shows how simple usability can be improved by using jQuery.
November 10, 2009 at 6:39 am
Hey Antonio, great tutorial.
I have one question though, in the last two examples instead of:
if($(this).hasClass(’unchecked’)){
$(this).removeClass(’unchecked’);
$(this).addClass(’checked’);
} else {
$(this).removeClass(’checked’);
$(this).addClass(’unchecked’);
}
could you just toggle the classes like this?
$(this).toggleClass(’unchecked’);
$(this).toggleClass(’checked’);
I understand that you wanted to show the ‘addClass’ and ‘removeClass’ functions and am just wondering if toggle would work.
November 10, 2009 at 7:04 am
Great article as always Antonio. that toggleClass got me. lol. I need to update one of my own posts now. thanks again for your help in the web community. it’s really appreciated.
November 10, 2009 at 8:17 am
great post! keep up the good work.
November 17, 2009 at 3:59 am
Hi Antonio,
You’ve applied some simple jQuery effects really nicely here to make simple actions more intuitive. I like the checkbox simulation, though I would suggest that you use a single background image instead of two separate ones, and simply change the CSS background-position between the .unchecked and .checked classes to make the transition, from ‘unchecked’ to ‘checked’, seamless the first time you use it.
November 19, 2009 at 2:27 pm
[...] previousy mentioned about addClass(), removeClass() functions in Manipulating CSS Classes lesson and animate() function in this lesson. But the usage of animate() function is a bit [...]