Build A JS Dark Theme Switcher

Hi devs, today we'll be building a simple javascript dark theme switcher. It's really more of a basic way to do it for those that are just beginning and want to get their hand dirty with some javascript. So with that said, let's dive in.

The first thing I'm going to put down as code is our HTML markup

HTML

<div class="btn">
<button>Click Me</button>
</div>

And that should be all for our HTML.

Now to get the CSS, basically, what we want to do here is center everything so that we have just the button in the middle of the page and give the button some style too.

CSS

body , html {
max-height: 100%;
display: flex;
flex-direction: column; 
align-items: center;
justify-content: center;
}

button {
padding: 10px;
background: transparent;
cursor: pointer;
border: 2px solid brown; // I'm using brown so that the color will stand out no matter the background
}

And the last part is to add a little bit of functionality to the button using javascript. What we're going to do is declare a variable called bgFate and set it to false, and then we are going to use the event listener to listen for when the button is clicked and then use an if else statement to change the background and color of our text.

Javascript

let body = document.querySelector('body');
let btn = document.querySelector('button');

let bgFate = false;

btn.addEventListener('click', ()=> {
  bgFate = ! bgFate;
  if(bgFate === true) {
    body.style.background = 'black';
    btn.style.color ='white';
  }else {
    body.style.background = 'white';
    btn.style.color ='black';
  }
})

And voila, you're done with your theme switcher.

Here's the link to the code pen

Thanks for reading guys, feel free to ask me any questions of your choice.

Until next time.

Peace.