0

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.

3
  • 1
    If n starts at 0 and only increases, it will never be red. It will only ever be black or #013220 Commented Feb 8, 2022 at 8:04
  • Your code works as it is. Only that #013220 is quite near to #000000, maybe you just can't see the difference ..? Commented Feb 8, 2022 at 8:06
  • 1
    It may also never be 0 either, since the first run of increase will always add 1 to n, so n will never be 0 when increase is run. Commented Feb 8, 2022 at 8:09

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.