I am working on a webpage for an embedded device where the server storage space is very limited. I want the user to be able to switch between day mode and night mode viewing of the webpages. To do so I would like to just load the page using a different webpage with a button is clicked. I don't want to have two copies of every page because I don't have enough space. Is there a way to switch to a different css page or load the css dynamically somehow? I can only use html and javascript. No PHP or asp.net.
2 Answers
Let me argue for something even simpler:
1: One CSS:
.day {
color: black;
background-color: white;
}
.night {
color: white;
background-color: black;
}
.day #content {
color: blue;
}
.night #content{
color: red;
}
2: One HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="dayornight.css">
</head>
<body class="day">
<div id="content">
<a>Hello World!</a>
</div>
</body>
</html>
3: A small piece of JavaScript or jQuery code tied to the button that toggles the class on the body tag from day to night.
As you can see if you bring this example up in your browser, changing the class not only changes the CSS style of the body, it can also shift the contained items as well because their selectors match differently now.
1 Comment
PICyourBrain
Thanks for the tip. I didn't think of that but it seems so simple. I will give it a try!
Here you go in plain javascript:
JS:
function change_css(){
var oLink = document.createElement("link")
oLink.href = "new_css.css"; //new css filename
oLink.rel = "stylesheet";
oLink.type = "text/css";
document.body.appendChild(oLink);
}
HTML:
<button onclick="change_css()" value="css change"/>
2 Comments
sdleihssirhc
This just adds a stylesheet, right? It doesn't get rid of the old one? You'd have to worry about overriding rules, specifity, being able to spell "specificity"...
Naftali
@sdleihssirhc css rules cascade, so the the new rules would override the old ones