Note that there are some explanatory texts on larger screens.

plurals
  1. POaccess head javascript variable in .js file jquery function
    primarykey
    data
    text
    <p>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.</p> <p>In my head I have something like.</p> <pre><code> &lt;head&gt; &lt;script type="text/javascript"&gt; var overlayAlignment = ["left:20px","right:40px","left:50px"]; &lt;/script&gt; &lt;/head&gt; </code></pre> <p>external .js file</p> <pre><code>$(document).ready(function () { alert(overlayAlignment[0]); }); </code></pre> <p>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. </p> <p>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. </p> <pre><code> &lt;head&gt; &lt;script type="text/javascript"&gt; setOverlayAlignment("value1", "value2", "values3"); &lt;/script&gt; &lt;/head&gt; </code></pre> <p>external .js file</p> <pre><code>function setOverlayAlignment(value1, value2, value3) { overlayalignment[0] = value1; overlayalignment[1] = value2; overlayalignment[2] = value3; } </code></pre> <p>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?</p> <p>I need to do it like this because the overlayAlignment variable values are only known at runtime.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload