Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does $(window).load() work but not $(document).ready()?
    primarykey
    data
    text
    <p>I'm working with a rails 3 app, and I want to use a sortable list. I'm working with the method shown <a href="http://awesomeful.net/posts/47-sortable-lists-with-jquery-in-rails" rel="nofollow">here</a>. My app uses JQuery, and there's a js file included in my app's layout that calls <code>$(document).ready()</code> to set up some visual stuff. That seems to be working fine.</p> <p>However, when I attempt to call <code>$(document).ready()</code> in my view template via <code>content_for :javascript</code> to set up the sortable list, that code never fires. I do have the requisite <code>yield :javascript</code> call in my layout file, and if I load the page and look at the source everything looks fine. The code never runs, though – i.e. this instance of <code>$(document).ready()</code> never fires.</p> <p>I've just found that if I replace <code>$(document).ready()</code> with <code>$(window).load()</code> then my js code runs. </p> <p>So my question is: <strong>Why would <code>$(document).ready()</code> fail and <code>$(window).load()</code> work?</strong></p> <h2>Code</h2> <p>This works:</p> <pre><code>&lt;% content_for :javascript do %&gt; &lt;script&gt; $(window).load(function(){ alert('it works!'); }); &lt;/script&gt; &lt;% end %&gt; </code></pre> <p>This doesn't work</p> <pre><code>&lt;% content_for :javascript do %&gt; &lt;script&gt; $(document).ready(function(){ alert('it works!'); }); &lt;/script&gt; &lt;% end %&gt; </code></pre> <p>Here's the Layout</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;%= content_for?(:title) ? yield(:title) : "Untitled" %&gt;&lt;/title&gt; &lt;!-- Reset Stylesheet --&gt; &lt;%= stylesheet_link_tag "reset" %&gt; &lt;!-- Main Stylesheet --&gt; &lt;%= stylesheet_link_tag "style" %&gt; &lt;!-- Invalid Stylesheet --&gt; &lt;%= stylesheet_link_tag "invalid" %&gt; &lt;%= javascript_include_tag :defaults, "nested_form", "DD_belatedPNG_0.0.7a", "simpla.jquery.configuration", "facebox", "jquery-ui.min" %&gt; &lt;%= yield :javascript %&gt; &lt;%= yield(:head) %&gt; &lt;%= csrf_meta_tag %&gt; &lt;/head&gt; &lt;body onload="initialize()"&gt;&lt;div id="body-wrapper"&gt; … </code></pre>
    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.
 

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