Problem:
I was trying to find a way to make a dark / light mode with jquery.
And I came up with this
The thing I don’t understand is when I remove the ‘darkmode’ class, it should add ‘whitemode’ class, but instead it adds only the attribute (class) without the actual class. Yet It works perfectly. Why is that?
index.php
<!DOCTYPE html>
<html lang="pt-br">
<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")));
});
});
Solution:
It works because background-color: #fff; color: black;
are the default styles for the body element in the vendor stylesheet.