Skip to content Skip to sidebar Skip to footer

Enable Disable Stylesheet Using Javascript In Chrome

Rephrase of question: What is the best way to provide alternate stylesheets for a document? I have a list of stylesheets, all of which are referenced in the html file. I use javas

Solution 1:

In general you'd subclass off the BODY tag and use a single stylesheet that uses these classes. Then just swap the BODY class, not the sylesheet. Otherwise, you should be doing this server-side.

<body class="sheet1">

then

sheet1.h1 {
 ...
}
sheet2.h1 {
 ...
}

Solution 2:

If you know the order of your stylesheets you can use-

document.styleSheets[i].disabled=true or
document.styleSheets[i].disabled=false;

If you have 2 stylesheets you can toggle between them with-

var S=document.styleSheets;
if(S[0].disabled){
  S[0].disabled=false;
  S[1].disabled=true;
}
else{
  S[1].disabled=false;
  S[0].disabled=true;
}

Solution 3:

Current browsers offer reasonable ability to dynamically enable/disable stylesheets through the use of either the 'disabled' DOM property (Gecko) or by adding/removing the disabled attribute (Webkit and IE). Unfortunately, these approaches only reliably work on 'link' tags that reference an external stylesheet (not 'style' tags), unless you are using IE10+. Yes - I said that - only IE does the right thing here.

For inline CSS using 'style' tags on non-IE browsers, you need to find a more crude way to enable/disable like those discussed above (remove the style element, etc).


Solution 4:

I was able to get this to work with setting the disabled property and by including a 'title' attribute the stylesheets. title property makes the stylesheet PREFERRED rather than PERSISTENT. see http://www.alistapart.com/articles/alternate/


Solution 5:

I've found a great way (IMHO) to achieve this:

Let's suppose you know the exactly order of your stylesheet. Let's say you want to alternate stylesheet 0 and 1 (first and second):

To get a stylesheet state (enabled/disabled) you can try this (i.e. testing the second one):

document.styleSheets[1].disabled

...and it returns trueor false.

So to alternate you can write this code in an onclick event:

document.styleSheets[0].disabled = !( document.styleSheets[1].disabled = !(document.styleSheets[1].disabled) );

HTH!


Post a Comment for "Enable Disable Stylesheet Using Javascript In Chrome"