I am trying to add dark-mode to the website. When someone clicks the dark mode button it will add additional CSS classes and remove them when the button is clicked again.
I know I can do it easily with toggleClass
but I don't want to disable this automatically when the page refreshes or some other page is opened on the website.
I have been playing with sessionStorage
but unable to succeed so far I have come up with this code here:
<a href="#" class="darkmode-button" id="dmbutton" onclick="changeText()">Dark Mode</a>
<div class="header-wrap">
Testing toggle with session
</div>
$('.darkmode-button').click(function() {
if (sessionStorage.getItem('darkmode', 'true')) {
$('.header-wrap').removeClass('dark-header');
sessionStorage.setItem('darkmode', 'false');
}
if (sessionStorage.getItem('darkmode', 'false')) {
$('.header-wrap').addClass('dark-header');
sessionStorage.setItem('darkmode', 'true');
}
});
function changeText() {
var x = document.getElementById("dmbutton");
if (x.innerHTML === "Dark Mode") {
x.innerHTML = "Light Mode";
} else {
x.innerHTML = "Dark Mode";
}
}
.header-wrap {
color: black;
}
.dark-header {
color: white;
background-color: black;
}
Can someone please share a working example of how it can be achieved?
I already created a question before but it was marked duplicate with this answer. I read it all but still could not figure it out.