INTERNET Programming WordPress

How to create a Dark/Night Mode Toggle Button for your Website

add dark mode night mode button website wordpress

More and more apps and websites are adopting the dark mode as it is becoming trendy and a necessary feature demanded by most users. Dark mode can reduce eye strain, especially in low light conditions and helps your users focus on content by reducing the glare and brightness from the background that is usually white on most web pages.

However, some of you may have apprehensions that you would have to redesign the entire website to implement the dark mode feature. However, it doesn’t require a complete redesign as you would have to make some minor changes and additions to the CSS file of your website.

You may have to change the static elements of your website like images, or images used as buttons, or icons, to ensure that they work well in both light and dark backgrounds. These elements have a fixed color that can’t be changed using CSS so choose icons which look good both on a dark and white background.

To add the Dark Mode feature to the page, we would add a button to the page which would toggle the light and the dark mode and also add javascript code to store the user preference on his local computer. So, when the user revisits your page the stored preference would be read from the local storage and the user preference would be automatically applied to the webpage.

Here’s the HTML code to add the button

This code adds a button to the HTML of the web page for the toggle. You can add this to the footer of your website.

<button id="dark-mode-toggle">
  <svg id="moon-icon" viewBox="0 0 128 128" role="img" aria-label="icon">
      <circle cx="64" cy="64" r="36" style="fill:#f2f2f2"></circle>
      <circle cx="64" cy="13" r="5" style="fill:#f2f2f2"></circle>
      <circle cx="99" cy="27" r="5" style="fill:#f2f2f2"></circle>
      <circle cx="114" cy="64" r="5" style="fill:#f2f2f2"></circle>
      <circle cx="99" cy="99" r="5" style="fill:#f2f2f2"></circle>
      <circle cx="64" cy="114" r="5" style="fill:#f2f2f2"></circle>
      <circle cx="28" cy="99" r="5" style="fill:#f2f2f2"></circle>
      <circle cx="14" cy="64" r="5" style="fill:#f2f2f2"></circle>
      <circle cx="27" cy="28" r="5" style="fill:#f2f2f2"></circle>
  </svg>
</button>

If you have a WordPress website then you can simply add the following code to the functions.php file present inside your theme directory. 

/* Code to add a darkmode toggle button in the wp_footer (main site footer) */
function color_toggle(){
echo '<button id="dark-mode-toggle" type="button" title="Darkmode">
        <svg id="moon-icon" viewBox="0 0 128 128" role="img" aria-label="icon">
        <circle cx="64" cy="64" r="36" style="fill:#f2f2f2"/>
        <circle cx="64" cy="13" r="5" style="fill:#f2f2f2"/>
        <circle cx="99" cy="27" r="5" style="fill:#f2f2f2"/>
        <circle cx="114" cy="64" r="5" style="fill:#f2f2f2"/>
        <circle cx="99" cy="99" r="5" style="fill:#f2f2f2"/>
        <circle cx="64" cy="114" r="5" style="fill:#f2f2f2"/>
        <circle cx="28" cy="99" r="5" style="fill:#f2f2f2"/>
        <circle cx="14" cy="64" r="5" style="fill:#f2f2f2"/>
        <circle cx="27" cy="28" r="5" style="fill:#f2f2f2"/>
        </svg>
    </button>';
}
add_action('wp_footer','color_toggle');

This code would add the toggle button with the id “dark-mode-toggle” to the page. The code for this button also contains a <svg></svg> html tag which is being used to create the icon for the button. The icon would be placed in the center of the button.

Add the CSS code to the Stylesheet file

After adding the button we would have to add some CSS to the stylesheet file of the website. 

You can add the following code to the style sheet.

body.dark-mode {
    background-color: #121212;
    color: white;
}

body.dark-mode h1{ 
  color:green;
}

#dark-mode-toggle {
    display: block;
    height: 50px;
    width: 50px;
    position: fixed;
    bottom: 170px;
    right: 60px;
    padding: 0;
    margin: 0;
    border-radius: 100%;
    cursor: pointer;
    background-color: rgba(0, 0, 0, 0.6);
    border: 4px solid grey;
}

If you are using a WordPress website then add the above code to the style.css file, that is present in your website’s theme directory.

The CSS code would be applied to the body of the page. It contains the dark mode code that would be applied to the elements of the page such as the background of the main page, the background color of the content <div> element, any buttons, menu bar etc. You would have to modify this code according to the design of the page.

Let’s say you want all the <h1> tags on your page in white color when the dark mode is activated. To do so, you can add this code to your stylesheet.

body.dark-mode h2{ 
  Color: #fff;
}

This CSS code would only be applied when the dark mode is active. All the <h2> tags in the page would have white color text when the dark mode is active.

Similarly, you can add code for other html elements if you want them to be different colored when the dark mode is active.

Add the javascript to make the Toggle Functional

We would have to add the javascript code to toggle the dark mode and make the button functional. Simply add the following code to your website’s javascript file.

document.addEventListener('DOMContentLoaded', (event) => {
    const darkModeToggle = document.getElementById('dark-mode-toggle');
    const body = document.body;
    darkModeToggle.addEventListener('click', () => {
        body.classList.toggle('dark-mode');
        // Save the user's preference in localStorage
        if (body.classList.contains('dark-mode')) {
            localStorage.setItem('darkMode', 'enabled');
        } else {
            localStorage.setItem('darkMode', 'disabled');
        }
    });

    // Load the user's preference from localStorage
    if (localStorage.getItem('darkMode') === 'enabled') {
        body.classList.add('dark-mode');
    }
});

When the toggle button is pressed it activates the javascript code which adds a darkmode class to the <body> of the page. We have already added the CSS for the darkmode class in the style sheet file of the website.

If you have a WordPress website then you can simply add the following code in the functions.php file present in your theme directory.

function custom_add_inline_script() {
    ?>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', (event) => {
        const darkModeToggle = document.getElementById('dark-mode-toggle');
        const body = document.body;
        darkModeToggle.addEventListener('click', () => {
            body.classList.toggle('dark-mode');
            // Save the user's preference in localStorage
            if (body.classList.contains('dark-mode')) {
                localStorage.setItem('darkMode', 'enabled');
            } else {
                localStorage.setItem('darkMode', 'disabled');
            }
        });
        // Load the user's preference from localStorage
            if (localStorage.getItem('darkMode') === 'enabled') {
            body.classList.add('dark-mode');
            }
        });
    </script>
    <?php
}
add_action('wp_footer', 'custom_add_inline_script');

This javascript code also checks the local storage on the client’s or visitors computer to check the saved preference. If the visitor has visited for the first time then his preference would be saved for the first time when he clicks on the dark mode toggle button. (Also remember that, this feature won’t work if the visitor has javascript or cookies disabled).

See the Pen Dark Mode Toggle by Praveen Singh (@Praveen-Singh-the-decoder) on CodePen.

After saving the javascript code, reload the page by pressing the Ctrl + F5 button which would load the webpage with the toggle button in the bottom right corner of the page. Press it to activate the dark mode, press again to enable normal mode.