1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Stylesheet Switcher

Stylesheet switchers allow you to define several different stylesheets that define how your page should appear and allow your visitors to then choose which of the stylesheets to use depending on which style that the individual visitors prefer. For example you might have stylesheets that will present your page content with different colour backgrounds, different fonts, different font sizes, and even completely different page layouts and allow your visitors to switch to whichever of these stylesheets best suits the way that they prefer to view your content.

The first step in adding a stylesheet switcher to your web page is to define the alternate stylesheets that you want to be able to switch between. You link them all into the head of your page like this:

<link href="/css/main.css" rel="stylesheet"
type="text/css" title="main" media="screen" />
<link href="/css/alt1.css" rel="alternate stylesheet"
type="text/css" title="alt1" media="screen" />
<link href="/css/alt2.css" rel="alternate stylesheet"
type="text/css" title="alt2" media="screen" />

Note that the stylesheet that we want to use first (main) is defined the regular way (apart from making sure that it has a title) while the alternative stylesheets that we want to be able to switch to are defined as alternates (and also have titles). The reason for giving a title to each of the stylesheets is that we are going to use those titles in the Javascript to determine which stylesheet we want to use.

Here's the javascript function that we need to add to the head of our page in order to be able to switch stylesheets:

function changeStyle(title) {
var lnks = document.getElementsByTagName('link');
for (var i = lnks.length - 1; i >= 0; i--) {
if (lnks[i].getAttribute('rel').indexOf('style')> -1 && lnks[i].getAttribute('title')) {
lnks[i].disabled = true;
if (lnks[i].getAttribute('title') == title) lnks[i].disabled = false;

Now a simply call that function specifying the title of the stylesheet that should be active eg. changeStyle('alt2'); is all that needs to be added to whatever code you are using that you want to handle the stylesheet switching. For example you could add it to the onclick event handler associated with some text on your page like this:

<span onclick="changeStyle('alt2')">Switch to second alternative stylesheet</span>
See More About

©2017 About.com. All rights reserved.