DEV Community

Cover image for How to toggle dark mode
Yigit S
Yigit S

Posted on • Updated on

How to toggle dark mode

Hi all. In this post, I'll show you how to create a toggle button to switch between dark and light mode.

HTML

<!DOCTYPE html>
<html lang="en" data-theme ="light">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, 
initial-scale=1.0">

    <link rel="stylesheet" href="styles.css">
    <script src="script.js" defer></script>

    <title>toggleDark</title>
</head>
<body>

    <div class="toggle-container">
        <input type="checkbox" id="toggle" name="toggle">
        <label for="toggle"></label>
    </div>

    <h1>Long Live Rock 'n Roll</h1>
    <p>Rock and Roll ain't noise pollution!
Rock and Roll will never die!
I like that old time Rock and Roll!</p>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CSS

*{
    box-sizing: border-box;
}

body{
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;

    min-height: 100vh;
    flex-direction: column;
    padding: 5rem;
    transition: background 0.4s linear, color 0.4s linear;
    font-size: 2rem;
}

body.dark{
    background: #201e1e;
    color: white;
}

label{
    user-select: none;
    cursor: pointer;
    background-color: #201e1e;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: inline-block;
    transition: background 0.4s linear;
}

body.dark label{
    background-color: #ffff;
}

.toggle-container{
    position: fixed;
    top: 10px;
    right:10px
}

input{
    visibility: hidden;
}
Enter fullscreen mode Exit fullscreen mode

Javascript

const toggle = document.getElementById("toggle")

toggle.addEventListener('change', (e)=>{
document.body.classList.toggle('dark',e.target.checked)

}) 

Enter fullscreen mode Exit fullscreen mode

Final Result


I hope you find this tutorial useful. See you on the next article.
Here's the Source Code on GitHub
Here's the YouTube Video where I code it from scratch.
Check it out on CodePen


Follow me on

Top comments (0)