Value from API doesn't change

Here’s my Pen so far: https://codepen.io/GiaFil/pen/jzxvXZ
When the button is pressed it always uses the original value obtained from the API call, despite the code that in theory should change it. The celsius variable changes, so that is not the problem. What am I missing?

You initialized a variable named temp inside your $.ajax success function. So, anytime temp referenced inside the success function or any other functions nested inside the success function, it will retain that same value. What this means to your code, is that inside the click handler callback function (seen below), temp will always be the same value it started at when you initialized (var temp = data.main.temp). So, every time the button is clicked, the changeTemp function receives the same value.

        $("#getChange").on("click", function() {
          $("#temperature").html(changeTemp(temp));
        });

Since you now have this knowledge of what is going on with temp, you can use this fact to simplify your if statement logic inside changeTemp. You no longer need an else statement, because if celsius is equal to false, then there is no need to make any conversion because temp will already hold the value.

function changeTemp(temp) {
  if (celsius) {
    temp = temp * 1.8 + 32;
  }
  celsius = !celsius; // flips the value for celsius
  $(".change").html(temp);
}
1 Like