demosthenes.info

I’m Dudley Storey, the author of Pro CSS3 Animation. This is my blog, where I talk about web design and development with , and . To receive more information, including news, updates, and tips, you should follow me on Twitter or add me on Google+.

web developer guide

my books

Book cover of Pro CSS3 AnimationPro CSS3 Animation, Apress, 2013

my projects

CSSslidy: an auto-generated #RWD image slider. 3.8K of JS, no JQuery. Drop in images, add a line of CSS. Done.

tipster.ioAutomatically provides local tipping customs and percentages for services anywhere.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Dynamically Preview Custom Site Themes With jQuery

javascript / navigation

Estimated reading time: 2 minutes, 18 seconds

This article was prompted by a question from one of my evening class students: rather than the user clicking on links and letting PHP dynamically load a new stylesheet to respond to user preferences, was it possible to preview site styles on hover, without touching PHP?

The answer is yes: as we’ve seen, JavaScript can dynamically alter the CSS of any element; this goes all the way up to loading a new stylesheet for the entire document. (In the example used for this article, I’ve restricted the CSS changes to just the header.)

Why would you want to do such a thing? For several reasons: the obvious purpose is to let users see a series of themes for a web site without needing to click or reload. Another possibility is a desire to change the CSS for the page on the fly, without needing any user interaction at all. (For example, changing the theme of the site based on the time or season).

The setup is pretty simple. First, we need to make the stylesheets: theme1.css, theme2.css and theme3.css. In each stylesheet,write the CSS that you want to apply for that theme. I would also write a base.css stylesheet that would contain styles that were consistent between all the pages for the entire site, such as reset rules.

So the head of the document would look like this:

<head>
<title>Dynamic Stylesheet Preview</title>
<link rel=stylesheet href=base.css>
<script src=//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js>
</script>
<script>
/* our script will go here */
</script>
</head>

And our CSS; theme1.css, in this case:

body { background-image: url(moonrise.jpg); }
/* the rest of the unique CSS for this theme goes here */

We’ll also make theme2.css and theme3.css.

(Photographs are supplied by Spreng Ben, HessieBell and Tom Raftery, liscensed under Creative Commons.

Then, the markup. I’ll use three links that, when clicked, will set the user’s theme preference for the site via the PHP method I have written about earlier:

<a href="themeset.php?theme=1" id="theme1">1</a>
<a href="themeset.php?theme=2" id="theme2">2</a>
<a href="themeset.php?theme=3" id="theme3">3</a>

These links will also initiate the stylesheet preview when they are hovered over.

Finally, the JQuery:

$(document).ready(function () {
    $("a#theme1").hover(function () {
        $('head').append('<link rel=stylesheet href=theme1.css>');
    });
   $("a#theme2").hover(function () {
        $('head').append('<link rel=stylesheet href=theme2.css>');
    });
   $("a#theme3").hover(function () {
        $('head').append('<link rel=stylesheet href=theme3.css>');
    });
});

As you can see, there is a lot of repetition here. While this script works, there is a better and more efficient way. First, we’ll change the initiating event. All of the id values of our links begin with "theme". So we can use the JQuery "starts with" attribute selector:

$('a[id^="theme"]').hover(function () {

Each link has the same value for id as the name of the stylesheet that it matches. So we can concentrate the id value of the link with the required text to get our stylesheet file name:

$('head').append('<link rel=stylesheet href='+$(this).attr("id")+'.css>');

The new script in its entirety:

<script>
$(document).ready(function () {
    $('a[id^="theme"]').hover(function () {
$('head').append('<link rel=stylesheet href='+$(this).attr("id")+'.css>');
    });
});
</script>
comments powered by Disqus

This site helps millions of visitors while remaining ad-free. For less than the price of a cup of coffee, you can help pay for bandwidth and server costs while encouraging further articles.