PDA

View Full Version : Changing stylesheets across multiple pages using javascript



IanOLeary1
07-13-2011, 02:02 PM
I'm trying to allow the user to change the stylesheet of my website. I can change the stylesheet on a page by page basis (eg. from red style to blue style) but once the user navigates to a different page the stylesheet resets back to the original setting.

For example, when the user visits the site first its set to the red style, they can change it to blue but when they navigate to another page the style goes back to red again where as I want the style to stick across pages.

HTML


<html>
<head>
<link href="red.css" rel="stylesheet"
type="text/css" title="red" media="screen" />
<link href="green.css" rel="alternate stylesheet"
type="text/css" title="green" media="screen" />
<link href="blue.css" rel="alternate stylesheet"
type="text/css" title="blue" media="screen" />

<script type="text/javascript">
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;
}}}
</script>


</head>
<body>
<a href = "home1.html">Page 1</a>
<br>
<br>
<a href = "home2.html">Page 2</a>
<br>
<br>
<a href = "home3.html">Page 3</a>
<br>
<br>
<br>
<br>
<a href = "#" onclick="changeStyle('red')">Red Stylesheet</a>
<br>
<br>
<a href = "#" onclick="changeStyle('blue')">Blue Stylesheet</a>
<br>
<br>
<a href = "#" onclick="changeStyle('green')">Green Stylesheet</a>
</body>
</html>

CSS


body
{
background-color:red;
}

Beverleyh
07-13-2011, 03:09 PM
You'll need to set a cookie to remember user choice - try these:

http://plugins.jquery.com/plugin-tags/stylesheet-switcher
http://www.kelvinluck.com/2006/05/switch-stylesheets-with-jquery/
http://www.net-kit.com/10-practical-jquery-style-switchers/