So let’s get started with below HTML and CSS.
and following CSS
If you save, above markup in a file and load in browser you should see below output. Please make sure you load the page using a local server.
data-theme attribute on
body element as follows
We have not set any value to
data-theme attribute and will treat default/null is equal to light theme.
So if you save it and reload the browser tab you won’t see any difference.
Next, we will set
onclick handler of theme swicther button
Now we have defined the onclick handler however we have not created the function yet. So lets create
switchTheme() function. You can open the
script tags within document or create the function in separate file.
Before we author that function lets gather our requirements
themeproperty - on inital load this won’t exist so, it will return null. We are using localStorage as we need to persist the theme betwen various page loads. If current theme is
lightupdate the theme value to
data-themeattribute defined in step#1 above
switchTheme() function is ready. Now, we need to handle the scenario when the website is loaded the first time - again there are two cases here listed below
So let’s handle the above two scenarios in function
setTheme() and here are our detailed requirements
themeis not found then default it to
lighton the first load
data-themeattribute that we created in step#1 above.
setTheme()function on initial page load
As you can see few of steps are common between the
switchTheme() function and
setTheme() function so, its good time to refactor
switchTheme() function and below is updated code.
We have removed last 2 lines and called
setTheme() function instead
Local Storage section and then click on the theme switcher button you should see the theme being updated at each click.
Now we just need to add magic of CSS data attributes here to respond to theme switcher button.
You can use any color however, I just used two colors i.e.
data-themeis set to
dark, we are setting the font color to
black. No action is required when the theme color is
lightas the browser will default the font color to
blackand background color to
A working demo of code discussed above