Creating a Dark/Light theme Toggle using CSS & Javascript

Creating a Dark/Light theme Toggle using CSS & Javascript

·

2 min read

Hey Devs, Today in this post we’ll be Creating a Dark/Light theme Toggler using CSS & Javascript. To be fair, my describing skills arent that professional, so you would compromise on that. I will try my best. hope you enjoy this post.

Adding a website's dark/light mode feature has been rising. You could have already seen them on different websites. This feature enhances the quality and user satisfaction. Various websites like YouTube, and Facebook have introduced such dark mode features.

Let’s head to create it.

Demo Clickto watch the demo!

Dark Mode Toggle Button in JavaScript (source code)

HTML Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
  </head>

  <div class="all">
    <div class="container">
        <input type="checkbox" id="toggle">
    </div>

    <p>
        Lorem30
    </p>
   </div>

    <script src="script.js"></script>
  </body>
</html>

CSS Code Let’s add some CSS

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
body{
    padding: 30px;
}
.all{
  width: 400px;
  margin: 40px auto;
}
.container{
    width: 100%;
    height: 40px;
    margin-bottom: 20px;
    position: relative;
}
#toggle{
    -webkit-appearance: none;
    appearance: none;
    height: 32px;
    width: 65px;
    background-color: #15181f;
    position: absolute;
    right: 0;
    border-radius: 20px;
    outline: none;
    cursor: pointer;
}
#toggle:after{
    content: "";
    position: absolute;
    height: 24px;
    width: 24px;
    background-color: #ffffff;
    top: 5px;
    left: 7px;
    border-radius: 50%;
}
p{
    font-family: "Open Sans",sans-serif;
    line-height: 35px;
    padding: 10px;
    text-align: justify;
    }
.dark-theme{
    background-color: #15181f;
    color: #e5e5e5;
}
.dark-theme #toggle{
    background-color: #ffffff;
}
.dark-theme #toggle:after{
    background-color: transparent;
    box-shadow: 10px 10px #15181f;
    top: -4px;
    left: 30px;
}

JavaScript Code

Javascript would be doing the main work, it will change the theme when the toggle button will be clicked by adding and removing classes given in CSS. We have linked the CSS codes of the dark mode added above in the switch.

document.getElementById("toggle").addEventListener("click", function()
{
    document.getElementsByTagName('body')[0].classList.toggle("dark-theme");
});

Congratulations! You have now successfully created our Dark/Light theme Toggler using CSS & Javascript

Check out my other amazing CSS and Javascript tutorials:

1. 5+ Free CSS Box-shadow Generators to save your time 2. Responsive footer design in HTML and CSS 3. How to change the background colour using javascript

My Website: codewithayan, see this to check out all of my amazing Tutorials.