Weather data won't show by default

link to pen:
I am using jquery to change the html in the .temp span but it only works if I put the .getJson function inside an .on(“click”) function. I want the data to display without having to push a button. What do I need to change to achieve this?

Without much change to your code, you can simply move everything inside $("#ajaxButton").on("click", function() { /* ... */ }); to just after where you are currently logging the weatherAPI variable.

The reason for this is because navigator.geolocation.getCurrentPosition() is asynchronous (I think), and the rest of your code (outside) would run before you have finished getting a user’s location; therefore, by putting the API call inside the callback function of navigator.geolocation.getCurrentPosition(), you are making sure that you are only making that call once you have a user’s location:

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      weatherAPI +=
        "lat=" + position.coords.latitude + "&lon=" + position.coords.longitude;
      // API call moved to here
      $.getJSON(weatherAPI, function(json) {
        var temp = json.main.temp;
        $(".temp").html(temp + degreesUnit);

It is worth noting that if a user chooses to not allow geolocation or has it disabled, this code would not work. To take those cases into account, you could display default information or use other method (such as getting a user’s approximate location using another API (something like to make the user experience better.

I hope that helps!

Thanks heaps, that 's fixed it for now.