Reputation: 3
I have a web application I'm working on that does addition between integers. I have two functions called num1() and num2() that get the two integers as input from the user. I want to change the resulting output text color if the sum of the two integers is negative. How do I do this with JavaScript?
I've seen a lot of jQuery examples, but I want to do this with solely JavaScript.
function addIntegers() {
var sum = num1() + num2();
if(sum < 0) {
document.getElementById('display').innerHTML=
"Result: " + sum;
}
else {
document.getElementById('display').innerHTML=
"Result: " + sum;
}
}
Upvotes: 0
Views: 4341
Reputation: 1683
DOM objects have a .style
object that will let you set whatever you would like. In your case, you're looking for the color
property, so your function would look like this:
function addIntegers() {
var sum = num1() + num2();
var displayObj = document.getElementById('display');
displayObj.innerHTML = "Result: " + sum;
if (sum < 0)
displayObj.style.color = 'red'
else
displayObj.style.color = 'green'
}
You'll notice I set the element in question to an object so you don't have to call getElementById
multiple times. Also, since you'll always be writing the sum, you can remove that from the if
statement, as you only care about changing the color there.
Upvotes: 2