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

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

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 !

Share this post: