I was experimenting with creating a dark/light mode toggle using jQuery and I came up with this solution
One thing that puzzles me is when I remove the 'darkmode' class, instead of adding the 'whitemode' class, it simply adds the attribute (class) without the actual class name. Surprisingly, it still functions properly. Can anyone explain this behavior?
index.html
<!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="darkmode.css">
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/aa7be85309.js" crossorigin="anonymous"></script>
<title>Dark Mode</title>
</head>
<body class='whitemode'>
<div class="darkmode"></div>
<div class="container">
<div class="content">
<h1>Light / Dark mode</h1>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui non numquam excepturi corrupti vel dicta commodi veritatis eaque eius harum blanditiis voluptatem dolores itaque iure ex, molestias expedita rem velit?
</div>
<div class="toggle-btn" id='toggle-btn'><i class="fa-regular fa-moon"></i></div>
<script src="main.js"></script>
</div>
</body>
</html>
darkmode.css
body{
transition-duration: .3s;
}
.container{
width: 500px;
margin: auto;
font-family: sans-serif;
}
.toggle-btn{
padding: 3px 5px;
border: 1px solid red;
border-radius: 3px;
}
#toggle-btn{
position: fixed;
top: 40px;
right: 40px;
cursor: pointer;
}
body.whitemode{
background-color: #fff;
color: black;
transition-duration: .3s;
}
body.darkmode{
background-color: black;
color: #ffffff;
transition-duration: .3s;
}
.border{
border-color: #fff;
}
main.js
$(document).ready(function(){
$("#toggle-btn").click(function(){
if($("body").hasClass('whitemode') ? ($("body").toggleClass('whitemode'), $("body").toggleClass("darkmode"), $("#toggle-btn").toggleClass("border")) : ($("body").toggleClass("darkmode"), $("#toggle-btn").toggleClass("border")));
});
});