javascripthtmldomincrementdecrement

Increment & Decrement not working as intended in Javascript


The unexpected behavior I'm getting is when clicking the donate or undonate button. It takes 2 clicks initially for the tracker to display the incremented or decremented number despite the color change happening immediately. Once it does change the number on the second click, the 3rd click and on using the same button will work normally to increment or decrement.
In addition to that, if you switch the button you're clicking to the other, it still performs the previous action first.
Hopefully this explanation of the issue makes sense. Appreciate any direction that can be given as I am still new!

HTML:

<!DOCTYPE html>
<head>
    <link rel="stylesheet" href='style.css' />
    <title>Front-End Portfolio Project</title>
</head>
<body>
    <h1>Donate Food 2 Me</h1>
    <p id="container"></p>
    <p id='caption'>food quantity</p>
    <button id="donate">Donate</button>
    <button id="undonate">Un-Donate</button>
    <script type="text/javascript" src='main.js'></script>
</body>
</html>

JS:

const donateButton = document.getElementById("donate");
const unDonateButton = document.getElementById("undonate");
const tracker = document.getElementById("container");
var i = 0;

tracker.innerHTML = i;

donate = function(){
    donateButton.style.backgroundColor = 'red';
    tracker.innerHTML = i++;
}

undonate = function(){
    unDonateButton.style.backgroundColor = 'blue';
    tracker.innerHTML = i--;
}

donateButton.addEventListener("click", donate);

unDonateButton.addEventListener("click", undonate);

Solution

  • The only mistake you made is ignoring the difference between i++ and ++i (i-- and --i).

    Change your code as below (You can see the result here):

    donate = function(){
        donateButton.style.backgroundColor = 'red';
        tracker.innerHTML = ++i;
    }
    
    undonate = function(){
        if (i > 0) {
            unDonateButton.style.backgroundColor = 'blue';
            tracker.innerHTML = --i;
        }
    }