Weather app! How to change the background according to the temperature?

Hello everyone!

I just finished my local weather app (you can find the project here:, but I don’t know how to change the background when the temperature is in a certain range. I tried using the “if statement” and the “while loop”.

Can someone help me? Any feedback or advice would be greatly appreciated!

How many temp ranges did you have in mind? I’m not 100 percent sure if this is the most efficient way to do this but you could use if and else if statements to check to see if the current temp is in a specific range, ex: if (temp > 50 && temp < 70) and then change the background with jquery’s “.css” method.

I made you a simplified example where i change the background color

// inside render()
var backgroundImage = chooseImage(wd.main.temp)
$("body").css("background-image", "url(" + backgroundImage + ")");

// chooseImage() definition
function chooseImage(temp) {
    if (temp > 50) {
         return 'bg50.jpg'
    if (temp > 30) {
         return 'bg20.jpg'

Thank you for your answers! Especially to @marzelin and @Dolpoteg.

I tried to use both of your solutions but it still not working. I would love to change the “container” color and I really don’t understand what I’m doing wrong.

Thank you again for your precious advises!

you have to use . before container becuse you are looking for a class

like this:


also you’ll have to change your code so you will make a function call after you get the temperature and be sure you pass an integer, if the api you are using is sending you a string you will have to convert it to a number

function changeContainerBgColor(temp){
  var color='rgba(244,244,244,0.4)'
  if(temp > -10 && temp <= 0){
    color='rgba(50,97,214, 0.4)'
  }else if(temp > 1 && temp <= 15){
    color='rgba(244,244,244, 0.4)'
  }else if(temp > 16 && temp <= 25){
    color='rgba(244,204,0, 0.4)'
  }else if(temp > 26){
    color='rgba(216,128,48, 0.4)'

Actually the API I’m using is sending me numbers, it returns something like this:

“main”: {
“temp”: 286.164,
“pressure”: 1017.58,
“humidity”: 96

giulippi I think your API is returning temp as Kelvin. You might want to convert it to Fahrenheit and or Celsius. Set some var’s to = Fahrenheit and Celsius then list out the conversion. I think the conversion is:
Fahrenheit = (kelvin*(9/5)-459.67).toFixed(1);
Celsius = (kelvin-273).toFixed(1);

Try using that. You might check my calculations though. Also the .toFixed sets the number of decimals, I set to 1 but you could use as many as you want.

I hope I helped a little.

1 Like

@giulippi If you’re using the recommended openweathermap api check this out: You need to use the &units=imperial/metric in order to get your temp in F or C

1 Like