Using Javascript/jQuery to modify CSS based on Text Value

OK Stackoverflowians, Here’s the riddle for the day.

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

Read More

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

Is there anything out there that can do this? Or would I have to start from scratch?

Related posts

Leave a Reply

3 comments

  1. You could express the color using two dimensions like this:

    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 would become:

    rgb(red, 0, blue)
    

    No idea if it will look nice though 😉

  2. 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, the fiddle. Alternatively, you can use .keyup() function too! 🙂

  3. Here’s a JSFiddle of an adaptation from a similar implementation I made to generate colours for JavaScript heatmap charts.

    You pass in a value, a minimum and a maximum value to define a range, which then interpolates and generates a hex value given the first, last and midpoint colours defined in the script. This goes from red to green, given a range of 0 – 50, but it also handles out-of-range values by providing the most extreme colour. Maybe you can modify this to suit your requirements?