Day / Night Mode with JavaScript
Lots of applications, nowadays, have a feature to change day and night modes. Let’s see how to make one using HTML, CSS, JS.
This feature is quite straight forward so I am going to explain why to implement of what it does. Having said that let’s get into the code. (I tried to omit the unnecessary codes)
Code
HTML
<body id="top">
<!-- Nav -->
<nav>
<div class="mode">
<i class="fas fa-sun"></i>
<label>
<input id="toggle" type="checkbox">
<span class="toggle-circle"></span>
</label>
</div>
</nav>
<!-- Home -->
<section id="home">
<h1>Custom</h1>
<h2>welcome</h2>
</section>
</body>
CSS
/* html에 전역변수 지정 */
:root {
--bg-light-alt: rgba(0, 0, 0, 0.4);
--font-primary: aliceblue;
--font-alt: #000;
--bg-primary: transparent;
--btn-primary: rgb(255, 92, 92);
--btn-secondary: #03dac5;
}
/* data-theme='dark' 속성이 존재 할 때 야간 모드로 바꾸어 줌 */
[data-theme='dark'] {
--bg-light-alt: rgba(0, 0, 0, 1);
--font-primary: rgb(218, 58, 250);
--font-alt: rgb(218, 58, 250);
--bg-primary: rgba(0 0 0 /90%);
--btn-primary: rgb(150, 64, 255);
--btn-secondary: #1b9999;
}
body {
color: var(--on-background);
font-family: 'Comfortaa';
background-color: var(--background);
}
nav {
height: 100px;
background-color: var(--bg-light-alt);
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
padding: 15px;
}
h1 {
font-size: 100px;
font-family: Kaushan Script;
text-align: center;
color: var(--font-alt);
}
h2 {
font-size: 40px;
text-align: center;
color: var(--font-alt);
}
/* mode */
.mode {
display: flex;
align-items: center;
color: var(--font-primary);
font-size: 1.2rem;
}
.mode span {
margin-right: 5px;
}
.mode .fas {
margin: 0 20px;
transform: scale(1.6);
}
/* toggle */
label {
height: 30px;
width: 60px;
border-radius: 30px;
}
input {
display: none;
}
input:checked + span {
background-color: gray;
}
input:checked + span::before {
left: 30px;
}
.toggle-circle {
height: 100%;
width: 100%;
display: block;
border-radius: 30px;
transition: 0.4s ease;
border: 1px solid black;
position: relative;
}
.toggle-circle::before {
content: '';
position: absolute;
left: 0;
height: 28px;
width: 28px;
display: block;
border-radius: 50%;
background-color: aliceblue;
transition: 0.4s ease;
}
I choose CSS global variable to implement this. The first code sets the variable with the default color in the root (HTML). Then on the second code, I made an attribute (this one will be added or deleted in the JS) to signal the change of the mode, and when the attribute is added colors are changed.
JS
const toggle = document.getElementById('toggle')
toggle.addEventListener('change', () => {
if (toggle.checked) {
document.documentElement.setAttribute('data-theme', 'dark')
} else {
document.documentElement.removeAttribute('data-theme')
}
})
Then we can add or remove the attribute using the click event on the toggle button.
Conclusion
In this writing, we have gone through how to implement a day/night mode feature using Vanilla JavsScritp.