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>
The swapCSS function takes a single parameter; choice. This is an arbitrary value to distinguish between the style choices. In this example, I use "gob" to stand for green text on a black background, and "bog" to stand for black text on a gray background. The function first gets your style element, in this case "globalStyle", sets href value of that element to change the current CSS, and stores the name of the preferred stylesheet in a cookie.
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);
  }
}
The loadCSS function, called when the page is first loaded, checks to see if a cookie has previously been set with the users preferred style. If so, that current stylesheet is set to the value of that cookie.
function loadCSS() {
  var styleId = document.getElementById("globalStyle");
  if(cookieValue('style')) {
    styleId.href = cookieValue('style');
  }
}
Finally, we have the cookie functions; setCookie and cookieValue. setCookie takes 3 parameters; name, a string that will be used to identify the cookies, value, the name of the stylesheet, and days, the number of days before your cookie will expire. The function checks to see if days has been specified and uses document.cookies to create the cookie.
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=/";
}
cookieValue checks to see if a specified cookies exists, and if so, it returns to value of that cookie.
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;
}
View a live demo »

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.

Bookmark and Share

0 Comments So Far

Post a comment


If you are seeing this message, you are either using a screen reader or you have disabled CSS. Please do not fill in the following form field, titled "lastname", or your comment will not be saved. This field is only used to help prevent spam comments.


Welcome

JustinSpegele.com is where I share projects that I'm working on, php tutorials, web development tips and tricks, and random thoughts.

#MLS has a very odd notion of an all-star game. MLS all-stars vs. an EPL team? Still, should be very fun to watch. MLS 3 - Man United 2 1:41 PM Jul 28th from web
The New Digg And The Future Of Social News http://bit.ly/cM7Guq 10:44 AM Jun 29th from TweetMeme
so as of right now, the Big 10 has 12 teams and the Big 12 has 10 teams? http://sports.espn.go.com/ncaa/news/story?id=5276668 7:59 PM Jun 11th from web
heading to Las Vegas for #caworld in the morning 7:12 PM May 12th from web
Found out from CNN that I went to high school with a convicted terrorist who worked with Al-Qaeda. Not what I expected to see on the news 9:49 PM May 10th from web
View all posts on Twitter »

Friend me

Twitter Digg Facebook FriendFeed Del.icio.us iFanboy Last.fm Squidoo

Login

Username:

Password: