Show the Local Weather - I can't change background

Hi,

This code works perfectly when there are no conditions:
$("body").css("background-image","url('https://images3.alphacoders.com/892/89289.jpg')");

But, when i try to compare the variable currentWeather with other value it falls apart:

if (currentWeather>0) {
  $("body").css("background-image","url('https://images3.alphacoders.com/892/89289.jpg')");
}

The currentWeather is a variable that holds the degrees value from $.getJSON:

  $.getJSON(temperature, function(parse) { 
 // variable currentWeather contains the degrees value
    currentWeather = parse.main.temp.toFixed(1); 
    temperIndex.innerHTML = currentWeather; 
    var isRaining = parse.weather.main;
  })

The full code on codepen : codepen.io/RycerzPegaza/pen/pbzdgY (getJSON works only when you switch the url to non-https, so make sure you won’t open the codepen with https:// prefix).

How to access the value of currentWeather in that if statement so the background change?

Moving everything inside the async functions fixed your problem.

1 Like

Thanks a lot! do you know any source where i could read about it more, so it was obvious to me as it is to you? :smiley:

Honestly, I learned about it from other people telling me like I did you, but googling a bit, I found this link that might be helpful: http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron

Also, codepen protip: if your variable name inside a function is yellow instead of blue, JavaScript doesn’t recognize it there and you probably need to check its scope (or you just forgot to declare it).

1 Like