I’m still new to jQuery and I’m wondering how come the jQuery functions called inside .ready() work just fine but not outside?
For example, this would work:
$(document).ready(function() {
$('#field1').click(function() {
$('#result').load('/random_post #post');
});
});
But this won’t:
$('#field1').click(function() {
$('#result').load('/random_post #post');
});
How and if it works will depend on the order of which scripts and elements are laid out in your HTML, and it might also be affected by parameters outside your control (e.g. how the browser is programmed to behave).
I ‘d hazard a guess that this script appears in your page before the element with
id="field1"that gets a click handler added; this causes the script to run and find no such element in the document tree (yet). The element gets added after the script runs, which is why jQuery finds it just fine after the whole document has loaded.If you move this script at the very end of your page it should work (although of course the correct solution is to use the document ready event, as in your first snippet).