Showing posts with label Anonymous function. Show all posts
Showing posts with label Anonymous function. Show all posts

Friday, 25 November 2011

The ready event

As mentioned in the previous chapter, it's good practice to wait for the document to be fully loaded and ready, before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section, either directly or through a link to an external JavaScript file. You may do just that by placing your code inside the document ready event. We will use the same example as in the "Hello, world!" chapter, but this time the code is inside the ready event:

<div id="divTest1"></div>
<script type="text/javascript">
function DocumentReady()
{
        $("#divTest1").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="divTest2"></div>
<script type="text/javascript">
$(document).ready(function()
{
        $("#divTest2").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="divTest3"></div>
<script type="text/javascript">
$(function()
{
        $("#divTest3").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.

Introduction to events

Events in JavaScript are usually something where you write a snippet of code or a name of a function within one of the event attributes on an HTML tag. For instance, you can create an event for a link by writing code like this:

<a href="javascript:void(0);" onclick="alert('Hello, world!');">Test</a>

And of course this is still perfectly valid when using jQuery. However, using jQuery, you can bind code to the event of an element even easier, especially in cases where you want to attach anonymous functions or use the same code for multiple events, or even the same code for multiple events of multiple elements. As an example, you could bind the same event to all links and span tags in your document, with only a few lines of code like this:
<script type="text/javascript">
$(function()
{
        $("a, span").bind("click", function() {
                alert('Hello, world!');
        });
});
</script>

We use the bind method, which is essential when working with events and jQuery. In the following chapters we will tell you more about how it works, along with other event related information you need.

The bind() method

One of the most important aspects of dealing with events through jQuery is the bind() and unbind() methods. As the names imply, they will simply attach and unattach code to one or several events on a set of elements. We saw a very simple usage example for the bind() method in the introduction chapter for events, and here is a more complete one:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
$(function()
{
        $("a").bind("click", function() {
                alert($(this).text());
        });
});
</script>

It works by selecting all links (<a> elements) and then bind the anonymous function you see to the click event. A cool little feature is that jQuery will automatically assign the element that is clicked, to the "this" keyword inside of the anonymous function. This will allow you to access the element that activates the element, even when you assign the same code to multiple elements.

When jQuery calls your method, it will pass information about the event as the first parameter, if you have specified one or more parameters on it. For instance, the event object passed will contain information about where the mouse cursor is, which type the event is, which keyboard key or mouse button was pressed (if any) and much more. You can see all the properties and methods on the event object here: http://api.jquery.com/event.which/

Here is an example:

<div id="divArea" style="background-color: silver; 
width: 100px; height: 100px;">
</div>
<script type="text/javascript">
$("#divArea").bind("mousemove", function(event)
{
        $(this).text(event.pageX + "," + event.pageY);
});
</script>

We create a div element of a reasonable size and a background color. For this div, we subscribe to the mousemove event, with an anonymous function with a parameter called "event". This object gives us access to the pageX and pageY properties, which tells us where on the page the mouse cursor currently is, relative to the top left corner of the document. Try the example and move the cursor over the div element and you will see the coordinates updated as you move the mouse.

The bind() method also allows you to pass in data of your own and access it from the event object. This also allows you to set values at the time you bind the event, and be able to read this value at the time the event is invoked, even though the original variable you used may have changed. Here's an example where you can see just that:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        $("a").bind("click", { message : msg }, function(event) {
                msg = "Changed msg";
                alert(event.data.message);
        });
});
</script>

We pass the value as the secondary parameter of the bind() method, as a map of keys and values. You can pass more than one value by separating them with a comma. To access the value inside the event handler, we use the data property of the event object. This property contains sub-properties for each of the values you have passed, which means that you can access the value of the message parameter using event.data.message.

Despite the fact that we change the value of the "msg" variable inside the event handler, the message displayed will still be "Hello, world!" every time you click on one of the links, because it's evaluated as soon as the event handler is bound, which is once the page has been loaded.