javascript,tutorials

Change a CSS class dynamically using Javascript

27 Dec , 2008  

Hi everyone,

Yet another tutorial of javascript explaining very basic functionlity of it. But this can be extended further to fo the javascript magic icon smile Change a CSS class dynamically using Javascript

Well in this you will learn how to change the class of any element dynamically on an event. I am using the onclick event which is fired when the div is clicked. I have associated a function changeClass() when the div gets clicked. The HTML code for the div would be

<div id="my-div" class="first" style="width: 200px;" onclick="changeClass(this);">
    Hi i am the text just when the page loads with a default class</div>

I have defined two classes namely first,second to define the styles of the div. These classes get interchanged by simply clicking on the done. This functionality is achieved by the javascript function. The two css classes look like :

.first{
background:silver;
padding:20px;
color:#ffffff;
}
 
.second{
background:yellow;
padding:30px;
color:#000000;
 
}

Now we need to define the logic in javascript which let us interchange the two classes dynamically.

function changeClass(x)
{
	x.className=(x.className=="first")?"second":(x.className=="second")?"first":"second";
}

All set all done.
When you copy paste these block of codes in their respecting places, i.e. javascript function inside script tags and css code inside style tags this should appear just like the working example shown below.

Hi i am the text just when the page loads with a default class

For those who do not want to copy the whole working code Click Here to unhide the code

Cheers !!
Realin !

, ,


2 Responses to “Change a CSS class dynamically using Javascript”

  1. Honour Chick says:

    very useful info… thanks :)

  2. Marty Turner says:

    Nice, but I think you could simplify this.

    Being as you are only toggling the classnames, you could cut your function down to:

    function changeClass(x)
    {
    x.className=(x.className==”first”)?”second”:”first”;
    }

    This will also mean that you will get a result even if your element starts off without either of the classnames assigned. ;-)

More in javascript, tutorials (102 of 114 articles)


I know this is just another tutorial you found online for creating horizontal menu on a self hosted wordpress blog. ...