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

You Asked,
We made it!

fix japanese keyword hack

Step by Step Video Tutorials on trending topics in software development

Yes I am Curious »

AR in Websites – Top 3 Platforms for Bringing Augmented Reality to Your Web Experience

As technology advances, augmented reality (AR) is no longer limited to gaming or social media apps. Integrating AR into websites...

Know More »

Webhook Explained for Beginners: Everything You Need to Know

In the world of APIs, automation, and modern web applications, the term “webhook” often comes up. But what exactly is...

Know More »