0

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(""); }; 
5
  • Why are you redeclaring the variable celsius in the onready eventhandler? Commented Apr 20, 2015 at 0:37
  • Your success handler is nested inside of two asynchronous operations $(document).ready() and $.simpleWeather(). That means those operations will complete some time LATER. Meanwhile, your if (fahrenheit > 55) code will have run BEFORE those async operations have completed. Put all code that needs to results INSIDE the success handler function itself. Commented Apr 20, 2015 at 0:40
  • @cmate I was basing my syntax off of a variable exercise. My understanding was that this was the correct syntax for changing a variable using the same variable. Commented Apr 20, 2015 at 0:53
  • @jfriend00. Thank you. This was the key. I was console logging "test" throughout the document and this function was running later than the others, but I could not figure out why. I removed the $(document).ready() hander but had not realized $.simpleWeather would run later as well. Thanks! Commented Apr 20, 2015 at 0:56
  • @sjos - if something takes a callback that is called when the operation is complete, then it is probably an async operation that is called sometime later. Commented Apr 20, 2015 at 1:02

1 Answer 1

1

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(""); }; 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @xdazz. I didn't realize the functions were running asynchronously. This solution worked for me!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.