Using Javascript / jQuery to change CSS based on text value

OK Stackoverflowians, here's a riddle for the day.

I have a weather sidebar widget on a WordPress site that interferes with all my data from the Google Weather API. I would like to set the gradient from RED to BLUE, and then, by the magic of the javascript gods, look at the temperature value.

Higher number = closer to RED
Lower Number = closer to BLUE -

Is there anything that can do this? Or do I need to start from scratch?

+4
source share
3 answers

You can express color using two dimensions:

var max_temp = 50, // set maximum expected temperature min_temp = -10, // set minimum temperature temp_range = max_temp - min_temp, // calculate range temp_rating = ((temp - min_temp) / temp_range) * 255 // express value in terms of the range multiplied by 255 red = temp_rating, // more temp = more red blue = 255 - temp_rating; // more temp = less blue 

Then your CSS color will be as follows:

 rgb(red, 0, blue) 

I don’t know if this will please, though :-)

+2
source

You can do this using jQuery :

 $(document).ready(function(){ $('#temp')​.change(function(){ if($(this).val() < 47) $(this).removeAttr("class").addClass("cold"); else $(this).removeAttr("class").addClass("hot"); })​; }); 

CSS

 ​.hot {background: #f00; color: #fff;} .cold {background: #00f; color: #fff;} 

HTML

 ​<input type="text" id="temp"​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ />​​​​​​​​​​​​​​​ 

Hope this helps! FYI, fiddle . Alternatively, you can use the .keyup() function too! :)

0
source

Here's the JSFiddle adaptation from a similar implementation that I did to generate colors for JavaScript thermal diagrams.

You pass the value, the minimum and maximum value to determine the range, which then interpolates and generates a hexadecimal value based on the first, last and middle colors defined in the script. This is from red to green, given a range of 0 - 50, but it also processes values ​​outside the range, providing the most extreme color. Perhaps you can change this to suit your requirements?

0
source

All Articles