Integrated Tech Solutions

Create Dark/Light Color Modes in PHP website With Bootstrap & Jquery

By - Admin, Updated on May 7, 2023

With Bootstrap 5.3, Color modes are now supported in Bootstrap

How Does Color Mode Work in Bootstrap

To set the color mode in bootstrap, we need to specify the color mode with the data-bs-theme attribute

<!doctype html>
<html data-bs-theme="dark" >

Include Bootstrap CSS & JS

<!--Add this in head--->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<!--Add this in footer-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

Include Jquery Script in head

<!--Add this in head-->
<script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>

Create the switch in bootstrap

<input class="form-check-input" type="checkbox" role="switch" id="flexSwitchCheckDefault">

Using Cookies to Remember Color Mode

Javascript function to set cookies

<script>
	function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  let expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
</script>

Save Preferred Color mode in Cookies

<script>
$( document ).ready(function() {
    $("#flexSwitchCheckDefault").change(function(){
        
        var colorMode = $('html').attr('data-bs-theme');

        if(colorMode  == 'light'){
            //$(this).attr('color-mode','dark');
            $('html').attr('data-bs-theme','dark');
			setCookie('site-theme', 'dark', 7);
        }
        if(colorMode == 'dark'){
          //  $(this).attr('color-mode','light');
            $('html').attr('data-bs-theme','light');
            setCookie('site-theme', 'light', 7);
        }
    });
});
</script>

Check cookies in PHP

<html <?php if($_COOKIE['site-theme'] == 'dark'){ echo 'data-bs-theme="dark"';}else{echo 'data-bs-theme="light"';}?> >

Popular Articles on Bootstrap

Keep Reading

👋 Hi, Find this Helpful? There is More

20 Most asked Odoo Interview Questions

Odoo Accounting Interview Questions

Know More »
shopify sections and blocks

How to create Custom Sections in Shopify[Dawn Theme]

Are you looking to customize your Shopify store beyond the standard templates and themes? Do you want to create unique...

Know More »
fix japanese keyword hack

Looking for Video Tutorials?

Explore Our Youtube Channel for in-depth Tutorials

Yes I am Curious »