Reputation: 181
I'm making a webpage which includes buttons to change the theme from light to dark and back on the front page. However, if I click through to another page I want the theme to stay.
Is there a way I can tell the browser to choose the css file dynamically based on whether the user was using the light or dark theme?
For reference here is what I have on the front page:
Javascript:
function swapStyleSheet(sheet, text){
//variables to access elements in the DOM
var styleSheet = document.getElementById('pagestyle');
var defaultText = document.getElementById('styleSwitchText');
styleSheet.setAttribute('href', sheet); //changes the stylesheet
defaultText.style.display = "none"; //hides initial text
//creates p element and appends text parameter to it
var pElement = document.createElement('p');
var textnode = document.createTextNode(text);
pElement.appendChild(textnode);
var item = document.getElementById('swapStyleButtons');
//replaces the text node in the p each time button is clicked
item.replaceChild(pElement, item.childNodes[0]);
}
html:
<div id="swapStyleButtons">
<p id="styleSwitchText">Don't like the style? Try Night Mode!</p>
<button id='night' onclick='swapStyleSheet("dark.css", "Think Night Mode sucks? Switch back!")'>Night</button>
<button id='default' onclick='swapStyleSheet("recipes.css", "Liked it better before? Try Night Mode!")'>Default</button>
</div>
This works perfectly on the front page. I could just repeat this process for the other pages but then the user would have to press the button on every page, which is obviously a bit annoying.
Can 1 html page communicate with another in this way?
Upvotes: 0
Views: 56
Reputation: 3662
Inside buttons click event for choosing stylesheet write following code to set selected stylesheet as local storage
localStorage.setItem("Selected_Style_sheet_name", "yourstylesheetname");
In Home Page set selected theme
var btn1 = document.getelementbyid("btnTheme1");
var btn2 = document.getelementbyid("btnTheme2");
btn1.onclick =function(){
localStorage.setItem("Selected_Style_sheet_name", "Theme1.css");
}
btn2.onclick =function(){
localStorage.setItem("Selected_Style_sheet_name", "Theme2.css");
}
Now apart from home page every page add following code it
if(localStorage.getItem("Selected_Style_sheet_name") !== null){
styleSheet.setAttribute('href', localStorage.getItem("Selected_Style_sheet"));
}
Upvotes: -1
Reputation: 53
With HTML5 you can store data with HTML itself and u do not need to another language.
function setColorTheme(curColorTheme)
{
if(typeof(Storage) !== "undefined") {
localStorage.setItem("colorTheme", curColorTheme);
} else {
// Backup cookie Support
}
}
function getColorTheme()
{
if(typeof(Storage) !== "undefined") {
return localStorage.getItem("colorTheme");
} else {
// Backup cookie Support
}
}
Here is a tutorial:
http://www.w3schools.com/html/html5_webstorage.asp
Upvotes: 4