0
I tried to create a simple code from a button that, when clicked, leaves the bottom of the page in dark mode.
const btn = document.querySelector(".button");
btn.addEventListener("click", (evt) => {
evt.preventDefault();
let body = document.querySelector("body");
let contador = 0;
body.classList.add("dark")
contador += 1;
if (contador == 2) {
contador = 0;
body.classList.remove("dark");
}
})
.button {
margin: 10% 49%;
padding: 10px 15px;
background-color: transparent;
border: none;
border-radius: 5px;
transition: 600ms all;
border: 2px solid rgb(240, 240, 240);
}
.button:hover {
background: rgb(240, 240, 240);
box-shadow: 2px 2px 7px 0 gray;
}
.section {
margin: 10% 20%;
background: rgb(240, 240, 240);
padding: 10px 15px;
border-radius: 10px;
}
.section__h1 {
font-weight: lighter;
letter-spacing: 1.25px;
}
.section__p {
color: #808080;
}
.dark {
transition: 400ms all;
background: #1d2731;
color: rgb(240, 240, 240)
}
<!DOCTYPE html>
<html lang="pt-BR">
<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="style.css">
<title>texte</title>
</head>
<body>
<button class="button">Dark Mode</button>
<section class="section">
<h1 class="section__h1">Lorem ipsum </h1>
<p class="section__p">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ac nulla eleifend, interdum dolor eget, pretium leo. Sed interdum magna eget diam facilisis, vitae vulputate felis lobortis</p>
</section>
<script src="script.js"></script>
</body>
</html>
when the event callback is invoked, the variable
contador
is initialized at 0, you add 1, then the expressioncontador == 2
always returns false and instructions inside theif
are never executed. Suggestion, put this excerptlet contador = 0;
immediately below the instructionconst btn = document.querySelector(".button");
– Vander Santos