Javascript - Style Switching

The style switcher is a way of showing how to use alternate style sheets in a browser. The documents in this site are as semantically harmonious as the documents in the tutorial. Clicking the 'Tutorial Tones' link in the style switcher bar above uses a clever piece of Javascript to make the page use a different style sheet to the one you are presently viewing it with. Style switching like this has no real function here other than to illustrate the power of CSS and the flexibility that the ironically rigidly coded XHTML provides.

For the purpose of this demonstration we will assume tht you ahve two style sheets style1.css and style2.css Note the addition of the word alternate to the second style sheet rel attribute value and the addition of a title attribute in each case.

<link href="style1.css" rel="stylesheet" type="text/css" title="Style1" /> <link href="style2.css" rel="alternate stylesheet" type="text/css" title="Style2" />

Add this line into the <head></head section of your document, this is the method of linking a file containing Javascript code to a document, similar to the <link> tag for style sheets.

<script type="text/javascript" src="the.js"></script>

Create a new text file, rename it the.js, open it in a text editor and paste this code into it and save it.

function switchToCSSFile(sty) { sty=(sty)?sty:this.getAttribute('title'); var l=document.getElementsByTagName("link"); for(i=0;i< l.length; i++) { if(l[i].getAttribute("rel").indexOf("style") != -1 && l[i].getAttribute("title")) { l[i].disabled = true; if(l[i].getAttribute("title") == sty) { l[i].disabled = false; } } } }

Without going into detail about how the Javascript programming language works, this piece of code searches for <link> tags in the XHTML, to find style sheets to switch between and then switches to the chosen style defined by the value of the title attribute in the link tag. The Javascript function is triggered by something called an 'event' the event to be used is the click of the mouse on a link. To add this code to a link so it is triggered use the onclick attribute, and make the value the name of the Javascript function and include the relevant title attribute value for the style sheet to switch to when the link is clicked.

<a href="#" title="Style1" onclick="switchToCSSFile('Style1');">Style1</a> <a href="#" title="Style2" onclick="switchToCSSFile('Style2');">Style2</a>

I hope you found this paper interesting and informative and if you have never built a web page before I hope you will give it a try. There is mor to learn and plenty of places like this on the Internet to visit and learn the next steps. I may even write a full set of tutorials myself one day...

Technohippy

Style Switcher: one document many styles

Valid XHTML 1.1Valid CSS!