The first time I saw a style sheet switcher I was either reading A List Apart or Simple Bits, both excellent sites you should visit if you are serious about design.
Since then, I’ve seen many different methods for allowing a visitor to switch a stylesheet with a click of a mouse. But recently I came across a short example of how to do it with jQuery.
I want to show you this example and walk you through it because it not only gives another fine example of the short code you can write with jQuery but also too illustrate some of the more advanced features of the jQuery javascript library.
$(document).ready(function()
{
$('.styleswitch').click(function()
{
switchStylestyle(this.getAttribute("rel"));
return false;
});
var c = readCookie('style');
if (c) switchStylestyle(c);
});
function switchStylestyle(styleName)
{
$('link[@rel*=style]').each(function(i)
{
this.disabled = true;
if (this.getAttribute('title') == styleName) this.disabled = false;
});
createCookie('style', styleName, 365);
}
What I’ve left out of the demonstration are the functions you’ll see later for creating and reading the cookies.
$(document).ready(function()
{
$('.styleswitch').click(function()
The beginning of the code tells jQuery “As soon as possible, get all elements with the class name of styleswitch and fire off a function when the element is clicked”.
So far so good.
When these chosen elements are clicked the switchStylestyle function will be called. So that’s where we turn our attention next.
The first time I really looked closely at this I was stumped:
$('link[@rel*=style]').each(function(i)
{
After searching the web and coming up empty handed I contacted John Resig, the creator of jQuery, and asked him for some hints.
He directed me to some pages on the jQuery site that explain some of the more advanced ways that jQuery can be used to find and manipulate elements on a page.
If you read the short explanations and examples here you’ll soon see that this mysterious line of code tells jQuery “Find all link elements with a rel attribute containing the string ‘style’”.
Huh?
Let’s look at how we would create a page with one main stylesheet and two alternate ones:
<link rel="stylesheet" type="text/css" href="styles1.css" title="styles1" media="screen" /> <link rel="alternate stylesheet" type="text/css" href="styles2.css" title="styles2" media="screen" /> <link rel="alternate stylesheet" type="text/css" href="styles3.css" title="styles3" media="screen" />
Notice how all of the links to the stylesheets have a rel attribute with “style” somewhere between the quotation marks.
So, in short, this code is telling jQuery to target all of the stylesheet links in the page.
The each() function loops through each of the stylesheet links and performs the operations spelled out in the next few lines of code:
this.disabled = true;
if (this.getAttribute('title') == styleName) this.disabled = false;
“Disable every stylesheet link but then un-disable any link where the “title” attribute is the same as the value passed to the switchStylestyle function”
That’s a mouthful too, but it’s really not that tough.
What we’re doing is matching the rel attribute of the links on our page (the clickable links for switching the stylesheets) with the title attribute of the stylesheets (and alternates) available to us.
When one of the clickable links is clicked, a function is called, which finds all the stylesheets, disables all of them, and then turns one back on… the one where the title of the stylesheet link matches the rel attribute of the link clicked.
Whew!
Since Kelvin Luck already created the code, no need for me to replicate it here.
Code – I won’t link directly to the zip, since that’s sometimes seen as rude. Go to this page and at the bottom is a link to the zip.
I believe ol’ Kelvin got his inspiration from this site where you’ll see that to do this without jQuery is a little bit more complicated and you don’t get all the benefits of Kelvin’s code – namely the long term memory of stylesheet chosen.
[tags]jQuery, javascript, DOM, cookie, stylesheet, css, alternate stylesheets[/tags]
39 Responses
Sam
June 18th, 2006 at 6:51 pm
1Thanks for taking time to post these examples. Here’s my 2-cents on further code reduction:
Replace
this.disabled = true;
if (this.getAttribute(‘title’) == styleName) this.disabled = false;
With
this.disabled = this.getAttribute(‘title’) != styleName;
v
June 19th, 2006 at 7:53 pm
2Doesn’t work in Safari.
joon
October 23rd, 2006 at 11:30 am
3Is $(document).ready(function().. absolutely necessary in this case? In Safari the default style sheet is rendered for a split second then the chosen style is loaded on each page load.
If it’s possible, let the browser execute as it’s being read. Me (big noob) has to test it out.
Thanks for the tutorials.!
nic
April 3rd, 2007 at 7:50 pm
4How would you modify this code to load a specific style sheet based on an attribute in the ? I’ve been mucking around in the code and I’ve gotten totally confused.
Thanks for all the tutorials, you’ve gotten me hooked on jquery.
nic
April 3rd, 2007 at 7:51 pm
5it’s supposed to say… based on an attribute in the body tag.
Jack
April 4th, 2007 at 11:49 am
6Should be easy enough, just grab the class or attribute of the body tag, and pop that into the mix.
This is an untested quickie based on an id:
$(‘body’).each(function(){
switchStylestyle(this.id);
});
But I also think that you can perform the same or similar without the use of javascript by putting a class name and/or id in the body tag of your document, and then putting the appropriate rules in your css
body#one p { color: black; }
body#two p { color: red;}
nic
April 4th, 2007 at 7:32 pm
7Jack,
Thanks for the example, that’s exactly what I needed.
I’ve been doing the tutorials on jQuery and I literally know 200% more than when I wrote that first question. The problem I’m trying to solve is that we want to have an individual style for multiple users on the same set of pages.
For example two people visit page Cranberry, if user A came from page Apple they would have the Apple style loaded, and if user B came from page Banana they would have the Banana style loaded.
If someone visited Cranberry straight up they would see the default theme.
We already had this system in place using an onLoad script, but I wanted to switch over to jQuery.
Mike
April 26th, 2007 at 12:42 pm
8Oops, forgot to mention one thing. In the line that generates the random number:
var randNum = Math.floor(Math.random() * 4);
Change the number you are multiplying by, in this case 4, to the number of alternate stylesheets you have listed, or one more than the last ‘title’ number. In my case I have 4 alternate stylesheets numbered 0 through 3, so I multiply by 4.
Aleksey
May 30th, 2008 at 8:59 am
9It’s all based on an attribute in the body tag…
buy valium onli
August 18th, 2008 at 7:12 pm
10Hi webmaster!
Dave Artz
September 8th, 2008 at 4:34 pm
11Unfortunately, this approach means downloading all the alternate stylesheets even if they are never used. For performance-conscious sites with many skins, this is an issue.
The best cross-browser approach I’ve found so far for theme switching is to AJAX in styles and swap out the old CSS once they are completely downloaded and save the cookie for the next load of the page.
Sean
January 15th, 2009 at 4:42 pm
12I have a very irritating problem, I cannot add a ‘title’ attribute to a . When I do, the stylesheet isn’t loaded at all. I have tried switchin doctypes, checked the validator, but not luck
Any idea what it could be?
40+ Excellent jQuery Tutorials | instantShift
February 9th, 2009 at 2:54 pm
13[...] Tutorial Link: Click Here [...]
40?????jQuery???? - Code Index
February 23rd, 2009 at 4:07 am
14[...] Tutorial Link: Click Here [...]
30 excellentes ressources pour développer avec jQuery
March 3rd, 2009 at 9:01 am
15[...] exemple de code pour changer la feuille de style [...]
Dan Sorensen
March 4th, 2009 at 5:50 pm
16Just a quick update to say that jQuery 1.3 doesn’t support the @ sign in the attribute. To make this code work properly, just remove the @ sign. See this page for more details:
http://docs.jquery.com/Selectors
Anthony Alexander
May 4th, 2009 at 1:27 am
17Asynchronous Javascript functions became AJAX, All javascript became Jquery, now John Resig invented CSS selectors too.
pligg.com
July 18th, 2009 at 2:31 am
18Style Sheet Switcheroo…
allow visitors to switch a stylesheet with a click of a mouse.
This not only gives another fine example of the short code you can write with jQuery but also too illustrate some of the more advanced features of the jQuery javascript library….
shengmx
January 5th, 2010 at 2:48 am
19agree idea said by Dan Sorensen at 16th floor
40+ Excellent jQuery Tutorials « PSD to HTML , Slicing PSD to HTML
January 10th, 2010 at 3:10 pm
20[...] Tutorial Link Demo Link [...]
Li
January 22nd, 2010 at 4:59 am
21Thanks!
???????
10 jQuery Resources | Brightscape Blog
February 4th, 2010 at 5:56 am
22[...] CSS Switcher [...]
40??jquery?? | QK31
February 23rd, 2010 at 12:36 pm
23[...] Tutorial Link Demo Link [...]
PHP-help » Excellent jQuery Tutorials
March 8th, 2010 at 8:12 am
24[...] Tutorial Link Demo Link [...]
Aman
August 18th, 2010 at 12:49 pm
25Hi
I like this plugin.I have Also 10+ Jquery Style Switchers plugins please see:-
http://jquery13.blogspot.com/2010/08/10-jquery-style-switchers.html
Thanks
Aman
links for 2010-10-15 - Craig's Blog
October 15th, 2010 at 2:03 pm
26[...] Using jQuery Iframe height sizing js (tags: jquery iframe javascript resize resizing development) Style Sheet Switcheroo by 15 Days Of jQuery Font resizer js (tags: jquery css javascript howto switch switcher js font resizer) Published [...]
10+ jQuery Excellent Tutorials | jQuery4u
February 8th, 2011 at 9:59 am
27[...] [...]
46 Excellent jQuery Tutorials For Web Developers | stylishwebdesigner
February 15th, 2011 at 2:51 am
28[...] 36. Style Sheet Switcheroo [...]
Late Night Stop 45 Great JQuery Tutorials !
March 16th, 2011 at 6:44 pm
29[...] Tutorial Link Demo Link [...]
Monique Sanchz
March 18th, 2011 at 12:26 pm
30As being a Newbie, I am always looking on the net for content articles that may help me. Thank you
to do | tallphil.co.uk
March 27th, 2011 at 1:33 pm
31[...] system – write in photo system (http://www.jupload.biz/) – write different styles to choose from (help) – write toy to create your own style? – finish social bookmarking links (ideas) and make share by [...]
konut projeleri
August 1st, 2011 at 7:37 am
32Thanks for the tutorials.!
Lenny Breau
August 19th, 2011 at 1:13 pm
33This doesn’t work in Safari 5.1. There is an issue use relative stylesheet in Safari.
100+ Excellentes Recursos jQuery | zebit | Chile
September 9th, 2011 at 9:14 pm
34[...] Style Sheet Switcheroo [...]
40+ Excellent jQuery Tutorials « RPL Class
October 2nd, 2011 at 9:58 pm
35[...] Tutorial Link Demo Link [...]
baskaran
October 15th, 2011 at 1:48 am
36Its fine, but i want to execute two alternate style sheet at a same time. Please give your idea
Robert
January 18th, 2012 at 10:20 am
37I use 4 variations of column styles in my website.
How can I use this script to change stylesheets based on a tag id such as body or div when the page is loaded.
Example <body id=1column or id=2column etc. or <div id=1column or id=2column.
Thanks
Theo Kingsbury
January 19th, 2012 at 6:04 am
38Hey very nice blog!! Man .. Excellent .. Amazing .. I will bookmark your website and take the feeds also…I am happy to find numerous useful information here in the post, we need work out more strategies in this regard, thanks for sharing. . . . . .
Victor Prince
January 31st, 2012 at 2:22 am
39I conceive this site has got some real fantastic information for everyone
. “Time–our youth–it never really goes, does it It is all held in our minds.” by Helen Hoover Santmyer.
RSS feed for comments on this post · TrackBack URI
Leave a reply
Categories
Archives
Links
15 Days Of jQuery is proudly powered by WordPress - BloggingPro theme by: Design Disease