My latest project involved creating a dark mode button along with a custom dark theme. The theme is stored in Local Storage to ensure consistency. However, I have encountered an issue where, upon page reload, the site remains in dark mode but the button icon reverts back to a moon. To better illustrate the problem, here is a link to a screenshot: ()
//This script handles the dark mode functionality.
function darkmode() {
const wasDarkmode = localStorage.getItem('darkmode') === 'true';
localStorage.setItem('darkmode', !wasDarkmode);
const element = document.body;
element.classList.toggle('dark-mode', !wasDarkmode);
}
function onload() {
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
}
//End
//The following code switches the button's icon
$('button').on('click', fav);
function fav(e) {
$(this).find('.fa').toggleClass('fa-moon-o fa-sun-o');
}
//I am looking to integrate these two codes, specifically to save the icon state in Local Storage.
.card {
color: yellow;
background-color: blue;
}
.dark-mode .car {
color: blue;
background-color: yellow;
}
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<a style="padding: 0 !important;"><button class="darkmode" onclick="darkmode()"><i class="fa fa-moon-o"></i></button></a>
<div class="card">
<h1>Title</h1>
<p>Text<//p>
<h2>Another text..</h2>
</div>
</body>
</html>