-1

I done for my jQuery weather from wundground, I just want make color for temperature change auto higher or lower and this code I use but I don't know how use CSS inside jQuery.

function check(temp_c) {
      if (temp_c < 1 && temp_c > 10)
        return '';
      else if (temp_c > 11.25 && temp_c < 33.75) {
        return '';
      } else if (temp_c > 33.75 && temp_c < 56.25) {
        return '';
      } else if (temp_c > 56.25 && temp_c < 78.75) {
        return '';
      } else if (temp_c > 78.75 && temp_c < 101.25) {
        return '';
      } else if (temp_c > 101.25 && temp_c < 123.75) {
        return '';
      } else if (temp_c > 123.75 && temp_c < 146.25) {
        return '';
      } else if (temp_c > 146.25 && temp_c < 191.25) {
        return '';
      } else if (temp_c > 191.25 && temp_c < 213.75) {
        return '';
      } else if (temp_c > 213.75 && temp_c < 236.25) {
        return '';
      } else if (temp_c > 236.25 && temp_c < 258.75) {
        return '';
      } else if (temp_c > 258.75 && temp_c < 281.25) {
        return '';
      } else if (temp_c > 281.25 && temp_c < 303.75) {
        return '';
      } else if (temp_c > 303.75 && temp_c < 326.25) {
        return '';
      } else {
        return '';
      }
    }


var temp_c = data.current_observation.temp_c ;
var temperature = check(temp_c );
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ALI GHASSAN
  • 221
  • 1
  • 4
  • 13
  • What I would do is use your function to return a class name which relates to the temperature then apply it to whatever html element you're using to display the result. Something like: `$("#weather-element").addClass(temperature);` – jazibobs Apr 06 '16 at 09:04

1 Answers1

3

You can simplify your code by just checking the upper bound of the temperature and letting control pass through each condition to set the highest value. Something like this:

function check(temp) {
    temp = parseFloat(temp);
    var tempClass = 'gt326'; // default class for > 326        
    if (temp < 326.25) tempClass = 'lt326'; 
    if (temp < 303.75) tempClass = 'lt303';
    if (temp < 281.25) tempClass = 'lt281';
    // and so on...

    return tempClass;
}

From there you can set the returned class using the addClass() method:

var temp_c = data.current_observation.temp_c ;
var tempClass = check(temp_c);
$('#myElement').addClass(tempClass);

Working example

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339