I have a javascript variable in the head of my dom and I need to access it in an external js file but it seems to come up undefined.
In my head I have something like.
<head>
<script type="text/javascript">
var overlayAlignment = ["left:20px","right:40px","left:50px"];
</script>
</head>
external .js file
$(document).ready(function () {
alert(overlayAlignment[0]);
});
In my external js file I want to use the variable but something like this comes up undefined all the time, any idea what I am doing wrong.
I found that I could run a function from the external .js in the head to set the overlayAlignment variable if I add the overlayAlignment variable to the .js file.
<head>
<script type="text/javascript">
setOverlayAlignment("value1", "value2", "values3");
</script>
</head>
external .js file
function setOverlayAlignment(value1, value2, value3) {
overlayalignment[0] = value1;
overlayalignment[1] = value2;
overlayalignment[2] = value3;
}
This still comes up as undefined when I try to use it in my jquery function however. Strange, I thought $(document).ready was to tell the function to wait till the dom is loaded to run, if that is the case why is overlayAlignment undefined when it runs?
I need to do it like this because the overlayAlignment variable values are only known at runtime.
Weird just tried this and it worked. Strange I thought window.onload and $(document).ready were the same thing.
Apparently overlayAlignment was not ready when $(document).ready was called but it will be available after window.onload.