This page has been archived. For the latest news on FormAssembly, go to: http://www3.formassembly.com/blog

Javascript Enabled Stylesheets

It is sometimes necessary to hide a CSS stylesheet from the browser if javascript is disabled or not available.

A collapsed section of a document, for instance, will never be visible if the javascript functionality to expand it is not working. To prevent this situation from happening you need two different behaviors: “section expanded” if javascript is disabled and “section collapsed” otherwise.

Such behaviors can be easily implemented by moving the javascript-dependant CSS rules to a specific stylesheet that cannot be activated without javascript.

For instance,

default.css
.expanded { display: block; }
.collapsed { }

jsonly.css
.collapsed { display: none; }

The idea is too use a technique similar to some stylesheet switching scripts. The js only stylesheet will first be loaded as an alternate stylesheet, while the default stylesheet is loaded normaly.

<link href="default.css" rel="stylesheet" type="text/css" />
<link href="jsonly.css" rel="alternate stylesheet" type="text/css" title="this stylesheet is activated by javascript" />

The alternate stylesheet is safely ignored by the browser, until the following script, if allowed to run, enables it.

function activateStylesheet(sheetref) {
     if(document.getElementsByTagName) {
        var ss=document.getElementsByTagName('link');
     } else if (document.styleSheets) {
        var ss = document.styleSheets;
     }
     for(var i=0;ss[i];i++ ) {
          if(ss[i].href.indexOf(sheetref) != -1) {
          ss[i].disabled = true;
          ss[i].disabled = false;
          }
     }
}
activateStylesheet('jsonly.js');

This function should be called from your onload event handler, or in any case, after the links to the stylesheets. It basically enumerates the stylesheet collection, looking for the one named after the given parameters and then enables it. It might look a bit silly to do disabled = true before doing disabled = false, but it is necessary in order for the disabled property to work correctly in Internet Explorer.

This method was tested in IE5.5+, Safari, Firefox, Netscape 7+ and Opera 7.5.

One Response to “Javascript Enabled Stylesheets”

  1. Get Into This » The Form Assembly » Blog Archive » Javascript Enabled Stylesheets Says:

    […] ty and want to have more control over your page w/o javascript, then check out this link: The Form Assembly » Blog Archive » Javascript Enabled Stylesheets It shows you how to include a certain sty […]