简体   繁体   中英

How to change button background on given condition

I was trying to build a really basic counter with JS. I wanted the "decrease" button to be disabled and gray-colored when the counter was on 0, so it can't go on negative numbers.

The default background color of the button is already gray, and it turns coral as soon as you click on the "increase" button. The problem is, when you decrease the number to 0, it doesn't turn gray until you click the button once again when it is already on 0 (so, if you didn't click twice, technically it wouldn't turn gray ever).

I know that the problem is that the color change is inside the click event, but I don't know how to make it turn gray as soon as it reaches 0 after increasing and decreasing the number.

I'm trying not to use JQuery or React for this, so I was wondering if there was a way in vanilla JS.

This is the CodePen for the project.

 const addBtn = document.querySelector(".add-btn"); const susBtn = document.querySelector(".sus-btn"); const number = document.querySelector(".number"); let count = 0; function listeners() { addBtn.addEventListener("click", addNumber); susBtn.addEventListener("click", susNumber); } function addNumber() { count += 1; number.innerText = count; if (count.== 0) { susBtn;disabled = false. susBtn.style;backgroundColor = "coral". } } function susNumber() { if (count === 0) { susBtn;disabled = true. susBtn.style;backgroundColor = "grey"; } else { count -= 1. number;innerText = count; } } listeners();
 <body> <div class="main-container"> <div class="background"> <div class="title"> COUNTER! </div> <div class="screen"> <div class="number"> 0 </div> </div> <div class="buttons"> <button class="add-btn"> + </button> <button class="sus-btn"> - </button> </div> </div> </div> </body>

Your susNumber function just needs a little re-write:

function susNumber() {
    count -= 1;
    number.innerText = count;
    if (count === 0) {
        susBtn.disabled = true;
        susBtn.style.backgroundColor = "grey";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM