Toggle light and dark themes in Bootstrap - DEV

In this article we will learn how we can easily toggle between light and dark theme.

While theming in Bootstrap[1] can be done through it's built-in SASS variables, for this article we are going to use provided css stylesheets.

Bootswatch[2] has some great themes, we're going to use it's Cyborg[3] theme for darker variant. And for light, we are going to use Bootstrap's default theme.

So, let's get started.

Create project folder and index.html file

mkdir toggle-bootstrap-theme cd toggle-bootstrap-theme 

Create the index.html file in it:

<!DOCTYPE html> <html lang="en">   <head>     <!-- Required meta tags -->     <meta charset="utf-8" />     <meta       name="viewport"       content="width=device-width, initial-scale=1, shrink-to-fit=no"     />      <!-- Bootstrap CSS -->     <link       rel="stylesheet"       href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"       integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"       crossorigin="anonymous"     />      <!-- ๐Ÿšจ Notice this link -->     <link id="dark-theme-style" rel="stylesheet" />      <title>Toggle Bootstrap Theme</title>   </head>   <body>     <nav class="navbar navbar-transparent">       <!-- ๐Ÿšจ Notice the toggleTheme() function -->       <a         href="javascript:void()"         class="btn btn-outline-info btn-lg ml-auto font-weight-bold"         id="theme-toggler"         onclick="toggleTheme()"       ></a>     </nav>      <div class="container-fluid">       <div class="jumbotron">         <h1 class="display-4">Hello, world!</h1>         <p class="lead">           This is a simple hero unit, a simple jumbotron-style component for           calling extra attention to featured content or information.         </p>         <hr class="my-4" />         <p>           It uses utility classes for typography and spacing to space content           out within the larger container.         </p>         <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>       </div>     </div>      <!-- Optional JavaScript -->     <!-- jQuery first, then Popper.js, then Bootstrap JS -->     <script       src="https://code.jquery.com/jquery-3.5.1.slim.min.js"       integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"       crossorigin="anonymous"     ></script>     <script       src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"       integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"       crossorigin="anonymous"     ></script>     <script       src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"       integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"       crossorigin="anonymous"     ></script>      <!-- ๐Ÿšจ Our custom JavaScript  -->     <script src="index.js"></script>   </body> </html>  

Notice these 2 snippet in above code:

<link> to dynamically load stylesheet

<link id="dark-theme-style" rel="stylesheet" /> 

Here, we will render dark theme stylesheet through JavaScript. Also note that we have kept this after our default stylesheet, so that if any rules is missing in dark one, it will be taken from default.

<a> to toggle themes

<a         href="javascript:void()"         class="btn btn-outline-info btn-lg ml-auto font-weight-bold"         id="theme-toggler"         onclick="toggleTheme()" ></a> 

This anchor tag will help user to toggle between light and dark theme. We are going to create function toggleDark in JavaScript. Let's see that.

Create index.js file

// you can use app's unique identifier here const LOCAL_STORAGE_KEY = "toggle-bootstrap-theme";  const LOCAL_META_DATA = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));  // you can change this url as needed const DARK_THEME_PATH = "https://bootswatch.com/4/cyborg/bootstrap.min.css";  const DARK_STYLE_LINK = document.getElementById("dark-theme-style"); const THEME_TOGGLER = document.getElementById("theme-toggler");  let isDark = LOCAL_META_DATA && LOCAL_META_DATA.isDark;  // check if user has already selected dark theme earlier if (isDark) {   enableDarkTheme(); } else {   disableDarkTheme(); }   /**  * Apart from toggling themes, this will also store user's theme preference in local storage.  * So when user visits next time, we can load the same theme.  *  */ function toggleTheme() {   isDark = !isDark;   if (isDark) {     enableDarkTheme();   } else {     disableDarkTheme();   }   const META = { isDark };   localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(META)); }  function enableDarkTheme() {   DARK_STYLE_LINK.setAttribute("href", DARK_THEME_PATH);   THEME_TOGGLER.innerHTML = "๐ŸŒ™ Dark"; }  function disableDarkTheme() {   DARK_STYLE_LINK.setAttribute("href", "");   THEME_TOGGLER.innerHTML = "๐ŸŒž Light"; }  

I believe that above code is self-explanatory ๐Ÿ˜‰ and no further explanation is required.

Output

After successfully writing all of the above code, you can simply open index.html in browser to see the output:

Toggle Bootstrap Theme output

๐Ÿ‘‰ The http call to dark stylesheet is done only once per session. If user switches back to light theme and then again dark theme, it is loaded from cache. See the Network panel in browser devtools to see this.

Conclusion

We learned how easily we can toggle between light and dark theme with just few lines of JavaScript code.

If you're looking for a complete Bootstrap theme generation code base with support of sass, gulp, auto-refresh, etc. checkout my github repo:

Quickly generate and showcase your bootstrap theme.

Bootstrap Theme Kit

Quickly โšก Generate and Showcase ๐ŸŽฏ your bootstrap theme ๐ŸŽจ. Get Started[4] or See sample theme[5].

GitHub license Commitizen friendly

๐Ÿš€ Getting Started

โ˜‘๏ธ Minimum Requirements

node -v // v10.17.0 git --version // git version 2.x

โฌ‡๏ธ Steps to Follow

  1. First, fork this repo.
  2. Open terminal and:
git clone <forked-repo-url> cd bootstrap-theme-kit npm i npm run init npm start
  1. Browser will open at 3000 port.
  2. Start editing your scss/html files and browser will reload.

๐Ÿ† Features

And yes, always believe in yourself...

silhouette of trees under starry night photo โ€“ Free Nature Image on Unsplash

Photo by Nick Dunlap on Unsplash[6][7]

References

  1. ^ theming in Bootstrap (getbootstrap.com)
  2. ^ Bootswatch (bootswatch.com)
  3. ^ Cyborg (bootswatch.com)
  4. ^ Get Started (raw.githubusercontent.com)
  5. ^ See sample theme (shhdharmen.github.io)
  6. ^ Nick Dunlap (unsplash.com)
  7. ^ Unsplash (unsplash.com)
keywords bootstrap, css3, javascript, webdev, software, coding, development, engineering, inclusive, community

No Items Found.

Add Comment
Type in a Nick Name here
 
Other Items in webdev
Font Awesome Icons [ Icons ] - CSS Bundle Daily Dev Tips CSS Background Patterns by MagicPattern GitHub - ganlanyuan/tiny-slider: Vanilla javascript slider for all purposes. GitHub - jonasstrehle/supercookie: โš ๏ธ Browser fingerprinting via favicon! URL-encoder for SVG Bootstrap Icons ยท Official open source SVG icon library for Bootstrap GitHub - kognise/water.css: A drop-in collection of CSS styles to make simple websites just a little nicer Toggle light and dark themes in Bootstrap - DEV Deploy your Publish website for free on GitHub Pages - DEV Bootstrap ยท The most popular HTML, CSS, and JS library in the world. GitHub - diegocard/awesome-html5: A curated list of awesome HTML5 resources Fixing PHP SQLite database is locked warning - Unable to execute statement: database is locked [ php ] - KruXoR openstreetmap.org 50 Developer tools to make your life a little easier https://www.mrlacey.com/2020/07/youve-only-added-two-lines-why-did-that.html?m=1 GitHub - ForEvolve/bootstrap-dark: Bootstrap 4 dark theme that supports togging dark/light themes as well. There is no fluff, it changes the color of Bootstrap and that's it, no new thing to learn or unlearn, just Bootstrap, but Dark! Responsive Web Design Online Testing - isResponsive Trianglify.io ยท Low Poly Pattern Generator Grid.js - Advanced table plugin HEAD - A free guide to <head> elements Roots | Modern WordPress Development Tools A Local Dev Tool For Every Project | Lando new.css Synchronized responsive testing, development, inspection |ย Vanamco Gold Price Charts Widgets | GoldBroker.com Trianglify.io ยท Low Poly Pattern Generator Special tags that Google understands - Search Console Help 404 Error Page Codepen ScrollMagic โ™ฅ Demo AOS - Animate on scroll library Font Awesome v4.7.0 - Icon Search Tool Carbon Offers โ€” LowEndTalk Featherlight โ€“ The ultra slim jQuery lightbox. Tailwind CSS - A Utility-First CSS Framework for Rapidly Building Custom Designs HEAD - A free guide to <head> elements API Blueprint | API Blueprint Filtering Data Client-Side: Comparing CSS, jQuery, and React | CSS-Tricks CSS Quickies: CSS Variables - Or how you create a ๐ŸŒžwhite/๐ŸŒ‘dark theme easily - DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป Responsive Slider Timeline Colormind - the AI powered color palette generator Get Waves โ€“ Create SVG waves for your next design Nuxt.js - The Vue.js Framework CodeSandbox: Online Code Editor Tailored for Web Application Development Hover.css - A collection of CSS3 powered hover effects Live.js - One script closer to Designing in the Browser Color this sofa! โ€“ SVG + Blend Mode trick You Might Not Need jQuery CSS Wave Animation with a .png
Search Linx
Search Linx by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code here, mostly for my reference. Also if i find a good link, i usually add it here and then forget about it. more...

Subscribe to weekly updates about things i have added to the site or thought interesting during the last week.

You could also follow me on twitter or not... does anyone even use twitter anymore?

If you found something useful or like my work, you can buy me a coffee here. Mmm Coffee. โ˜•

โค๏ธ๐Ÿ‘ฉโ€๐Ÿ’ป๐ŸŽฎ

๐Ÿชฆ 2000 - 16 Oct 2022 - Boots
Random Quote

minecraft
Random CSS Property

appearance (-moz-appearance, -webkit-appearance)

The appearance CSS property is used to display an element using platform-native styling, based on the operating system's theme. The -moz-appearance and -webkit-appearance properties are non-standard versions of this property, used (respectively) by Gecko (Firefox) and by WebKit-based (e.g., Safari) and Blink-based (e.g., Chrome, Opera) browsers to achieve the same thing. Note that Firefox and Edge also support -webkit-appearance, for compatibility reasons.
appearance css reference