Javscript - if else problem (changing style color if a number is negative or positive)

Viewed 79

I created a simple program that contains two buttons "higher" that adds 1 to the number and "lower" that subtracts 1 from the same number. When the number is negative it must change its color to red and when it is positive it must become green but that doesn't work. Here's the javascript

        let num = 0;
        function higher() {
            num ++;
            document.getElementById("number").innerHTML = num;
        }
        function lower() {
            num --;
            document.getElementById("number").innerHTML = num;
        }

        // (conditionals statements below do not work for an unknown reason)
        if (num < 0) {
            document.getElementById("number").style.color = "red";
        } else if (num > 0) {
            document.getElementById("number").style.color = "green";
        }

Here's the Html body

<body>
    <div class="counter">
        <div id="number">0</div>
        <button onmousedown="higher()" class="btn_high">Higher</button>
        <button onclick="lower()" class="btn_low">Lower</button>
    </div>
</body>

Here's an example of how the program should look https://romeojeremiah.github.io/Counter-Project/

2 Answers

Nothing is calling the code at the end, so you'll never see those results. Try wrapping your conditional in a function, then calling that function at the end of higher() and lower(). For example:

let num = 0;

function higher() {
    num++;
    document.getElementById("number").innerHTML = num;
    checkNumberAndApplyStyles();
}

function lower() {
    num--;
    document.getElementById("number").innerHTML = num;
    checkNumberAndApplyStyles();
}

function checkNumberAndApplyStyles() {
    if (num < 0) {
        console.log('under')
        document.getElementById("number").style.backgroundColor = "red";
    } else if (num > 0) {
        document.getElementById("number").style.color = "green";
    }

You have to put the conditional statement inside a function and then call that function on each button click like this

    let num = 0;

    function higher() {
        num ++;
        document.getElementById("number").innerHTML = num;
        colorChange();
    }

    function lower() {
        num --;
        document.getElementById("number").innerHTML = num;
        colorChange();
    }

    function colorChange(){
        if (num < 0) {
            document.getElementById("number").style.color = "red";
        } else if (num > 0) {
            document.getElementById("number").style.color = "green";
        }
    }
Related