Changing Color of Text Based on Variable

144
February 26, 2022, at 06:30 AM

Trying to make a simple increase/decrease counter. When var n is < 0 it changes to red, and same for ==, but when its greater than it stays black..am i missing something?

var n = 0
function increase() {
    n = n + 1
    document.getElementById('num').innerHTML = n
    if (n > 0) {
        document.getElementById('num').style.color = '#013220'
    }
    else if (n < 0) {
        document.getElementById('num').style.color = '#ff0000'
    }
    else if (n == 0) {
        document.getElementById('num').style.color = '#000000'
    }
}

no error messages.

Answer 1

this is a way to do it:

var n = -2. // let me start with a negative number so we can see that color too
function increase() {
    n = n + 1;
    let color = '#000000'; // default color is black
    if (n > 0){
        color = '#CC0'; // yellow when n > 0 
    }
    if (n < 0){
        color = '#ff0000'; // red when n < 0 
    }
    const elem = document.getElementById('numWrapper')
    elem.innerHTML = n
    elem.style.color = color
}
<div id='numWrapper'>-2</div>
<button onClick='increase()'>Increase</button>

Rent Charter Buses Company
READ ALSO
Track position and changing css style

Track position and changing css style

How do you calculate opacity from 0 to 1 depending on the scroll for text elements?

120
TailwindCSS: Combining 2 transitions properties

TailwindCSS: Combining 2 transitions properties

I wanna have transition-transform and transition-shadow, not neither transition-all nor only onePutting the two not effecting, i couldn't find doc for it, i tried playing around like: transition-[transform, shadow] and obviously didn't work

167
How to implement animated javascript background in HTML

How to implement animated javascript background in HTML

I'm attempting to do an animated background like https://benscottdev uses

120
Angular Button Click Registering on Both the Button and Div Underneath

Angular Button Click Registering on Both the Button and Div Underneath

Whenever I click on my #dropDown button, it functions as intended and opens the dropdown menu; however, the click also hits the underneath which is also clickableI don't want the button click event to also hit the div underneath, as that is not the intended...

139