Inspecting the source code and how it changes as you change themes, it is really quite simple. Digg is harnessing the awesomeness of CSS to drastically change content by simply changing the class of an element. All you have to do is this:
<div id="theme_viewer">
<!-- HTML code for your widget/thing to be styled -->
</div>
And then you can have your themes:
<ul>
<li><a href="#" onclick="return switchTheme('theme1');">theme 1</a></li>
<li><a href="#" onclick="return switchTheme('theme2');">theme 2</a></li>
<li><a href="#" onclick="return switchTheme('theme3');">theme 3</a></li>
<li><a href="#" onclick="return switchTheme('theme4');">theme 4</a></li>
</ul>
All switchTheme
needs to then do is change the class of theme_viewer
to the class passed:
function switchTheme(theclass) {
var viewer = document.getElementById('theme_viewer');
viewer.className = theclass;
return false;
}
Your CSS stylesheets can then do whatever the different styles call for:
#theme_viewer.theme1 {
background-color: red;
}
#theme_viewer.theme2 {
background-color: blue;
}
#theme_viewer.theme3 {
background-color: black;
color: white;
}
#theme_viewer.theme4 {
background-color: orange;
}
here is an example of this at work
As mentioned in the comments by J-P and in edeverett's answer, it is not a good idea to have your events inline as I have them in this example (ie, with the onclick
attribute). I did it for simplicity, but it's not a good idea. The better idea is to wait for your document to load and attach the event handlers dynamically with Javascript. This is known as unobtrusive Javascript, and it is a Good ThingTM.
An example of the above example following good practices would look like this:
<ul id='theme_options'>
<li><a href="#" id='theme1'>theme 1</a></li>
<li><a href="#" id='theme2'>theme 2</a></li>
<li><a href="#" id='theme3'>theme 3</a></li>
<li><a href="#" id='theme4'>theme 4</a></li>
</ul>
And then we use this cross browser addEvent function (written by John Resig, author of jQuery):
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent( 'on'+type, obj[type+fn] );
} else
obj.addEventListener( type, fn, false );
}
To add the event handlers:
addEvent(window, 'load', function() {
var opts = document.getElementById('theme_options');
var links = opts.getElementsByTagName('a');
for(var x = 0; x < links.length; x++) {
addEvent(links[x], 'click', function() {
switchTheme(links[x].id);
});
}
});
It might be a little more verbose than inline Javascript, but it is worth it. I know you said you'd like to avoid jQuery, but something as simple as this makes you start appreciating the library, as you could do it with jQuery with something as simple as this:
$(function() {
$('a','#theme_options').click(function() {
switchTheme($(this).attr('id'));
return false;
});
});