Wednesday 25 October 2017

Global Variables in JavaScript?

I'm new to Javascript and the following code is confusing
the hell out of me. By my understanding, you can assign values to global variables by
dropping the var in front of them, and you don't need to define any initial value when
you declare the global in the first place. However, why is the following code not
working? (By not working I mean that the call to document.write within main() spits out
"undefined" for "ulat").



var
ulat;

function write(latitude) {
ulat =
latitude;
document.write("

This works:" + ulat +
"

");
}


function getloc()
{

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(
function(position) {

write(position.coords.latitude);
},
function (error) {

switch(error.code) {

case error.TIMEOUT:
alert
('Timeout');
break;
case error.POSITION_UNAVAILABLE:

alert ('Position unavailable');
break;
case
error.PERMISSION_DENIED:
alert ('Permission denied');

break;
case error.UNKNOWN_ERROR:

alert ('Unknown
error');
break;
}
});


}
else {
alert("Geolocation is not supported by your web
browser.");
}

}



function main() {

getloc();
document.write("

This doesn't work: " + ulat +
"

");
}


Any
help? Thanks!

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...