Add a Dark/Light Theme Switcher to your Blogger Blog

How to Add a Dark/Light Theme Switcher to a Blogger Blog

Creating a blog that is comfortable to read at any time of the day is a great way to enhance your readers' experience. One popular method is to provide a theme switcher that lets users toggle between a light theme and a dark theme. Here's how you can add such a switcher to a Blogger blog:

Step 1: Add the Theme CSS

Go to the Blogger theme customizer (Theme > Customize > Advanced > Add CSS) and add the following CSS:

body.light-theme {
  --main-bg-color: white;
  --main-text-color: black;
  --link-color: blue;
}

body.dark-theme {
  --main-bg-color: #282c36;
  --main-text-color: #abb2bf;
  --link-color: #61afef;
}

body {
  background-color: var(--main-bg-color);
  color: var(--main-text-color);
}

a {
  color: var(--link-color);
}
  

Step 2: Modify the Body Tag

Go to the Blogger HTML editor (Theme > Edit HTML) and replace the existing <body> tag with the following:

<body expr:class='data:blog.pageType == "item" ? "light-theme" : "dark-theme"'>
  

Step 3: Add the Theme Switching JavaScript

Still in the Blogger HTML editor, add the following JavaScript code right before the closing </body> tag:

<script>
  function setTheme(themeName) {
    document.body.className = themeName;
    document.cookie = 'theme=' + themeName + ';path=/';
  }

  function toggleTheme() {
    if (document.body.className === 'light-theme') {
      setTheme('dark-theme');
    } else {
      setTheme('light-theme');
    }
  }

  (function() {
    var theme = (document.cookie.match(/(^|;)theme=([^;]+)/) || [,'light-theme'])[1];
    setTheme(theme);
  })();
</script>
  

Step 4: Add the Theme Switch Button

Finally, add the following button to your blog where you want the theme switcher to appear:

<button onclick='toggleTheme()'>Switch theme</button>
  

And that's it! Your blog now has a fully functioning theme switcher. Enjoy your new light and dark themes!

Comments

Popular posts from this blog

CSS for Light and Dark Modes

How to Add a Dark/Light Theme Switcher to a Blogger Blog