Home › Forums › JavaScript › Any Cross-browser JS code that can swap CSS Stylesheets by onClick? › Re: Any Cross-browser JS code that can swap CSS Stylesheets by onClick?
June 23, 2012 at 11:20 pm
#104810
Member
I’ve used a version of this theme switcher forever. Instead of disabling the stylesheet as you have above, it just disables the link, it works very nicely.
Actually, the one of dynamic drive is really messy… this is the version that I used in the past, now I just use jQuery to disable the link.
Set up the links like this:
And the script:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca;
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) {
a.disabled = false;
createCookie("style", title, 365);
}
}
}
}
function setPassiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")); i++) {
if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}
Note: The setPassiveStylesheet function is run on page load, then the setActiveStyleSheet function is used to change themes. The title is just the title of the theme contained within the link.