Rickard Nilsson is a software architect, developer, craftsman, agile enthusiast, and father of three... More
Rickard blogs about crafting software using .NET tooling and solid, development practices.
It has been almost three years since I wrote my top ranking post on this blog: Applying stylesheets dynamically with jQuery. It was a quick and dirty example of a testing scenario pulled together for a colleague but it has become my number one linked post. It is still the post that gets the most hits every month because it is the first hit on Google for jquery add stylesheet which seems to be a lot of people has trouble with.
So, I felt it was time to do another post on the subject considering I’ve been using jQuery more or less every day these last three years.
I’ve created a simple jQuery plugin for adding or switching out stylesheets dynamically and interactively and it can be used like this:
<ul>
<li><a href="#" rel="1.css">Apply Stylesheet 1a>li>
<li><a href="#" rel="2.css">Apply Stylesheet 2a>li>
<li><a href="#" rel="3.css">Apply Stylesheet 3a>li>
ul>
$('a').click(function () {
$.stylesheets.clear().add($(this).attr('rel'));
return false;
});
$.stylesheets = (function () {
var stylesheets,
add,
clear;
add = function (cssfile) {
$('head').append(''" rel="stylesheet" />');
return stylesheets;
};
clear = function () {
$('head link[rel=stylesheet]').remove();
return stylesheets = {
add: add,
clear: clear
} ());
Download source / demo
Related posts
Comments
May 20. 2011 09:47
Applying stylesheets dynamically with jQuery Applying stylesheets dynamically with jQuery
Rickard Nilsson