Skip to main content

JavaScript to Swap CSS on XHTML Strict Webpage

Please note these forums are being decommissioned and use the new and improved forums at
No replies
Joined: 2013-04-07

Over Easter I was set a task by the HTML sub-module of the Computer Science degree I am doing. Basically, it was to do a critique of an infographic and then present that in the form of two webpages. These webpages both have to have three different style sheets assigned to them (the same three being on both.) And we have been told the user should be able to swap between each of the three in realtime. We have been provided with a javascript program to allow this (since we haven't started learning java yet,) however we have not really been told how to implement the change in the XHTML Strict code.

The following is the javascript code (stylesheets.js) that was provided:

                function setActiveStyle (styletitle) {<br />
			var stylelist = document.getElementsByTagName("link");<br />
			for (i = 0; i < stylelist.length; i++) {<br />
				if (isOptionalStylesheet(stylelist[i])) {<br />
					activateWhenMatching(stylelist[i], styletitle);<br />
				}<br />
			}<br />
<p>		function isOptionalStylesheet(thislink) {<br />
			return (thislink.getAttribute("rel").indexOf("style") != -1) && thislink.getAttribute("title")<br />
<p>		function activateWhenMatching(thislink, styletitle) {<br />
			if (thislink.getAttribute("title") == styletitle) {<br />
				thislink.disabled = false;<br />
			}<br />
			else {<br />
				thislink.disabled = true;<br />
			}<br />
<p>		function chooseStyleBySize() {<br />
			var theWidth = document.documentElement.clientWidth;<br />
			if (theWidth < 800) {<br />
				theSheet = "smallsheet";<br />
			}<br />
			else if (theWidth < 900) {<br />
				theSheet = "mediumsheet";<br />
			}<br />
			else {<br />
				theSheet = "bigsheet";<br />
			}<br />
			setActiveStyle(theSheet);<br />

So far, I've got this in the head of the webpage:

<head><br />
        <title>Critique of an Information Graphic</title></p>
<script type="text/javascript" src="stylesheets.js"> </script><link rel="stylesheet" type="text/css" href="stylesheet1.css" title="stylesheet1"/>
<link rel="alternate stylesheet" type="text/css" href="stylesheet2.css" title="stylesheet2"/>
<link rel="alternate stylesheet" type="text/css" href="stylesheet3.css" title="stylesheet3"/>

As you can see, I've chosen to have a permanent style sheet implemented (being the first one of three.)

Would it be possible to make a command button for each stylesheet to run off? (For example, clicking the "Style Sheet 2" button would enable the second style sheet.)