I thought that script within $(document).ready(…) would always execute after the DOM is loaded. Hence, it wouldn’t matter if a $(document.ready(…) went in the head or in the body. However, the code below does not generate “apples” on the screen like I want it to. If I locate the giveApples() function at the bottom of the page though, it works.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(giveApples());
function giveApples() {
$("#appleTree").html("apples");
}
</script>
</head>
<body>
<div id="appleTree"></div>
</body>
<script>
//$(document).ready(giveApples());
</script>
</html>
Can anyone please correct my misconceptions about DOM, page loading, Script-tag location, (document).ready(), or anything else that is causing this problem? I’m still quite new to web programming.
And it does not. The problem is that you’re not passing
giveApplesas argument, but its returned value, since you are calling it (because of the()). To make it work, don’t put the parenthesis:By your current code, the value that is being passed to
$(document).readyisundefined, sincegiveApplesdoesn’t return any value.You could also do:
You can see what I explained above if you
alertthese two values:Its the same when you use DOM events (
onload,onclick, etc). You do this way:And not: