DEV Community

Discussion on: Simple JavaScript Theme Toggle

Collapse
 
link2twenty profile image
Andrew Bone • Edited

You could so something like

:root {
    /*--------------------Light Theme Variables (Default)--------------------*/
    --light-theme-background-color: #eee;
    --light-theme-darker-background-color: #ccc;
    --light-theme-text-color: #333;
    --light-theme-link-color: #ff6347;
    --light-theme-link-hover-color: #fa2600;

    /*--------------------Dark Theme Variables--------------------*/ 
    --dark-theme-background-color: #333;
    --dark-theme-darker-background-color: #111;
    --dark-theme-text-color: #eee;
    --dark-theme-link-color: #00fa9a;
    --dark-theme-link-hover-color: #00955b; 

    /*--------------------Other Variables--------------------*/ 
    --link-hover-timing: all 0.25s ease-in-out;
    --theme-change-timing: all 1s ease-in-out;
}

body[data-theme=light] {
  --theme-background-color: var(--theme-light-background-color);
  --theme-darker-background-color: var(--theme-light-darker-background-color);
  --theme-text-color: var(--theme-light-text-color);
  --theme-link-color: var(--theme-light-link-color);
  --theme-link-hover-color: var(--theme-light-ink-hover-color);
}

body[data-theme=dark] {
  --theme-background-color: var(--theme-dark-background-color);
  --theme-darker-background-color: var(--theme-dark-darker-background-color);
  --theme-text-color: var(--theme-dark-text-color);
  --theme-link-color: var(--theme-dark-link-color);
  --theme-link-hover-color: var(--theme-dark-ink-hover-color);
}

var body = document.querySelector('body');
var themeToggle = document.querySelector('#theme-toggle');

themeToggle.addEventListener('click', () => {
  var theme = body.dataset.theme;
  theme = theme == "dark" ? "light" : "dark"
});
Collapse
 
ryandotfurrer profile image
Ryan Furrer

What is the benefit of using dataset rather than a class?

Collapse
 
link2twenty profile image
Andrew Bone

The only benefit would be that you don't have to remove the old class simple override the dataset.

The main advantage of this method is that you don't need to change classes in several places. Simply change the dataset, or class if you prefer, on the body and everything else follows automatically.

Thread Thread
 
ryandotfurrer profile image
Ryan Furrer

I see! Interesting - I'm still (obviously) a novice in JS and definitely want to look more into this.

Thanks so much for reading and commenting, Andrew!