Quite often you achieve altering a specific HTML element’s look and feel by assigning it to a particular class, that class already possessing some customised CSS style rules in the document’s main stylesheet.
There are of course times when you actually want to achieve this visual style change on the fly, say for instance when you hover over a table row (change it’s background color for example) and the good news for you is that jQuery makes this particular ability of adding or removing classes to any element on the fly an absolute doddle.
So how is this achieved?
Well jQuery comes bundled with the handy hasClass, addClass and removeClass functions, which all do pretty much as their names suggest. The trick is to attach them to a particular selector (whichever element whose class membership you want to alter), as well as specify the name of the class that they will need to act upon.
if ( $('body').hasClass('blue') ) {
$('body').removeClass('blue');
} else {
$('body').addClass('blue');
}
Looking at the code above, you’ll see we’re essentially toggling the body element’s class structure, adding “blue” to it should it not already belong to that class. If however body already has the blue class instated, we then rather remove it.
It really is that simple and immediately thrusts a lot of event-driven visual manipulation power into your hands, so go forth and alter wisely my sons! :P
Related Posts :
From jQuery 1.2 onwards, the ability to tween (animate) from one color to another, in other word ...
Using jQuery to highlight a table row on mouse over is pretty simple to achieve, and today I'll ...
I’ve mentioned the wonderful jQuery plugin DataTables a number of times before, the awesome litt ...
To bind a hover effect, in other words a mouse over and mouse out event that goes together, to a ...
Flot is a fantastic jQuery-driven graphing engine that is extremely flexible and capable of prod ...






