Hook

—
Their other posts in the index, biggest breakout first.
Whenever I click on the toggle, you can see the dark mode is applied smoothly. And even after reloading, it stays saved in local storage. So let's build this in a simple way. First, I'll take an h1 tag and then a button with an ID called toggle. Now in CSS, I'll use colon root and this will show the light mode by default. Next, I want that one I click the toggle, the page switches to dark mode. The text becomes white and the button becomes black. For that, I'll use body.dark and define the dark version there. Now if I apply this class to the body, you can see it converts into dark mode. But I want to toggle on button click. So I'll remove it from here. Now we'll write. Const btn = document.getElementById("toggle"); Now I'll check if the theme is already dark in local storage. If it is, then I'll add the dark class to the body. Now I'll set an onclick function on the button. Document.body.classList.toggle("dark"); Which means when I click, dark will be added. And when I click again, it will be removed. Now I want to save the user's preference. So here I'll use an if else condition. If document.body.classList.contains("dark"), then localStorage.setItem("theme", "dark"); else localStorage.setItem("theme", "light"); Now if I click, you can see dark mode is working. And even after refresh, it's not changing because it's already saved in local storage. Thanks for watching and make sure to subscribe to my youtube channel.