There are so many articles about cookies
and localStorage
(setting, deleting...), but it's unclear for me where I should place some code.
Namely, I'm trying to change css stylesheet clicking on a button, but cannot save that choice for the next time the page is loaded. Something like:
params.php
if (user clicked on "btntheme") {
$theme = 'green.css';
}else{
$theme = "blue.css";
};
index.php
<?php include ("params.php");?>
<head>
<link id="link01" rel="stylesheet" href="<?php echo $theme;?>">
</head>
<body>
<div id="btntheme">THEME</div>
</body>
JS
$('#btntheme').click(function(){
$('#link01').attr('href', 'green.css');
});
This changes style but only for the current session. How can I tell to params.php
that in the future $theme
is green.css
, and not blue.css
?
Using localStorage is very easy.
To set
localStorage.setItem('theme','green');
To get
localStorage.getItem('theme');
So you can just use that in a function to get from LS and then set your stylesheet.
function changeTheme(){
var theme = localStorage.getItem('theme');
$('#link01').attr('href', theme + '.css');
}
$('#btntheme').click(function(){
localStorage.setItem('theme','green');
changeTheme();
});
And you can just call that function in your document.ready
function to set it on page load as well.
You can use select
element to set localStorage
to user selected value. Use $.holdReady(true)
to check if localStorage
is not null
, if a value is set at the key, set href
of link
element, else call $.holdReady(false)
. Would consider setting a default href
for link
element for case where user does not make a selection.
html
<!-- set default value at `href` -->
<link id="link01" rel="stylesheet" href="<?php echo $theme;?>">
<select>
<option>Select a theme</option>
<option value="green.css">Green Theme</option>
<option value="blue.css">Blue Theme</option>
</select>
javascript
$.holdReady(true);
if (localStorage.getItem("theme") !== null) {
$("#link1").attr("href", localStoage.getItem("theme"))
}
$.holdReady(false);
$(function() {
$("select").change(function(e) {
$("#link1").attr("href", this.value);
localStorage.setItem("theme", this.value);
});
});