let count = 0; let counter = document.querySelector("#number-el"); let btns = document.querySelectorAll(".btn"); let decreaseEl = document.querySelector(".decrease-el"); let increaseEl = document.querySelector(".increase-el"); btns.forEach(function(btn) { btn.addEventListener("click", function() { if (decreaseEl) { count--; console.log(count); } else if (increaseEl) { count++; } else { count = 0; } if (count < 0) { counter.style.color = "green"; } if (count > 0) { counter.style.color = "red"; } if (count === 0) { counter.style.color = "yellow"; } counter.textContent = count; }); });
<div class="container"> <div> <p id="counter-el">COUNTER <div id="number-el">0</div> </p> <button class="btn increase-el">INCREASE</button> <button class="btn reset-el">RESET</button> <button class="btn decrease-el">DECREASE</button> </div> </div>
It’s a program to perform a counter which increases, decreases, and reset the count from 0, but the output that I am getting is only increasing with a negative sign
i access classes inside if statement directly. is it possible to directly access classes without using event objects.
Advertisement
Answer
Added values in button and used switch/case
let count = 0; let counter = document.querySelector("#number-el"); let btns = document.querySelectorAll(".btn"); let decreaseEl = document.querySelector(".decrease-el"); let increaseEl = document.querySelector(".increase-el"); btns.forEach(function(btn) { btn.addEventListener("click", function(e) { switch (e.target.value) { case "INCREASE": count++; break; case "DECREASE": count--; break; case "RESET": count = 0; break; default: break; } if (count < 0) { counter.style.color = "green"; } if (count > 0) { counter.style.color = "red"; } if (count === 0) { counter.style.color = "yellow"; } counter.textContent = count; }); });
<div class="container"> <div> <p id="counter-el">COUNTER <div id="number-el">0</div> </p> <button class="btn increase-el" value="INCREASE">INCREASE</button> <button class="btn reset-el" value="RESET">RESET</button> <button class="btn decrease-el" value="DECREASE">DECREASE</button> </div> </div>