Trying to find code for switching between two style sheets with just one button. I've tried to adapt others' solutions, but to no avail (yet). Here's my most recent attempt:
Set Up:
<link id="style1" rel="stylesheet" type="text/css" href="resumecss.css" />
<script type="text/javascript">
function toggle() {
var el = document.getElementById("style1");
if (el.href == "resumecss.css") {
el.href = "resumecssinvert.css";
}
else {
el.href = "resumecss.css";
}
}
</script>
Calling:
<button type="button" onclick="toggle()">Switch</button>
The purpose being to flip between two skins on one page repeatably.
Thanks in advance to those of you kind/knowledgeable to help.
JavaScript can interact with stylesheets, allowing you to write programs that change a document's style dynamically. There are three ways to do this: By working with the document's list of stylesheets—for example: adding, removing or modifying a stylesheet.
With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.
Use rel="stylesheet" to link to the default style, and rel="alternate stylesheet" to link to alternative style sheets. This tells the browser which style sheet title should be selected by default, and makes that default selection apply in browsers that do not support alternate style sheets.
Try including both of them, and then switched the disabled flag
<link id="style1" rel="stylesheet" type="text/css" href="resumecss.css" />
<link id="style2" rel="stylesheet" type="text/css" href="resumecssinvert.css" disabled="disabled"/>
<script type="text/javascript">
function toggle() {
var el1 = document.getElementById("style1"),
el2 = document.getElementById("style2");
if( el1.disabled == "disabled" ) {
el1.disabled = undefined;
el2.disabled = "disabled";
} else {
el1.disabled = "disabled";
el2.disabled = undefined;
}
}
</script>
This is the shortest solution I could think of (and works probably in all browsers):
function toggle() {
var a = document.getElementById("style1");
a.x = 'resumecssinvert' == a.x ? 'resumecss' : 'resumecssinvert'; // short if
a.href = a.x + '.css';
}
As everything in javascript is a object you can simply add properties.
Assuming that your default css is "resumecss"
The first time x
is not set and returns false
, so "resumecssinvert" will be set.
The second time time x
is set and returns true
and switches back. Everything works as it should.
Your script is solid, except that the href
attribute is a full URL, even if you use a relative path. Here's the code I used that works:
function toggle() {
var el = document.getElementById("style1");
if (el.href.match("resumecss.css")) {
el.href = "resumecssinvert.css";
}
else {
el.href = "resumecss.css";
}
}
See fiddle here: http://jsfiddle.net/jakelauer/LWJjX/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With