sjos
sjos

Reputation: 53

Local function variable change not effecting variable in global scope. Why not?

I'm creating a simple weather application in js/jquery. One component of the simpleweather function is that it should globally effect the var fahrenheit, yet when I call it later in the if/else statement it logs in the var fahrenheit logs as 0. What am I doing wrong?

var fahrenheit = 0;
var celsius = 0;

$(document).ready(function() {

  $.simpleWeather({

    location: 'newyork, NY',
    woeid: '',
    unit: 'f',
    success: function(weather) {
    //renames weather.temp as fahrenheit
     fahrenheit = weather.temp;
    console.log(fahrenheit);
     //puts that value into .fahrenheit div
      $(".fahrenheit").html(fahrenheit);
      //converts to celsius then puts in .celsius div
       celsius = fahrenheit - 32;
    var celsius = celsius * 5;
    var celsius = celsius / 9;
    var celsius = parseInt(celsius);
    $(".celsius").html(celsius);
    },
  });
});

if (fahrenheit > 55) {
    $(".scarf").html('<img src="img/scarf.svg"></img>');

} else {

    $(".scarf").html("");
};

Upvotes: 0

Views: 58

Answers (1)

xdazz
xdazz

Reputation: 160833

You should put the below code inside the success callback. (Ajax works asynchronous.)

if (fahrenheit > 55) {
    $(".scarf").html('<img src="img/scarf.svg"></img>');
} else {
    $(".scarf").html("");
};

Upvotes: 1

Related Questions