I started working on the weather app, and the first steps I took were to lay out the simple page, add a click function to convert between units, and then obtain the user’s location. After those parts all work, I would work on obtaining the local weather. However, the request to https://ipinfo.io only works on the click event in the app.
I tried initializing variables that store location information and updating the page with the defaults, then after that I have the request made for the user location, and another update for this new information. I have confirmed via simple tests that the update function works as expected, but the function to obtain user location oddly only works on the click event. How do I make this work when the page loads?
I put the jQuery’s $(document).ready function, as well as the standard window.onload function, in hopes that one of them would catch. Although the rest of the code seems to work just fine, so that’s why I am stumped.
Here’s the codepen:
Alternatively, here’s the code:
JS:
var userip = '';
var city = '';
var prov_stat = '';
var unit = '';
var weather = '';
var temp = 0;
function getLocation() {
$.get("https://ipinfo.io", function(response) {
userip = response.ip;
city = response.city;
prov_stat = response.region;
}, "jsonp");
}
function getLocalWeather() {}
function convertToF(celsius) {
var fahrenheit;
fahrenheit = (celsius * (9/5)) + 32;
return fahrenheit;
}
function convertToC(fahrenheit) {
var celsius;
celsius = ((fahrenheit - 32) * (5/9));
return celsius;
}
function convertTemp() {
var newtemp = 'F';
if (unit === 'C') {
newtemp = convertToF(temp);
unit = 'F';
} else {
newtemp = convertToC(temp);
unit = 'C';
}
temp = newtemp;
}
function updateApp() {
$('#temp').html(temp +' °');
$('#unit').html(unit);
$('#location').html(city + ", " + prov_stat);
$('#weather').html(weather);
}
function init() {
// Initialize variables
city = 'Vancouver';
prov_stat = 'BC';
unit = 'C';
weather = 'Snow';
temp = 20;
// Update variables to user's location
getLocation();
updateApp();
}
window.onload = function() {
$(document).ready(function() {
init();
$('#unit').click(function() {
getLocation();
convertTemp();
updateApp();
});
});
}