I want to change styles with JavaScript, but I would prefer that the styles be written in CSS in a style sheet for organization reasons. I know I can invoke an alternate stylesheet with JS:
but there might be many of these alternatives and I'd prefer all CSS was in a single file (for performance). Just as you can have many blocks of styles (in same file) activated by media queries, I'd like to have in a single file many blocks of styles that can be triggered by JavaScript.
in javascript, toggle between modes using classes:
Code:
//enter setup mode:
function enterSetup(){
document.title="Game Config";
document.body.classList.add("setup");
}
//leave setup mode
function saveSettings(){
// saving setup form ...
document.body.classList.remove("setup");
document.title="Game On!";
}
of course, all the nouns in the above example are madeup, but this is the principle.
you can add several classes, so in CSS you can make pools of settings depending on the "mode" of your app.
these can be independently selected, so you can have something like "setup largePrint ie widscreen" as body classes, and targeted CSS that does the right thing in each case.
this puts all the power in CSS, no more element.style.xxx...
there is also document.styleSheets, and styleSheet.disabled, which does what it sounds like, but i have given up using those because they are too complicated.
the two big issues with that approach are that some styleSheets import other styleSheets which means you have to iterate though and look at the rules of each stylesheet to look for imports, and secondly that process is complicated because some sheets come from off-site, and trying to read those will throw an exception and halt all your code, so you can only iterate on-site recursively-defined rules.
partial iteration sucks, just use classes and save yourself a lot of headaches.
you will have more customization options and expandable code in the end, while lowering the editing threshold to css skills instead of js skills.
I wouldn't mind putting the CSS chunks in separate files - that's conceptually clean enough for me. But having numerous small CSS files dynamically loaded brings a performance issue I want to avoid.
Bookmarks