I made this counter but I wish to color the id="clicks" based on positive or negative value also append text based on this.
var clicks = 0;
function clickplus() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
var clicks = 0;
function clickless() {
clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
#btn_plus{
background-color: #04AA6D; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;}
#btn_less{
background-color: red; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;}
<body style="background-color:#F0F0F0">
<center>
</br></br></br>
<h1>
<p style="color:#002244">COUNT: <a id="clicks">0</a></p>
</h1>
<button id="btn_plus" type="button" onClick="clickplus()">+1</button>
<button id="btn_less" type="button" onClick="clickless()">-1</button>
</center>
</body>
Can somebody help? id="clicks" color red if negative and color green if positive also show text positive/negative based on this.
3
Answers
Use
document.getElementById("clicks").style.color = color;
Here is a modern script using
delegation
eventListener
and proper CSS (center
is very deprecated)Also I swapped the buttons since humans normally see negative values left of 0
Simply create a CSS class such as
.negative
that containscolor: red
. Then you can useelement.classList.toggle()
to add or remove the class depending if the statement is true or false. The textpositive
and negativecan be added as pseu-element through CSS using
::afterand
content`: