CSS Stylesheet Switcher Widget

This snippet of code can be modified and used to change the stylesheet on your page. I set it up to work against a layout extracted from Salsa, but it should work on generic pages. It’s good for demos, discussions about a layout, trying different colors, etc.

You need to alter a few things – specifically the line:

if (href.match(/^index_files/p-[0-9].css$/)) {

Change the regex to work with your directory structure.

Then down in the HTML part, the values of the options must be paths to CSS files.

And, of course, the CSS files must exist, and be named like p-1.css, p-2.css, p-3.css, etc.

<!-- stylesheet switche -->
<script type='text/javascript'>
    function loadCss( target ) {
        var href;
        var link; 
        var cssindex = target.options.selectedIndex;
        var file = target[cssindex].value;
        var links = document.getElementsByTagName("link");
        for(var i=0; i<links.length; i++) {
            link = links[i];
            href = link.getAttribute("href");   
            if (href.match(/^index_files/p-[0-9].css$/)) {
                var newlink = document.createElement("link");
                newlink.setAttribute("rel", "stylesheet");
                newlink.setAttribute("type", "text/css");
                newlink.setAttribute("href", file);
                link.parentElement.replaceChild( newlink, link );
            }
        }

    }
</script>
<form id="css-switcher" style="display: block; width: 250px; position: fixed; top: 0px; left: 0px;">
    <select name="cssfile" onchange="loadCss(this);">
        <option value="index_files/p-1.css">Layout 1 - p-1.css
        <option value="index_files/p-2.css">Layout 2 - p-2.css
        <option value="index_files/p-3.css">Layout 3 - p-3.css
        <option value="index_files/p-4.css">Layout 4 - p-4.css
        <option value="index_files/p-5.css">Layout 5 - p-5.css
    </select>
</form>
<!-- end stylesheet switcher -->