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.
jQuery Plugin
I’ve created a simple jQuery plugin for adding or switching out stylesheets dynamically and interactively and it can be used like this:
HTML
<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>
jQuery hookup
$('a').click(function () {
$.stylesheets.clear().add($(this).attr('rel'));
return false;
});
jQuery Plugin
$.stylesheets = (function () {
var stylesheets,
add,
clear;
add = function (cssfile) {
$('head').append(''" rel="stylesheet" />');
return stylesheets;
};
clear = function () {
$('head link[rel=stylesheet]').remove();
return stylesheets;
};
return stylesheets = {
add: add,
clear: clear
};
} ());
Download source / demo