Steve0Greatness

Creating a simple theme switcher

This is a simple tutorial on how to make a simple theme switcher.

Step 1: Creating the themes

The first step is to create the themes in your stylesheet, you can have as many as you want. Just make sure to remeber all their names within your CSS.

Step 2: Making an array

This is why you need to remeber all their names within the CSS. You need to add them all to an array in your JS. Below is an example of an array containing some themes.

const themes = ["light", "dark", "gamer"]

Step 3: Switching themes

This is the part you've been waiting for! The actual content switcher. It's surprisingly simple.

First, get the index of the current theme using let currentTheme = themes.indexOf(document.documentElement.className). Then, use an if statement to see if it's more than or equal to the length of the array containing your themes.

if (currentTheme + 1 >= themes.length) {
document.documentElement.className = themes[0]
} else {
document.documentElement.className = themes[currentTheme + 1]
}
Now just add a listener to the button(using event listener, getElement.onclick, or onclick)

Final Product

In the end, what you just made should look something like the iFrame below.