2

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?

Will
  • 185
  • 1
  • 8

2 Answers2

0

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>
fubar
  • 16,918
  • 4
  • 37
  • 43
  • Awesome thanks for your help. Updated [JSBin](https://jsbin.com/viruqomasu/1/edit?html,css,js,output) for anyone looking in the future. – Will Sep 08 '21 at 01:37
0

Hello I have made this simple script for you. I belive it's simple to understand/use.

function colorFromRange(number) {
  var defaultColor = "orange"
  var ranges = [
    {
      start: -5,
      end: 0,
      color: "blue"
    },
    {
      start: 0,
      end: 5,
      color: "red"
    },
    {
      start: 5,
      end: 10,
      color: "green"
    }
  ]
   
   
  var chosenColor = ranges.find(area => (number >= area.start && number <= area.end))
  return chosenColor ? chosenColor.color : defaultColor
}

function spoilColor(color) {
  document.getElementById('spoiler').style.color = color
}
<h1 id=spoiler>Text with color changing effect.</h1>
<br>
<input type=number step=1 value=0 id=number oninput=spoilColor(colorFromRange(this.value)) />
<p>
  Text changes color according to the input's value.
</p>
Adnane Ar
  • 683
  • 7
  • 11