I'm using two stylesheets to improve the dark/light mode in my website but after refreshing the website it lost the chosen stylesheet and came back to default as it coded in the index file, I heard about sessionStorage
in JavaScript but I couldn't use it in my code.
And here is my code:
- Index.html
<link href="assets/css/style.css" rel="stylesheet" id="lnk">
<script>
function toggleTheme() {
link = document.getElementById("lnk");
if (link.getAttribute('href') == 'assets/css/style.css') {
link.setAttribute('href', 'assets/css/darkstyle.css');
const element = document.getElementById("dark-mode");
element.innerHTML = "<i class='bx bxs-moon'></i>";
} else {
link.setAttribute('href', 'assets/css/style.css');
const element = document.getElementById("dark-mode");
element.innerHTML = "<i class='bx bx-moon'></i>";
}
sessionStorage.setItem("autosave", link);
}
</script>
- Button to toggle the theme
<button onclick="toggleTheme()" class="dark" id="dark-mode"><i class="bx bx-moon"></i></button>