PDA

View Full Version : Want text red when counter is negative, green when positive

flatirondave
07-06-2011, 07:01 PM
I'm just starting out learning and have sort of given myself a couple of basic problems to solve. I pretty quickly found something that's apparently hard to Google.

I've made a page that shows a counter number, starting at 0, with buttons that will increase or decrease the number by 1 or 10.

So I'd like to figure out how to show that number in red when it is a negative number and in green when it is a positive number. I've tried a couple of things, including an if... else, but here's my latest crack:

var counter=0;

function countUp() {
lastCounter=counter;
counter++;
display();
}
function countDown() {
lastCounter=counter;
counter--;
display();
}
function tenUp() {
lastCounter=counter;
counter+=10;
display();
}
function tenDown() {
lastCounter=counter;
counter-=10;
display();
}
function lastNumber() {
counter=lastCounter
document.getElementById("number").innerHTML=lastCounter;
}

function display () {
number=counter+'';
switch(counter) {
case counter== 0;
document.getElementById("number").innerHTML=number.fontcolor(white);
break;
case counter> 0;
document.getElementById("number").innerHTML=number.fontcolor(green);
break;
case counter< 0;
document.getElementById("number").innerHTML=number.fontcolor(red);
break;
} //end switch
} //end display

I suspect that what I'm doing totally wrong has to do with how I'm describing the case or with calling one function inside another function, since it works up until I start messing with that (had the document.getElementByID stuff in the countUp, countDown, etc., functions before) but I don't know. Thanks in advance for any help you can offer.

Philip M
07-06-2011, 07:38 PM
A switch statement is not suitable here, just if....else. In any case your syntax is quite wrong.

function display() {
document.getElementById("number").innerHTML = counter;
if (counter == 0) {document.getElementById("number").style.color ='white'}
if (counter > 0) {document.getElementById("number").style.color = 'green'}
if (counter < 0) {document.getElementById("number").style.color = 'red'}
}

Note that Javascript is case-sensitive - document.getElementByID will throw an error.

The fontcolor() method returns the string embedded in the <font> tag. For this reason it is deprecated and no longer used. Use css instead.

"If you make it idiot proof, they'll build a better idiot"