I have the following code which gets the user’s current zipcode and displays it for them in a div:
(function ($, geolocation) {
if (geolocation) {
geolocation.getCurrentPosition(function (position) {
$.getJSON(
"http://ws.geonames.org/findNearestAddressJSON?callback=?",
{
lat : position.coords.latitude,
lng : position.coords.longitude
},
function (data) {
$(function () {
$('#zip').text(data.address.postalcode);
});
}
);
});
}
}(jQuery, navigator.geolocation));
The code runs on document ready, I believe. Is this the same as the code running onLoad? Anyways, is it possible to run this code when a button is clicked? I was thinking something like this would work, but using this doesn’t produce the zipcode on document ready, or when clicking the button:
function update() {
...code from above
}
$('#button').click(function(){update();});
This doesn’t run on
document.ready, except for one part of the code (the one inside thefunction (data) { }call.No,
document.readyis different fromonLoad.document.readyis when the DOM is accessible via Javascript (but not necessarily rendered / fetched);onLoadis when everything has been loaded (and presumably rendered — think images, etc.).To have the same function run on a button click, you’re already down more or less the right track. You’d want to have a reference to the function:
Then have that run via a click handler: