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(""); };
celsiusin the onready eventhandler?$(document).ready()and$.simpleWeather(). That means those operations will complete some time LATER. Meanwhile, yourif (fahrenheit > 55)code will have run BEFORE those async operations have completed. Put all code that needs to results INSIDE thesuccesshandler function itself.$(document).ready()hander but had not realized$.simpleWeatherwould run later as well. Thanks!