TikTok Tutorial #10 - How to create a Beginner Color Changing Toggle in CSS and Javascript

Learn with us how to create a color-changing toggle using CSS and Javascript!

If you found us on TikTok on the following post, check out this article and copy-paste the full code!

Happy coding! 😻

@creative.tim For the full code, check out the link in bio 🤩 #webdev #programmingexercises #csscoding #javascript ♬ original sound - Creative Tim

HTML Code

Use this code to start your toggle!

<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Test</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="dark-mode">
    <input type="checkbox" class='checkbox' id='checkbox'>
    <label for="checkbox" class='label'>
      <div class="ball"></div>
    </label>
  </div>

  <script src="script.js" charset="utf-8"></script>
</body>

</html>

CSS Code

Continue with the CSS code and add life to your color-changing toggle!

:root {
  --background: linear-gradient(#c8e7ff, #abc4ff);
  --check: #000;
  --ball: #f2eee3;
}

.dark {
  --background: linear-gradient(#5e60ce, #80ffdb);
  --check: #f2eee3;
  --ball: #000;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.dark-mode {
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
  background: var(--background);
  transition: 0.5s;
}

.checkbox:checked + .label .ball {
  transform: translateX(24px);
}

.checkbox {
  opacity: 0;
  position: absolute;
}

.label {
  width: 50px;
  height: 26px;
  background: var(--check);
  border-radius: 50px;
  padding: 5px;
  position: relative;
}

.ball {
  position: absolute;
  top: 2px;
  left: 2px;
  width: 22px;
  height: 22px;
  background: var(--ball);
  border-radius: 50%;
  transition: transform 0.2s linear;
}

Javascript Code

Add the JS code and Voila!


const html = document.querySelector('html')
const check = document.querySelector('#checkbox')

check.addEventListener('change', function(){
  html.classList.toggle('dark')
})

I hope you did find this tutorial useful!

For more web development or UI/UX design tutorials, follow us on:

Other useful resources:

Alexandra Murtaza

Alexandra Murtaza