Why can't I call a function direct when document loads with jQuery?
<p>I use the $(document).ready function from jQuery. It seems that I can't call a function directly with it. I can't figure out why. It gives an error when I try to find the canvas with getElementById.</p>

<p>This works:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" &gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var test="this is a test";
var canvas;
var ctx;

$(document).ready( function(){ 
    init(); 
}); 

function init() {               
    console.log (test);
    canvas=document.getElementById('canvas');
    ctx = canvas.getContext('2d');      
}

&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;div&gt;
&lt;canvas id="canvas" width="300" height="300"&gt;
    No HTML5 support.
&lt;/canvas&gt;       
&lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre>

<p>This works too:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" &gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var test="this is a test";
var canvas;
var ctx;

$(document).ready(function(){               
    console.log (test);
    canvas=document.getElementById('canvas');
    ctx = canvas.getContext('2d');      
}); 


&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;div&gt;
&lt;canvas id="canvas" width="300" height="300"&gt;
    No HTML5 support.
&lt;/canvas&gt;       
&lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre>

<p>But this gives an error...</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;script language="javascript" src="http://code.jquery.com/jquery-1.4.2.js" &gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
var test="this is a test";
var canvas;
var ctx;

$(document).ready(init()); 

function init() {               
    console.log (test);
    canvas=document.getElementById('canvas'); // &lt;= Error here!
    ctx = canvas.getContext('2d');      
}


&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;div&gt;
&lt;canvas id="canvas" width="300" height="300"&gt;
    No HTML5 support.
&lt;/canvas&gt;       
&lt;/div&gt;
&lt;/body&gt;

&lt;/html&gt;
</code></pre>

<p>Kind regards!</p>
