Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Change span text color based on numeric value

I'm trying to build a review system in WP with Advanced Custom Fields, but I can't solve this. I want to change the color of a score based on the number. For example: if the writer puts 0-40 as score it has to be changed to red; if the writer puts 40-60 it has to be changed to orange; if the writter puts 60-80 it has to be green...

HTML:

<div class="r-summary">
   <span id="score">
      <?php the_field('score'); ?> */HERE GOES THE NUMBER WITH THE SCORE
   </span>
 </div>
like image 581
Neks Avatar asked Aug 22 '15 16:08

Neks


2 Answers

Fiddle: http://jsfiddle.net/5zdemo3j/

(change the score in the HTML section and "Run" to see changes)

$(function () {
    // Score Color
    var score = parseInt($('#score').text().trim());
    var color = 'red';
    if (!isNaN(score)) {
        if (score >= 40) {
            color = 'orange';
        }
        if (score >= 60) {
            color = 'green';
        }
        $('#score').css('color', color);
    }
});
like image 143
Bitwise Creative Avatar answered Nov 03 '22 01:11

Bitwise Creative


Use this function in document.ready state if you are loading the score with PHP so the span will be edited when the document is loaded:

$(document).ready(function() {
  var score = parseInt($("#score").text());
  if (score <= 40) {
    $('#score').css('color', 'red');
  } else if (score > 40 && score <= 60) {
    $('#score').css('color', 'orange');
  } else if (score > 60) {
    $('#score').css('color', 'green');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="r-summary">
  <span id="score">
     50
   </span>
</div>

I used 50 as a score example here, and you can change it and see the results.

You will proceed like this:

  • Get the score from the span.
  • According to the score value, change the color of the span.
like image 41
cнŝdk Avatar answered Nov 03 '22 01:11

cнŝdk