I'm trying to create a dark mode toggle button and I require following text properties :-
Turn on dark mode
should appear when theme is a light oneTurn off dark mode
should appear if theme is dark one.Nothing more, Currently, I'm using follwing code to toggle between dark and light mode but the issue comes with button. I tried different codes but the text gets swapped in a wrong manner. https://codepen.io/vkdatta27/pen/oNxrxad .
<script>const btn = document.querySelector(".btn-toggle");
const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
document.body.classList.add("dark");
}
btn.addEventListener("click", function () {
document.body.classList.toggle("dark");
let theme = "light";
if (document.body.classList.contains("dark")) {
theme = "dark";
}
localStorage.setItem("theme", theme);
});
</script>
<style>
.btn-toggle {
border-radius: 20px;
float: center;
outline: none;
border: 25px;
padding: 10px;
width: fit;
font-size: 15px;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
text-align:center;
box-shadow: 5px 5px 10px #5c5c5f,
-5px -5px 10px #ffffff;
background-color: #101010;
color: #e6e7ee;
}
body.dark .btn-toggle {
box-shadow: 5px 5px 10px #121212,
-5px -5px 10px #4a4a4a;
color: #101010 !important;
background-color: #e6e7ee;
}
body.dark .btn-toggle a {
color: #101010 !important;
}
body {background-color: #e6e7ee}
body.dark {background-color: #101010; color:#ffffff}
</style>
<button class="btn-toggle" id="btn-id"></button>
In your case you don't really need Javascript to get things done:
Logic:
.dark
is off, show text 1 - this is the default.dark
is on, show text 2 - when CSS class .dark
is activeCSS:
/* ADDED */
.btn-toggle::before { content: 'dark mode' } /* default text of the button */
.dark .btn-toggle::before { content: 'light mode' }/* overwrite the default text*/
/*********/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.