Wednesday, December 23, 2009

Change Style Sheets Using Javascript

Themes are one of the most beautiful features that gives a web application very impressive survey and feed back. I happened to win a Client project because of the same.

It is quite easy to obtain this feature as well. Following is a simple illustration to perform the same.

Let me assume that my html page contains one link tag, pointing to a specific css file as follows,

<html>
 <head>
  <link rel='stylesheet' type='text/css' href='style1.css'/>
   ....
 </head>
 <body>
  ....
  <input type='button' value='Change Style' onclick='changeStyle()'/>
  ....
 </body>
<html>

My changeStyle() function shall contain the following code to help apply a new style sheet for my page with out refreshing the same,

function changeStyle() {
  document.getElementsByTagName('link')[0].href='style2.css';
}

Also you can enable and disable the style sheets that you have already defined in the following way

document.styleSheets[StyleSheetIterator].disabled = false;
document.styleSheets[StyleSheetIterator].disabled = true;

This seems to work fine with the following browsers,
Internet Explorer 6+,
Mozilla Firefox 3.5.6,
Opera 10.10
Safari 4.0.4


This is a very simple example and I have aimed at helping you understand the very core of the issue. In real time there would be more than one css applied for the page and you may have to develop your own mechanism of tracking and changing the ones as necessary.

No comments:

Post a Comment