Search code examples
javascriptstylesheet

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 javascript to disable all but one file.

example:

style1   disabled = false
style2   disabled = true

In practice, the last stylesheet to load (style2) is the active one, regardless of the disabled property.

How can I alternate between stylesheets on a document in chrome?

I tried to set the value of href attribute, but it seems to be read only.

example of code I have been using: (I am using an object called MenuStyles that is storing various css information)

function setActiveStyleSheet(name) {

    var selectedSheet;
    var currentSheet;
    for (var i = 0; i < MenuStyles.styleSheets.length; i++) {
        currentSheet = MenuStyles.styleSheets[i];
        if (currentSheet.name === name) {
            selectedSheet = currentSheet.sheetObj;
            currentSheet.disabled = false;
        } else {
            currentSheet.disabled = true;
        }
    }
    return selectedSheet;
}

EDIT: it turns out the problem was due entirely to bugs in the code. disabled property works fine. below is the fixed function:

function setActiveStyleSheet(name) {
    var selectedSheet;
    var currentSheet;
    for (var i = 0; i < MenuStyles.styleSheets.length; i++) {
        currentSheet = MenuStyles.styleSheets[i];
        if (currentSheet.name === name) {
            selectedSheet = currentSheet.sheetObj;
            currentSheet.sheetObj.disabled = false;
        } else {
            currentSheet.sheetObj.disabled = true;
        }
    }
    return selectedSheet;
}

Solution

  • 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/