Search code examples
javascripthtmlvar

Coloring Text with JS and negative numeric variable ranges


Any idea on how to use negative numeric values for variable ranges?

var colorMatch = {
'0-19'     : 'red',
'20-59'    : 'orange',
'60-100'   : 'green'

};

I've been using this JS code from previous question to color text with variable numeric ranges

https://stackoverflow.com/a/31805767/7922942

Which links to this Fiddle

For example i'm trying to '-5-0' : 'blue', etc

Any thoughts/work arounds?


Solution

  • I would suggest changing the structure of the mc object as follows:

    var mc = {
      blue: [-10, -1],
      red: [0, 19],
      orange: [20, 59],
      green: [60, 100]
    };
    

    This way, you're not having to parse the range from a string.

    $(document).ready(function(){
      
      var mc = {
        blue: [-10, -1],
        red: [0, 19],
        orange: [20, 59],
        green: [60, 100]
      };
      
      function between(x, min, max) {
        return x >= min && x <= max;
      }
    
    
      
      var dc;
      var first; 
      var second;
      var th;
      
      $('p').each(function(index){
        
        th = $(this);
        
        dc = parseInt($(this).attr('data-color'), 10);
            
        $.each(mc, function(color, [min, max]) {
          first = parseInt(min, 10);
          second = parseInt(max, 10);
    
          if(between(dc, first, second)){
            th.addClass(color);
          }
        });
      });
    });
    .blue {color:blue}
    .red {color:red}
    .orange {color:orange}
    .green {color:green}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p data-color="-5">Lorem -5</p>
    <p data-color="19">Lorem 19</p>
    <p data-color="25">Lorem 25</p>
    <p data-color="55">Lorem 55</p>
    <p data-color="60">Lorem 60</p>
    <p data-color="61">Lorem 61</p>
    <p data-color="100">Lorem 100</p>