Thursday, 31 Jan 2008 7:55AM EST
Swapping CSS Files with JavaScript
If you’re building a web application with user accounts, profile pages or any type of customized pages, you'll probably want to offer your users the option of changing their theme. The simplest way to accomplish this is to build multiple CSS files and allow your users to change their preferred style with the click of a button. All you need is a button that will swap the CSS files with a single click. Of course you'll want to get a bit more involved and store the users preferred theme in a database or a cookie. In this tutorial, I'll be showing you how to do the latter.The HTML is very simple. All you need is a link or button which calls the swapCSS function for each style option and a call to loadCSS in the body onload property of your page.
<body onload="javascript:loadCSS();">
<input type="button" value="Black on Gray" onclick="javascript:swapCSS('bog');" />
<input type="button" value="Green on Black" onclick="javascript:swapCSS('gob');" />
</body>
function swapCSS(choice) {
var styleId = document.getElementById("globalStyle");
if(choice == "gob") {
styleId.href = "black_with_green.css";
setCookie('style','black_with_green.css',90);
} else if(choice == "bog") {
styleId.href = "gray_with_black.css";
setCookie('style','gray_with_black.css',90);
}
}
function loadCSS() {
var styleId = document.getElementById("globalStyle");
if(cookieValue('style')) {
styleId.href = cookieValue('style');
}
}
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expire = "; expires=" + date.toGMTString();
}
else var expire = "";
document.cookie = name + "=" + value + expire + "; path=/";
}
function cookieValue(name) {
var name = name + "=";
var allcookies = document.cookie.split(';');
for(var i=0;i < allcookies.length;i++) {
var cookie = allcookies[i];
while (cookie.charAt(0)==' ') cookie = cookie.substring(1,cookie.length);
if (cookie.indexOf(name) == 0) return cookie.substring(name.length,cookie.length);
}
return null;
}
That's all there is to it. A simple javascript function to swap CSS files and store the users preference in a cookie. As always, if you have a technique that you think is better or a tweak that improves on this code, please share it in the comments. If you have a tip, a trick or an idea for my next post, please don't hesitate to contact me.
















0 Comments So Far