Global variable is undefined in function

Please see the code below.
Why is y passed on to the showPositionfunction while x appears as null ?

I am using the w3schools script like here: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_geolocation

but instead of placing <script> after the html element I include them in the head.

The weird thing is that if I insert variable x as a local variable in the showPosition function the script works.
That is how I ruled out the possible issue of page not having loaded before changing x’s[ B]innerHTML[/B]

<head>
<script>
var x=document.getElementById("demo");
var y="test";
var r=x.className;

function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }

function showPosition(position)
  {
  alert (y + r);
  x.innerHTML="Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;	
  }


</script>
</head>
<body>

<p id="demo" class="first">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>

</body

It’s because it’s running before the dom is built, so there’s no element of id=“demo”.

What you could do is just declare x as the global (i.e. var x; ), then add the variable assignment (x = document.getElementById(“demo”)) into the getLocation method.

I would add that global variables are seldom required and that undefined is the default initial value for a variable.

You should place your JS just before the closing </body> tag, to ensure that the rest of the page is loaded before the script runs.

and wrap it inside an anonymous function so that none of the variables are global.

Thanks!