I'm sorry if that's a duplicate, but I found myself in trouble as I can't get my theme mode stored in local storage.
Here is my HTML code:
<!--
The data-* attribute is used to store custom data private to the page or application.
The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
-->
<body id="webPage" class="container" data-theme="light">
<div class="">
<h1>Hello world</h1>
</div>
<div class="">
<button id="toggleDarkMode" type="button" class="" onclick="darkMode()">
Click Me !
</button>
</div>
<div class="">
<a href="#">
This is a link
</a>
</div>
</body>
As you can see, everything is handled by data-theme="light"
to apply my css and onclick="darkMode()"
to trigger my javascript. Here is the CSS:
:root {
--colour-bck: #FFFAFA;
--colour-font: #222;
}
[data-theme="light"],
a {
transition-duration: 1s;
}
/* If mode is swicthed, then apply following changes to the variable */
[data-theme="dark"] {
--colour-bck: #222;
--colour-font: #FFFAFA;
transition-duration: 1s;
}
/* Styling the DOM */
body {
margin: 0
}
.container {
height: 100vh;
background-color: var(--colour-bck);
}
body {
color: var(--colour-font);
}
a {
text-decoration: none;
color: var(--colour-font);
display: block;
margin-top: 2em;
}
And the JavaScript:
/*
darkMode switches to a dark/light mode view : body which renders the mode is fetch alongside data-theme holding the styles to render
if the theme is dark, change it to light, which applies "data-theme = light" styles & vice-sersa
*/
console.log(localStorage)
function darkMode() {
const container = document.getElementById('webPage');
// const theme = container.getAttribute('data-theme');
var dataTheme = container.getAttribute('data-theme');
localStorage.setItem("theme", dataTheme);
(localStorage.theme === 'dark') ? container.setAttribute('data-theme', 'light'): container.setAttribute('data-theme', 'dark');
}
Now, the thing is, I don't get any errors, and my value is saved into localStorage according to the console.log()
. Hence my question, what did I do wrong?
question from:
https://stackoverflow.com/questions/65942968/storing-and-retrieving-a-theme-in-javascript-from-a-data-attribute 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…