I successfully implemented a dark and light theme on my website following this helpful guide. The two color schemes are defined as classes in CSS and dynamically applied to the body element using JavaScript. The script automatically selects the theme based on the user's operating system preference, but users can also manually switch between themes by clicking a button, which then overrides the OS settings. The selected preference is saved locally using localStorage.
As I continue learning JavaScript, I attempted to create a function that changes the text of the theme switch button depending on the currently applied theme:
if (document.body.classList.contains("dark-theme")) {
document.getElementById("theme-btn").innerHTML = "Light Mode";
} else if (document.body.classList.contains("light-theme") {
document.getElementById("theme-btn").innerHTML = "Dark Mode";
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body class="dark-theme">
<button class="btn-toggle" id="theme-btn">Dark Mode</button>
</body>
</html>
Although this approach seems to be working fine, I am open to suggestions for improvements or alternative methods to achieve the same outcome. Any advice or ideas would be greatly appreciated!