Swap Style Sheet with Localstorage

Swap style sheet with localstorage

you can use this code

<script>
var swapStyleSheet = function (sheet) {
document.getElementById('pagestyle').setAttribute('href', sheet);
storebackground(sheet);
}

var storebackground = function (swapstylesheet) {
localStorage.setItem("sheetKey", swapstylesheet); //you need to give a key and value
}

var loadbackground = function () {
document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
}

window.onload = loadbackground();
</script>

Change Stylesheet and save it to Cookies / Local storage

At load event of window define a variable to store reference to Blob URL. If localStorage has key, for example, "styles", get css from localStorage, create a Blob with localStorage.getItem("styles") set as element of iterable at first parameter, type set to "text/css". Pass Blob to URL.createObjectURL() to set at value of #design .href. Else, filter document.styleSheets for .href which matches sheet parameter at swapStyleSheet call, create get .cssText from .rules property lookup, set as Blob, perform above described procedures.

window.onload = function() {
let blob, url;

function setStyle() {
var sheet = localStorage.getItem("styles");
blob = new Blob([localStorage.getItem("styles")], {type:"text/css"});
url = URL.createObjectURL(blob);
document.getElementById("design").setAttribute("href", url);
}

if (localStorage.getItem("style") != null) setStyle();

function swapStyleSheet(sheet) {

var rules = Array.prototype.filter.call(document.styleSheets, function(styles) {
return styles.href.indexOf(sheet) !== -1
})[0].rules;

for (var i = 0, css = ""; i < rules.length; i++) css += rules[i].cssText;

if (url) URL.revokeObjectURL(url);

localStorage.setItem("styles", css);

setStyle();

}
}

Save current stylesheet to local storage

You are just forgetting about Storage.setItem(). You stated the you want to 'save' the most recent stylesheet that was used.

I think you are confusing the idea of state here. In your code sample, you read value a from localStorage, but you did not attempt to set localStorage at any point.

Let's look at a minimal example. I prepared a live demo below:

LIVE DEMO

Imagine you have these files:

index.html

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link id="active-stylesheet" href="" rel="stylesheet" type="text/css"/>
</head>

<body>
<div class="switch-buttons">
<button class="switch-buttons__light button" data-stylesheet="light.css">Go Light</button>
<button class="switch-buttons__dark button" data-stylesheet="dark.css">Go Dark</button>
</div>
<h1>Light and Dark Stylesheets with Web Storage API</h1>
<h2> See <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage">MDN Storage - Web Storage API</a>.</h2>
<p>
Click a button above. The style you select will be 'remembered' when you refresh this page. To reset this demo, click the 'Clear Storage' button.</p>
<p>
Faucibus interdum posuere lorem ipsum dolor sit amet, consectetur adipiscing elit duis tristique sollicitudin nibh sit amet commodo nulla facilisi? In metus vulputate eu scelerisque felis imperdiet proin fermentum leo.</p>
<p>
Etiam sit amet nisl purus, in mollis nunc sed id semper risus in! Ultricies lacus sed turpis tincidunt id aliquet risus feugiat in ante metus, dictum at tempor commodo, ullamcorper?</p>
<button id="clear-storage">Clear Storage</button>
<script src="script.js"></script>
</body>

</html>

light.css

body {
background-color: #fff0bc;
}

h1, h2, p {
color: #363636;
}

dark.css

body {
background-color: #363636;
}

h1, h2, p {
color: #fff0bc;
}

script.js

var buttons = document.getElementsByClassName("button");
var activeSheet = document.getElementById("active-stylesheet");
var clearStorageButton = document.getElementById("clear-storage");

// Test to see if localStorage already has a value stored
if (localStorage.getItem("lastActiveSheet")) {
activeSheet.setAttribute("href", localStorage.getItem("lastActiveSheet"));
}

// Assign the event lister to each button
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", switchStyle);
}

// Create a button to clear localStorage
clearStorageButton.addEventListener("click", clearStorage);

// Set the #active-stylesheet to be the light or dark stylesheet
function switchStyle() {
var selectedSheet = this.getAttribute("data-stylesheet");
activeSheet.setAttribute("href", selectedSheet);
localStorage.setItem("lastActiveSheet", selectedSheet);
}

// Wrapper function to localStorage.clear
function clearStorage() {
localStorage.clear();
}

If you want your app to remember the most recently used stylesheet, you need to store it into localStorage as a value you can use when the user visits your app again in the future.

As @Hynek had pointed out, it is not a good idea to use window.onLoad. So, in this example, I attached event listeners to all buttons used instead.

In this example, the page has two options to select from: a light and a dark theme for contrast. If the user selects a theme, it will be remembered the next time the page is refreshed.

The key here is the state. You want your app to have 'memory'. So, you need to add the functionality to write, read, and clear the memory. I suggest reading more through MDN - Storage - Web APIs to see how you can implement this. On MDN, there are even more examples too!

Store users choice of CSS-style with local storage (How?)

I managed to solve my problem! Thought this might be useful to other than just me so here it is:

Javascript

function changeCSS(sheet) { 
document.getElementById('active_stylesheet').setAttribute('href', sheet);
localStorage.setItem('sheet', sheet);
}

var stylesheets = document.getElementsByClassName("left_sub8");

stylesheets[0].addEventListener("click", function(){
changeCSS('inlamning7_utseende1.css');
});
stylesheets[1].addEventListener("click", function(){
changeCSS('inlamning7_utseende2.css');
});
stylesheets[2].addEventListener("click", function(){
changeCSS('inlamning7_utseende3.css');
});
stylesheets[3].addEventListener("click", function(){
changeCSS('inlamning7_utseende4.css');
});

window.onload=function() {
document.getElementById('active_stylesheet').setAttribute("href", localStorage.getItem("sheet"));
};

Note 1: I did not change the html-code so that is the same as in the question above

Note 2: There is another problem now, which is unless the user chooses a theme, no css-document is loaded at all. This is not good, so a css-file needs be loaded by default if no theme is selected by the user. This remains to be solved.



Related Topics



Leave a reply



Submit