psj01 psj01 - 13 days ago 4
CSS Question

How can I change the color of a progress bar using javascript?

Please see my code so far (jsfiddle).

I am trying to change the color of the progress bar once it reaches max capacity.

How can I accomplish this?

HTML code:

<textarea></textarea>
<span id="characters">255 left</span>

<br>
<progress id="myProgress" value="0" max="255">
</progress>


JS code:

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
var max = 255;
var cs = $(this).val().length;
document.getElementById("characters").innerHTML= max-cs + " left..";
document.getElementById("myProgress").value = cs;
if (event.which < 0x20) {
return;
}
if (cs == max) {
event.preventDefault();
// make the color of progress bar red here!!
}

}

Answer

add progress::-webkit-progress-bar in css it changes color and also define it jquery. if(cs==max) $('#myProgress').css("background-color", "red");

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
	 var max = 255;
    var cs = $(this).val().length;
    if(cs>max) $(this).val($(this).val().toString().substring(0,max));
    document.getElementById("characters").innerHTML= max-cs + " left..";
    document.getElementById("myProgress").value = cs;
    if (event.which < 0x20) {
        return;
      }
      if(cs>=max)
      $('#myProgress').css("background-color", "red");
    if (cs >= max) {
        event.preventDefault();
        // make the color of progress bar red here!! 
      }     
      
}
progress[value] {color:red} /* IE10 */
progress::-webkit-progress-bar-value {background:red}
progress::-webkit-progress-value {background:red}
progress::-moz-progress-bar {background:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea></textarea>
<span id="characters">255 left</span>

<br>
<progress id="myProgress" value="0" max="255">
</progress>