jQuery Tip: How to Switch Css Class for elements

Have you ever come across a situation where you need to switch between two css classes for all the places where these classes are used? For example on click of button, you want to switch between class1 and class2. This can be easily achieved by jQuery. jQuery provides a method "switchClass" which allows you to swtich between two classes. The prototype of switchClass metohd is
switchClass(
'oldClassName',
'newClassName',
'value in millisecond for animation or 'fast'/'Normal'/'slow')
Let's first define the css classes.
<style type="text/css">
    .LargeClass
    {
        font-family: Arial;
        font-size: large;
        font-weight: bold;
        color: Red;
    }
    .NormalClass
    {
        font-family: Arial;
        font-size: small;
        font-weight: bold;
        color: Blue;
    }
</style>
Place a button and a div element. On click of the button we will switch between classes.
<div class="NormalClass">
   jQuery By Example Rocks!!!
</div>
<input type="button" id="btnSwitch" value="Switch Class" />
Below is jQuery code which uses switchClass method.
$(document).ready(function(){
  $('#btnSwitch').click(function(){
     $(".NormalClass").switchClass("NormalClass","LargeClass",'fast');
     $(".LargeClass").switchClass("LargeClass","NormalClass",'fast');
     return false;
  });
});
On button click event, first we are finding all the elements with 'NormalClass' and then changing their CSS to 'LargeClass' and then we are finding 'LargeClass' element and changing their css to 'NormalClass'.

One thing to note here that to use switchClass method, you need to include "jQuery.effects.core.js", which can be downloaded from here. This js file uses latest version of 'jQuery.ui'.
See live Demo and Code.
Feel free to contact me for any help related to jQuery. I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..