I'm trying to use a dark theme and light theme on my webpage, but I can't find a way to toggle them with just one button (so 1st click of the button turns on the dark theme and 2nd time turns it off). I would prefer to be able to do this without the use of a third-party JavaScript library. I have found a way to do this with an <option> element but that isn't the "toggle button" I want:
<button onclick=getTheme() id=themeToggle>Click to use this theme.</button>
<select id="select">
<option>Dark Theme</option>
<option>Revert To Original</option>
</select>
and
function getTheme () {
function changeTheme (Theme) {
document.getElementById('style').setAttribute('href', Theme);
}
var index = document.getElementById("select").selectedIndex;
switch (index) {
case 0:
changeTheme('css/dark.css');
break;
case 1: changeTheme('css/main.css');
}
}
Thanks for your help!
Another way is to use a boolean. You can change the value of the boolean on each click. And you can toggle the css with this boolean.
<button onclick=getTheme()>Click to use this theme.</button>
Js
var bool = true;
function getTheme() {
function changeTheme (theme) {
document.getElementById('style').setAttribute('href', theme);
}
bool = !bool;
var theme = bool ? 'css/dark.css' : 'css/main.css';
changeTheme(theme);
}
This does work perfectly, however, is there a way to use document.getElementById("themeToggle").innerHTML = "New text!"; with this to change the button between "dark theme" or "light theme"
You can use the same logic, like:
var bool = true;
function getTheme() {
function changeTheme (theme, text) {
document.getElementById('style').setAttribute('href', theme);
document.getElementById('themeToggle').innerText = text;
}
bool = !bool;
var theme = bool ? 'css/dark.css' : 'css/main.css';
var text = bool ? 'Dark theme' : 'Light theme';
changeTheme(theme, text);
}
I know this seems a bit amateur but you can do something like this,
<button onclick=getTheme() id=themeToggle>Click to use this theme.</button>
<script>
var click = 0;
function getTheme()
{
click++;
if(click%2 == 0)
changeTheme('css/dark.css');
else
changeTheme('css/main.css');
}
</script>
and change text on button accordingly. Let me know if it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With