Reputation: 41
I am trying to toggle between two different stylesheets to display different theme styles. I have 2 different stylesheets that I want to toggle between.
The stylesheets:
<link rel="stylesheet" type="text/css" title="light" href="css/default.css" />
<link rel="alternative stylesheet" type="text/css" title="dark" href="css/default_style2.css" />
<link rel="stylesheet" type="text/css" href="css/component.css" />
I gave each stylesheet a title tag of light and dark for reference when the toggle will be clicked to change the stylesheets.
my jQuery code:
<div id="toggleTheme">
<script>
$(document).ready(function () {
$("#light, #dark").click(function () {
changeStyle(this.getAttribute("rel"));
return false;
});
function changeStyle (light, dark) {
var light = $(this).attr('title') == "light";
var dark = $(this).attr('title') == "dark";
if ()
}
});
</script>
<ul id="themeToggle">
<a href="#" id="light"><li>light theme</li></a>
<a href="#" id="dark"><li>dark theme</li></a>
</ul>
</div>
Not sure where to go from here...
Some assistance will be great. Thanks in advance.
Upvotes: 1
Views: 1314
Reputation: 1074238
Simply detach
the one you don't want to be applied. The browser will remove all of the styles it defines. To activate it, attach it and detach the other one.
Here's a very quick and dirty example using style
elements, but the same principle applies to link
elements:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Changing styles</title>
<style id="light">
body {
color: black;
background-color: white;
}
</style>
<style id="dark">
body {
color: white;
background-color: black;
}
</style>
</head>
<body>
<label><input type="radio" name="chooseStyle" value="light">Light</label>
<label><input type="radio" name="chooseStyle" value="dark" checked>Dark</label>
<script>
(function() {
var styles = {
light: $("#light").detach(),
dark: $("#dark")
};
$("input[name=chooseStyle]").click(function() {
var other = this.value === "light" ? "dark" : "light";
styles[this.value].appendTo('head');
styles[other].detach();
});
})();
</script>
</body>
</html>
Upvotes: 2