Dark mode / theme has seen the light of day in modern design decision and user experience of a lot of app and web-pages. The benefits are listed below.
- Can reduce power usage by a significant amount (depending on the device’s screen technology).
- Improves visibility for users with low vision and those who are sensitive to bright light.
- Makes it easier for anyone to use a device in a low-light environment.
In the wake of these reasons herald the birth of Tuntum.js a pure vanilla js implementation of the dark theme for websites.
- It takes two CSS files thus the light theme CSS and the dark theme CSS
- It persists or stores the preferred theme of the user
- Automatically selects the appropriate theme based on the systems preference
Let’s look into how it was built
1. We create a DOM element link
const createdLink = document.createElement('link');
We create a new DOM element link that we’ll pass our light/dark CSS to after which we set the various attributes to it.
2. We give it a unique identifier to help us manipulate it
createdLink.id = 'tuntum-js'; createdLink.type = 'text/css'; createdLink.rel = 'stylesheet'; createdLink.href = url;
We set the type, rel and href attributes to the created link.
The URL will be the default CSS file to render depending on what you set in the user defaults (options) or the system theme preference.
We added an id to the link we created to help us uniquely identify the link tag so we can dynamically mutate the href.
Below is the full code snippet.
// Create link element in head of DOM const createdLink = document.createElement('link'); createdLink.id = 'tuntum-js'; createdLink.type = 'text/css'; createdLink.rel = 'stylesheet'; createdLink.href = url; if (head.getElementsByTagName('link')[0]) head.insertBefore(createdLink, head.getElementsByTagName('link')[0]); else head.appendChild(createdLink)
Adding this your website
npm i tuntum --save
<script src='tuntum.js'> </script>
Add another <script></script>
just below the above to set your default options as illustrated below then build().
<script> // Default option let options = { isDark: true, isLight: false, lightPath: "./fitaa.css", darkPath: "./tuntum.css", saveState: false }; //Instantiate the Tuntum class let tuntum = new Tuntum(options); tuntum.build(); </script>
Let us know what your thoughts are on this. The source code can be found here.