Most
programming tutorials begin with a “Hello World” example code snippet, so that
is where I am going to begin.
Our
goal here is to print “Hello World!!!” on the page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<div id="HelloWorld"></div>
<script type="text/javascript">
$("#HelloWorld").text("Hello World!!!");
</script>
</body>
</html>
You
will notice that I put the script tags and jQuery code after the <div id="HelloWorld"></div> element that I want
to insert the “Hello World!!!” text into. If I don’t do it like this, the
jQuery code will possibly fire before the <div id="HelloWorld"></div> element has been rendered in the browser window and
nothing will happen on the page.
Document ready event:
To
solve this problem you need to use the document ready() event to cause jQuery
to wait until the page rendering is complete before firing the jQuery code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function PrintHelloWorld() {
$("#HelloWorld").text("Hello World!!!");
}
$(document).ready(PrintHelloWorld);
</script>
<div id="HelloWorld"></div>
</body>
</html>
This
example has the script tags with the jQuery code before the <div id="HelloWorld"></div> element that I want
to insert the “Hello World!!!” text into.
It also
uses one of three methods of using the document ready() event.
They
are:
$(document).ready(PrintHelloWorld);
Or
$(document).ready(function () {
PrintHelloWorld();
});
Or
$(function () {
PrintHelloWorld();
});
All
three will do exactly the same thing, but each subsequent version of the
document ready() event is shorter and easier to use. The third is most commonly
used.
Without
the document ready() event, you will find that your jQuery code will not fire
at the right time, and will cause unexpected results.
No comments:
Post a Comment