Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading