World changes day by day!

Sunday, May 17, 2015

The ready event in jQuery

No comments
As mentioned in examples of events in jquery ready event in jquery contains all other functions. The ready event occurs when the DOM (document object model) has been loaded, and the page has been fully loaded (including images). It's good practice to wait for the document to be fully loaded and ready, before working with it. Thus ready event in jQuery must enclose all other events, functions and triggers.
The inclusion of other events inside the ready event in jQuery,  allows  to have JavaScript code before the body document, in the head section, either directly or through a link to an external JavaScript file. This is done by just placing the code inside the document ready event. Let get understand use of ready event in jQuery as an example.

<div id="test1"></div>
<script type="text/javascript">
function DocumentReady()
{
        $("#test1").text("Hello, world!");   
}

$(document).ready(DocumentReady);
</script>
What we do here is that we create a function, called DocumentReady, which should be fired as soon as the document is ready for DOM manipulation. In the last line, we use the ready() method to assign our function to the ready event, to tell jQuery that as soon as the document is ready, we want it to call our function.

However, we can shorten this a bit by using an anonymous function of JavaScript instead. This basically just means that instead of declaring the function and giving it a name, we simply create it and then immediately passes the reference to the ready() function. If you're new to JavaScript, then this might seem overly complicated, but as you get used to it, you might appreciate the fewer keystrokes and the less space needed to accomplish the same:
<div id="test2"></div>
<script type="text/javascript">
$(document).ready(function()
{
        $("#test2").text("Hello, world!");   
});
</script>
But of course, this wasn't even short enough for the jQuery team, so they decided to create a version (overload) of the jQuery constructor which takes a ready function as a parameter, to make it even shorter:
<div id="test3"></div>
<script type="text/javascript">
$(function()
{
        $("#test3").text("Hello, world!");   
});
</script>
In the last example, our anonymous function is passed directly to the jQuery constructor, which assigns it to the ready event. As you will see when you test the code, the event is fired as soon as the page is loaded, most of the time so fast that you won't even realize it.

As already described, wrapping your code in the ready event function is best practice for working with jQuery in your document, and therefore you will see this tutorial using the approach in most of the examples, unless skipped to keep example sizes down.

No comments :

Post a Comment

Leave Your comments