Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery .width() function issue with php
    text
    copied!<p>In calling an $("element").width() inside a $(document).ready function, I have found that I am getting varying answers. </p> <p>I believe this has something to do with session variable checking. If I have code like this:</p> <pre><code>&lt;body&gt; &lt;?php if(!isset($_SESSION['username'])){?&gt; &lt;!-- HTML Code Here --&gt; &lt;div id="some_element"&gt; &lt;/div&gt; &lt;!-- End HTML Code --&gt; &lt;?php } else { ?&gt; &lt;!-- More HTML Code --&gt; </code></pre> <p>And I reference "some_element" using:</p> <pre><code>$(document.ready(function(){ alert($("#some_element").width()); }); </code></pre> <p>Will I be guaranteed a distinct value to be returned for the width, if I have CSS that looks like this:</p> <pre><code>#some_element { width:300px; } </code></pre> <p>In testing, it seems like the return value I get actually does vary. If nesting the HTML code inside the PHP if statement is what is causing the issue, is there some other, better method to do so? I was thinking that the $(document).ready() method would wait until all the html was loaded so I could access those DOM objects.</p> <p>Also, the issue with having variable values returned from .width() is occurring in Chrome. Firefox seems to work fine and in IE the entire page looks messed up (this might be due to other code, not sure though).</p> <p>Any help would be much appreciated.</p> <p><strong>EDIT:</strong> Here is the solution (not for IE, still have no idea what's up going on with that) I have come up with for now. Inside both PHP if statements, I place a tag along with an onload attribute set to the function. In this case it would like something like:</p> <pre><code>&lt;?php if(!isset($_SESSION['username'])){?&gt; &lt;body onload="helperFunction()"&gt; &lt;div id="some_element"&gt; &lt;/div&gt; </code></pre> <p>If this is bad practice, or if there is a better way to achieve this kind of functionality, I'd appreciate the insight. Thanks for the quick replies guys.</p>
 

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