CHAMPION KAY TUTORIAL

Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Other frameworks and the noConflict() method

There may come a time when you wish to use other frameworks on your pages, while still using jQuery. For instance, a lot of third party JavaScript packages out there depends on one of the popular JavaScript frameworks, like ExtJS, MooTools and so on. Some of them uses the $ character as a shortcut, just like jQuery does, and suddenly you have two different frameworks trying to claim the same identifier, which might make your external scripts stop working. Fortunately the jQuery developers have already thought about situations like this and implemented the noConflict() method.

The noConflict() method simply releases the hold on the $ shortcut identifier, so that other scripts can use it. You can of course still use jQuery, simply by writing the full name instead of the shortcut. Here's a small example of it:

<div id="divTestArea1"></div>
<script type="text/javascript">
$.noConflict();
jQuery("#divTestArea1").text("jQuery is still here!");
</script>
If you think that "jQuery" is too much to type each time, you can create your own shortcut very easily. The noConflict() method returns a reference to jQuery, that you can save in your own little variable, for later use. Here's how it looks:
<div id="divTestArea2"></div>
<script type="text/javascript">
var jQ = $.noConflict();
jQ("#divTestArea2").text("jQuery is still here!");
</script>
If you have a block of jQuery code which uses the $ shortcut and you don't feel like changing it all, you can use the following construct. It's yet another version of the ready method, where $ is passed in as a parameter. This allows you to access jQuery using $, but only inside of this function - outside of it, other frameworks will have access to $ and you will have to use "jQuery":
<div id="divTestArea3"></div>
<script type="text/javascript">
$.noConflict();
jQuery(document).ready(function($) 
{
	$("#divTestArea3").text("jQuery is still here!");
});
</script>

Working with widths and heights

jQuery makes it easy for you to work with the dimensions of your elements and even the browser window. You can use the width() and height() methods for finding the dimensions, or alternatively the innerWidth()/innerHeight()/outerWidth()/outerHeight() methods, depending on the measurements you need. First a little example illustrating the differences and the some explanation:
<a href="javascript:void(0);" onclick="ShowElementDimensions();">Show element dimensions</a>
<div id="divTestArea1" style="height: 100px; width: 400px; padding: 20px; margin: 3px; border: 1px solid silver; background-color: #eee;"></div>

<script type="text/javascript">
function ShowElementDimensions()
{
	var result = "";
	
	result += "Dimensions of div: " + $("#divTestArea1").width() + "x" + $("#divTestArea1").height() + "</br>";
	result += "Inner dimensions of div: " + $("#divTestArea1").innerWidth() + "x" + $("#divTestArea1").innerHeight() + "</br>";	
	result += "Outer dimensions of div: " + $("#divTestArea1").outerWidth() + "x" + $("#divTestArea1").outerHeight() + "</br>";	
	result += "Outer dimensions of div (with margin): " + $("#divTestArea1").outerWidth(true) + "x" + $("#divTestArea1").outerHeight(true) + "</br>";	
	
	$("#divTestArea1").html(result);
}
</script>
The example is quite simple. We have a div element with extra padding, extra margin and a border. When we click the link, we use the width()/height(), innerWidth()/innerHeight() and outerWidth()/outerHeight() methods to show the dimensions of the element.

The width() and height() is simply the computed size of the element. If you use innerWidth() and innerHeight(), padding is included in the returned values. If you use the outerWidth() and outerHeight() methods, both padding and border is included in the returned values. These last methods take an optional boolean parameter which tells jQuery whether or not to include the margin as well, as you can see from the example.

The width() and height() methods can also be used to get the current dimensions of the browser window:
<a href="javascript:void(0);" onclick="ShowBrowserDimensions();">Show browser dimensions</a>

<script type="text/javascript">
function ShowBrowserDimensions()
{
	alert("Dimensions of document: " + $(document).width() + "x" + $(document).height());
	alert("Dimensions of window: " + $(window).width() + "x" + $(window).height());
}
</script>
We check the width and height for both the document (the HTML document) and the window (the browser viewport), since these may or may not differ.

Both the width() and the height() methods can also be used to set new dimensions for an element, simply by providing a parameter with the new value. Check out this example:
<a href="javascript:void(0);" onclick="ResizeElement();">Resize element</a>
<div id="divTestArea3" style="height: 100px; width: 300px; padding: 20px; border: 1px solid silver; background-color: #eee;">

<script type="text/javascript">
function ResizeElement()
{
	$("#divTestArea3").width(150).height(50);
}
</script>

Aborting an AJAX request

There may be situations where you need to cancel a running AJAX request before it ends. It's usually in cases where the user might perform an action, which sets of an AJAX request, several times within a short time period. A good example of this is auto-complete functionality for a search box, where you might try to help the user by finding related search terms based on their current input, by making an AJAX request each time they press a key in the search field. In that case, it's very likely that the user types faster than your AJAX request can be performed and therefore you would want to abort any non-finished requests, before starting the next one. Consider the following example:
<input type="button" name="btnDoRequest" value="Start" onclick="PerformSimpleCalculation();" />
<script type="text/javascript">
function PerformSimpleCalculation()
{
	$.get("/tests/calc.php", function(data, textStatus)
	{
		alert(data);
	});
}
</script>
It requests a PHP script which is doing a very complicated calculation (as you will see from the result), which means that it usually takes ~3 seconds to finish. Now, try the example and push the button several times after each other. The same "calculation" will be performed multiple times and the result will also be displayed multiple times (with a 3 second delay).

Fortunately, a call to the get() method and pretty much any other jQuery AJAX method, returns an object which, among others, contains an abort() method. We can save this reference and then call the abort() method on it if needed. Have a look at this slightly modified example:
<input type="button" name="btnDoRequest" value="Start" onclick="PerformAbortableCalculation();" />
<script type="text/javascript">
var calculationRequest = null;

function PerformAbortableCalculation()
{
	if(calculationRequest != null)
		calculationRequest.abort();
	calculationRequest = $.get("/tests/calc.php", function(data, textStatus)
	{
		alert(data);
	});
}
</script>
We start off by defining a common variable for containing the request reference. In the PerformAbortableCalculation() method, we assign the return value of the get() call to this variable, but before we do so, we check to see if it's null (the method hasn't been used yet) and if not, we call the abort() method on it. If you try this example and click several times, you will see that no matter how many times you click the button, it only executes the callback function once. 

Showing progress

When doing AJAX requests, you may want to show some sort of progress while waiting for the request to finish, especially if it might take a while for it to do so. It's actually very simple to do so with jQuery, as you will see from the following example:
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculation(this);" />
<script type="text/javascript">
function PerformCalculation(sender)
{
	$(sender).val("Working - please wait...");
	$.get("/tests/calc.php", function(data, textStatus)
	{
		$(sender).val("Perform calculation");
		alert(data);
	});
}
</script>
Right before performing the AJAX request, we change the text of the sender (the button which calls the function). As soon as it succeeds, we set it back. That's the simplest form of progress. Another approach is to show a piece of text somewhere on the page, but the most common way of doing it is to show a little piece of graphic which illustrates that the browser is currently working. You could make one yourself, or even better: Use one of the great online generators, for instance http://ajaxload.info/. I've created one, as you can see in the next example:
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculationWithImageProgress();" />
<img src="/images/ajax-loader.gif" style="display: none;" id="imgProgress" />
<script type="text/javascript">
function PerformCalculationWithImageProgress()
{
	$("#imgProgress").show();
	$.get("/tests/calc.php", function(data, textStatus)
	{
		$("#imgProgress").hide();
		alert(data);
	});
}
</script>
The process is pretty much the same, but instead of setting a text, we show and hide an existing image. You can place the image in a spot that the user is most likely to notice or dynamically place the image next to button/link clicked, if you have more than one. The possibilities are really endless.

There is one problem with the above examples though: If the request fails for some reason, the progress is shown but never removed again. We can fix this by subscribing to the error event, where we can then remove the progress and then show an error message. Check out this example:
<input type="button" name="btnDoRequest" value="Perform calculation" onclick="PerformCalculationWithErrorHandling(this);" />
<script type="text/javascript">
function PerformCalculationWithErrorHandling(sender)
{
	$(sender).val("Working - please wait...");
	$.get("/tests/non-existing.php", function(data, textStatus)
	{
		$(sender).val("Perform calculation");
		alert(data);
	}).error(function()
	{
		$(sender).val("Try again");
		alert("An error occurred.")
	});
}
</script>
It's pretty much identical to the first example, but here we call the error function on the returned AJAX object and pass in a callback function which should be called if the request fails, which it will in this example, since I have changed the path for the requested file to something which doesn't exist. 

In the previous chapter, we discussed the Same Origin Policy, which prevents us from making AJAX requests to a different domain or subdomain than the one currently executing the script. JSONP is a good solution to this, and in this article we will look into it.

In the following examples, we will be making calls to a PHP script on this server, but on a different subdomain. It will output an array of two users in the JSON format and the output will be JSONP compatible because the data will be surrounded by the parameter passed to the script and a set of regular parentheses. The PHP code looks like this:

<?php
$users = array
(
 array("name" => "John Doe", "age" => 42),
 array("name" => "Jane Doe", "age" => 39)
);
echo $_REQUEST['callback'] . "(" . json_encode($users) . ")";
?>
To see what data returned looks like, try opening the following URL in your browser:

http://tests.jquery-tutorial.net/json.php?callback=test

The result will look like this:

test([{"name":"John Doe","age":42},{"name":"Jane Doe","age":39}])

If you set the callback parameter to something else, you will see that change reflected in the output. This special notation is what separates regular JSON and JSONP. Now when JSON data is returned to jQuery, it parses it into objects that you may then access and use like any other JavaScript object. For instance, the above output would result in two objects, each with a name and an age property.

Now let's try requesting the page from jQuery and use the returned data. When you test this example, notice that we call the page on a different subdomain (tests.jquery-tutorial.net) than the currently executing domain (www.jquery-tutorial.net):
<ul id="ulUsers"></ul>
<script type="text/javascript">
$(function()
{
    $.get
 (
  "http://tests.jquery-tutorial.net/json.php?callback=?", 
  function(data, textStatus)
        {
         $.each(data, function(index, user)
   {
    $("#ulUsers").append($("<li></li>").text(user.name + " is " + user.age + " years old"));
   });
        },
  "json"
 );  
});
</script>
If you read the chapter on the get() and post() methods, you will see that there are only two main differences: The callback parameter on the URL, and the extra parameter specifying that we want the return type to be "json". The callback is set to a question mark, which will make jQuery generate a random one for us. In the script that takes the call, the value of this parameter is used, as you can see in the PHP code above.

Once we get some data back, we throw it into the each() method, which will loop over the data, each time invoking an anonymous method where we access the current set of data in the "user" variable. We then use the name and age of the user to construct a text representation, which we append to a list (ul tag) as a list item (li tag). As a result, we get an HTML list of the users returned by the script. 

Same Origin Policy

Same Origin Policy is a security feature found in the JavaScript implementation in most browsers, as well as in other technologies used in a browser, e.g. Flash. It basically allows you to make requests to pages within the same site/domain, while preventing you from making requests to pages on a different domain, another subdomain or through a different protocol. Since this is a part of JavaScript, it's also a part of jQuery, as you will see if you try to do an AJAX call to a page on another domain - it's simply not possible. There are certain hacks and workarounds to circumvent Same Origin Policy, but they usually don't work in all browsers or have other problems.

However, sometimes you really do need to make requests to a page on a different domain, especially in cases where you own both domains or when the owner of the secondary domain would like for you to access the page. Fortunately, the JSONP standard allows us to do just this, and while it's also a bit of a hack that would require quite a bit of effort to use within JavaScript, jQuery supports this very elegantly, allowing you to do JSONP based calls just as easy as a regular AJAX call. In fact, you can change the get() or post() call to be JSONP based simply by stating that you would like the return type to be "json".

JSON, short for JavaScript Object Notation, is a data notation, a bit like XML, allowing you to transfer structured data easily, usually over a network connection. Despite the fact that it was originally intended to use with JavaScript, a lot of other programming languages supports it out-of-the-box as well, allowing you to easily output arrays and objects in the JSON format.

The get() and post() methods

The jQuery get() and post() methods allows you to easily send a HTTP request to a page and get the result back. When you post a form, it's usually either a GET or a POST request, and with jQuery you can mimic that, since both a get() and a post() method exists.

The two methods are pretty much identical, since they simply just invoke different request types against the server. They are both static methods, which means that instead of instantiating a jQuery object and then working with that, we call get() or post() directly on the jQuery class, either by writing jQuery.get() or by using the shortcut character like this: $.get(). In its most simple form, the get() and post() methods takes a single parameter, which is the URL that you wish to request. However, in most cases you will want to do something with the returned data, in which case you can pass a callback function as a parameter, which jQuery will call if the request succeeds.

Let's do some testing. In the previous chapter, I created an HTML file called "content.html", which we loaded using the jQuery load() method. When testing the following example, make sure that you have a file called "content.html" in the same directory as the file in which you have the example. The content doesn't really matter, just write anything in there really. Here's an example of the get() method:

<script type="text/javascript">
$(function()
{
 $.get("content.html", function(data, textStatus)
 {
  alert("Done, with the following status: " + textStatus + ". Here is the response: " + data);
 });
});
</script>
The first parameter is the URL, which is just content.html. The second parameter is more interesting. It's a callback function, which jQuery calls if the page request succeeds. The first callback parameter is simply the content of the page requested, while the second callback parameter is the textual status of the request.

You can of course request a simple HTML page, like in the example above, but normally the reason for using a GET or a POST request is that you wish to pass in some parameters, which is then processed by the server, for instance with a piece of PHP, ASP or ASP.NET code, and then return the result. jQuery can take a map of GET or POST parameters, which we will try in the following example, where we use the post() method:
<script type="text/javascript">
$(function()
{
 $.post("test_post.php",
 {
  name: "John Doe",
  age: "42"
 },
 function(data, textStatus)
 {
  alert("Response from server: " + data);
 });
});
</script>
This example is much like the first one, but we make the POST request to another page, in this example a PHP page, and as the second parameter, we pass in a map of POST parameters. The map is constructed of two parameters, a name and an age. If we had used a GET request instead of a POST request (POST requests doesn't take parameters from the URL like GET does), the above code would actually have corresponded to requesting an URL like this in your browser:

test_get.php?name=John Doe&age=42

The PHP script can then read the parameters, process them and return a result. The script on our server simply takes the two values and creates a string like " is years old" and then returns it, which you can see if you test the example above. 

The load() method

As described in the previous chapter, there are many ways to use AJAX with jQuery, and they should of course be used depending on the situation. One of the simplest and yet still powerful methods for loading data asynchronously is the load() method. You use it by selecting an element where you want the content loaded to and then call the load() method on it. It takes the URL that you wish to load, as a parameter. For this example, we need a an external file that we can load. We'll call it content.html and the content of it should look something like this:
<div id="divContent">
 <b>This is external content</b>
</div>
And there's more of it
Save it as content.html, in the same directory where you keep your other example files for this tutorial. We can load it as simple as this:
<div id="divTestArea1"></div>
<script type="text/javascript">
$(function()
{
 $("#divTestArea1").load("content.html");
});
</script>
If you have the content file in another directory, or if you have named it differently, you will have to change the parameter for the load method accordingly. This is all it takes to load content from an external file with jQuery and the load method. A pretty cool trick is that you can actually pass a selector along with the URL, to only get a part of the page. In the first example, we loaded the entire file, but in the following example, we will only use the div, which contains the first sentence:
<div id="divTestArea2"></div>
<script type="text/javascript">
$(function()
{
 $("#divTestArea2").load("content.html #divContent");
});
</script>
As you can see, we simply append a standard jQuery selector to the parameter, after the URL, separated with a space. This causes jQuery to select the content out and only pass the matched part(s) back to the container. You can use any jQuery selector type to pull off this trick, which makes it pretty powerful.

The load method can take two extra parameters: A set of querystring key/value pairs, and a callback function which will be executed when the load method finishes, no matter if it succeeds or fails. Here is an example where we use the callback function to inform about the result. Normally, you would likely only show a message if the method fails, but to illustrate how it works, we do it if the method fails as well. I make sure that it fails for the example, by requesting a file which doesn't exist:
<div id="divTestArea3"></div>
<script type="text/javascript">
$(function()
{
 $("#divTestArea3").load("no-content.html", function(responseText, statusText, xhr)
 {
  if(statusText == "success")
   alert("Successfully loaded the content!");
  if(statusText == "error")
   alert("An error occurred: " + xhr.status + " - " + xhr.statusText);
 });
});
</script>
As you can see, the callback function specifies 3 parameters, which jQuery will fill in for you. The first parameter will contain the resulting content if the call succeeds. The second parameter is a string which specifies the status of the call, e.g. "success" or "error". You can use it to see if the call was successful or not. The third parameter is the XMLHttpRequest object used to perform the AJAX call. It will contain properties which you can use to see what went wrong and many other things. 

Introduction to AJAX

AJAX, short for Asynchronous JavaScript And XML, allows you to load data in the background and display it on your webpage, without refreshing the page. This allows you to create websites with much richer functionality. Popular web applications like Gmail, Outlook Web Access, and Google Maps uses AJAX extensively, to provide you with a more responsive, desktop-like experience.

Using AJAX can be a bit cumbersome, because the various browsers have different implementations to support AJAX. Normally this would force you to write code to respond differently, depending on the browser, but fortunately, jQuery has done this for us, which allows us to write AJAX functionality with as little as a single line of code.

You should be aware of the fact that thre are both advantages and disadvantages to using AJAX on your page though, which means that you should always consider carefully before deciding to use it instead of doing a regular postback to the server. Here's a summary:

Advantages

  • Your page will be more pleasant to use, when you can update parts of it without a refresh, which causes the browser to flicker and the statusbar to run.
  • Because you only load the data you need to update the page, instead of refreshing the entire page, you save bandwidth.

Disadvantages

  • Because the updates are done by JavaScript on the client, the state will not register in the browsers history, making it impossible to use the Back and Forward buttons to navigate between various states of the page.
  • For the same reason, a specific state can't be bookmarked by the user.
  • Data loaded through AJAX won't be indexed by any of the major search engines.
  • People using browsers without JavaScript support, or with JavaScript disabled, will not be able to use the functionality that you provide through AJAX.
The first two items on the list may be circumvented though, typically through the use of an iframe and reading and writing data from the part of the URL after the # character.

In the following chapters, you will learn how to use various AJAX related functions of jQuery. 

The live() method

In the previous chapters, we used the bind() and unbind() methods to attach and detach event handlers to various elements on the page. This works great for elements which already exists, but what if you want your event handler to be attached to future elements as well? Normally you would have to do this manually, upon creating the new elements, and this is still possible. However, using the live() method, you can inform jQuery to attach your event handler to any future elements which matches your original selector, without having to lift a finger. Let me first show you an example where we use the bind() method, and then replace it with the live() method, to show you the difference:
<div id="divTestArea1">
 <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
 <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{
 $(".test").bind("mouseover", function()
 {
  $(this).css("background-color", "blue");
 }).bind("mouseout", function()
 {
  $(this).css("background-color", "white");
 });
});

function AddBox()
{
 var div = $("<div></div>").addClass("test").text("Another box");
 $("#divTestArea1").append(div);
}
</script>
Okay, this example might seem a bit complicated, but actually it's not. Let me walk you through it. We have a link, which will call the AddBox() JavaScript method, and then we have a div with the class "test". The AddBox() method will simply add another div to the page, with the same class, so that when you click the link, you get yet another box on the page. In the ready event, we select all elements with the "test" class and then we bind a handler to two of the events: The mouseover and the mouseout event, where we change the color of the element invoking the event. Try the example in your browser. The first div will have the mouseover effect, but if you click the link to add more boxes, they won't have the same effect. The reason is pretty obvious: We attached the events before these new boxes were created.

Now try the following example instead. I have only changed two words in it: The two calls to bind() has been replaced with calls to live():
<div id="divTestArea2">
 <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
 <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{
 $(".test").live("mouseover", function()
 {
  $(this).css("background-color", "blue");
 }).live("mouseout", function()
 {
  $(this).css("background-color", "white");
 });
});

function AddBox()
{
 var div = $("<div></div>").addClass("test").text("Another box");
 $("#divTestArea2").append(div);
}
</script>
Now if you run this example, you will see that even though you add new elements after the page has loaded, jQuery will automatically attach the event handlers to them for you. The live() method works just like bind() in all the other aspects, so check the previous chapters for more information on it. The same goes for the die() method, which works just like the unbind() method, but should be used for cases where the live() method has been used. 

The unbind() method

In the previous chapter, we used the bind() method to subscribe to events with jQuery. However, you may need to remove these subscriptions again for various reasons, to prevent the event handler to be executed once the event occurs. We do this with the unbind() method, which in its simplest form simply looks like this:
$("a").unbind();
This will remove any event handlers that you have attached with the bind() function. However, you may want to only remove event subscriptions of a specific type, for instance clicks and doubleclicks:
$("a").unbind("click doubleclick");
Simply separate the event types with a comma. Here is a more complete example, where you can see it all in effect:
<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", function() {
  $("a").unbind("click");
  alert("First and only message from me!");
 });
});
</script>
In this little example, we subscribe to the click event of all links. However, once a link is clicked, we remove all the subscriptions and alert the clicker about it. The event handler will no longer be activated by the links.

jQuery allows you to subscribe to the same event type more than one time. This can come in handy if you want the same event to do more than one thing in different situations. You do it by calling the bind() method for each time you want to attach a piece of code to it, like this:
<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", function() {
  alert("First event handler!");
 });
 
 $("a").bind("click", function() {
  alert("Second event handler!");
  $("a").unbind("click");
 });
});
</script>
However, this opens up for the possibility that once you unbind an event, you may be removing event subscriptions used a whole other place in your code, which you still need. If you try the example, you will see the result of this - when you click a link, all of the event subscriptions are removed. jQuery allows you to specify a secondary argument, which contains a reference to the specific handler you would like to remove. This way, we can make sure that we only remove the event subscription we intend to. Here's an example:
<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()
{
 var handler1 = function() 
 {
  alert("First event handler!");
 }
 
 var handler2 = function() 
 {
  alert("Second event handler!");
  $("a").unbind("click", handler2);
 }
 
 $("a").bind("click", handler1);
 $("a").bind("click", handler2);
});
</script>
By specifying handler2 as the secondary parameter, only this specific event handler is removed. Try the example. The secondary message is only displayed the first time you click the link. 

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. 

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 remove() and empty() methods

In the last couple of chapters, we have worked with adding new elements to a page, but of course jQuery can help you remove them as well. There are mainly two methods for this: remove() and empty(). The remove() method will delete the selected element(s), while the empty() method will only delete all child elements of the selected element(s). The following example should illustrate the difference - be sure to click the links in the right order though:
<a href="javascript:void(0);" onclick="$('#divTestArea1').empty();">empty() div</a>   
<a href="javascript:void(0);" onclick="$('#divTestArea1').remove();">remove() div</a>
<div id="divTestArea1" style="height: 100px; width: 300px; padding: 20px; border: 1px solid silver; background-color: #eee;">
 <b>Bold text</b>
 <i>Italic text</i>
</div>
The first link will call the empty() method on our test div, removing all the child elements. The second link will remove the entire div, including any child elements. Pretty simple stuff.

The remove() method comes with one optional parameter, which allows you to filter the elements to be removed, using any of the jQuery selector syntaxes. You could of course achieve the same simply by doing the filtering in your first selector, but in some situations, you may be working on a set of already selected elements. Check out this example of it in use:
<a href="javascript:void(0);" onclick="$('#divTestArea2 b').remove('.more');">remove() more bold</a>
<div id="divTestArea2" style="height: 100px; width: 300px; padding: 20px; border: 1px solid silver; background-color: #eee;">
 <b>Bold text</b><br />
 <b class="more">More bold text</b><br />
 <b class="more">Even more bold text</b><br />
</div>
We start out by selecting all bold tags inside our test div. We then call the remove() method on the selected elements, and pass in the .more filter, which will make sure that we only get elements which uses the class "more". As a result, only the last two bold texts are removed.

You can of course use even more advanced selectors as a filter too. Have a look at the "Selectors" topic of this tutorial for inspiration.

The before() and after() methods

In the previous chapter, we used the append() and prepend() methods to insert stuff inside an element, but in some cases, you need to insert things before or after one or several elements instead. jQuery has the before() and after() methods for just this purpose, and they are just as easy to use. Check out this example:
<a href="javascript:void(0);" onclick="$('input.test1').before('<i>Before</i>');">Before</a>   
<a href="javascript:void(0);" onclick="$('input.test1').after('<b>After</b>');">After</a>

<br /><br />

<input type="text" class="test1" value="Input 1" name="txtInput1" /><br />
<input type="text" class="test1" value="Input 2" name="txtInput2" /><br />
Depending on which of the two links you click, an italic or a bold tag will be inserted before or after each input element on the page using the "test1" class. Just like with append() and prepend(), both after() and before() allows you to use HTML strings, DOM elements and jQuery objects as parameters and an infinite amount of them as well. We'll demonstrate that in the next example:
<a href="javascript:void(0);" onclick="InsertElements();">Insert elements</a>
<br /><br />
<span id="spnTest2">Hello world? </span>

<script type="text/javascript">
function InsertElements()
{
 var element1 = $("<b></b>").text("Hello ");
 var element2 = "<i>there </i>";
 var element3 = document.createElement("u");
 element3.innerHTML = "jQuery!";
 
 $("#spnTest2").after(element1, element2, element3);
}
</script>
In this example, we create a jQuery object, an HTML string and a JavaScript DOM element, and then we use the after() method to insert all of them after our span tag. Of course, the before() method could have been used in exactly the same way.

There are variations of the before() and after() methods, called insertBefore() and insertAfter(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to insert data before or after, with a parameter of what is to be inserted, you do the exact opposite. Which method to use obviously depends on the situation, but here's an example showing you how to use them both:
<a href="javascript:void(0);" onclick="InsertElementsBefore();">Insert elemenets</a>
<br /><br />
<span id="spnTest3">Hello world? </span>

<script type="text/javascript">
function InsertElementsBefore()
{ 
 $("#spnTest3").before($("<i></i>").text("before() "));
 $("<b></b>").text("insertBefore() ").insertBefore("#spnTest3");
}
</script>
In this example, we insert the items before the span tag, but you could of course do the exact same using after() and insertAfter(), if you wish to insert after the target elemenet. As you can see, the result is the same - only the order of what we do differs. 

The append() and prepend() methods


Adding new stuff to existing elements is very easy with jQuery. There are methods for appending or prepending, taking HTML in string format, DOM elements and jQuery objects as parameters. In the next example, you will see how easy it is to insert new elements in a list, using both the append() and the prepend() method:

<a href="javascript:void(0);" onclick="$('#olTestList1').append('<li>Appended item</li>');">Append</a>   
<a href="javascript:void(0);" onclick="$('#olTestList1').prepend('<li>Prepended item</li>');">Prepend</a>

<ol id="olTestList1">
 <li>Existing item</li>
 <li>Existing item</li>
</ol>
We have to links: The first will append an item to the list, meaning that the new item will be inserted as the last item. The other link will prepend a link to the list, which means that the new item will be inserted as the first item of the list. In this example, we simply insert a piece of HTML, but we could have generated the new items with jQuery as well, or created it through regular JavaScript code and DOM elements. In fact, both the append() and the prepend() method takes an infinite amount of new elements as parameters. In the next example, we will demonstrate this as well as the ability to add elements in various forms:
<a href="javascript:void(0);" onclick="AppendItemsToList();">Append items</a>   
<ol id="olTestList2"></ol>

<script type="text/javascript">
function AppendItemsToList()
{
 var item1 = $("<li></li>").text("Item 1");
 var item2 = "<li>Item 2</li>";
 var item3 = document.createElement("li");
 item3.innerHTML = "Item 3";
 
 $("#olTestList2").append(item1, item2, item3);
}
</script>
As you can see, item1 is a jQuery generated element, item2 is a simple HTML string and item3 is a JavaScript DOM generated element. They are all appended to the list using the same call and of course this would have worked for the prepend() method too.

There are variations of the append() and prepend() methods, called appendTo() and prependTo(). They do pretty much the same, but they do it the other way around, so instead of calling them on the elements you wish to append/prepend to, with a parameter of what is to be appended/prepended, you do the exact opposite. Which to use obviously depends on the situation, but here's an example showing you how to use them both:
<a href="javascript:void(0);" onclick="PrependItemsToList();">Prepend items</a>   
<ol id="olTestList3"></ol>

<script type="text/javascript">
function PrependItemsToList()
{ 
 $("#olTestList3").prepend($("<li></li>").text("prepend() item"));
 $("<li></li>").text("prependTo() item").prependTo("#olTestList3");
}
</script>
In this example, we prepend the items, but you could of course do the exact same using append() and appendTo(). As you can see, the result is the same - only the order of what we do differs. 

Getting and setting CSS classes

Just like it's very easy to manipulate content and attributes of elements, as we saw in the previous chapters, it's equally easy to manipulate the CSS of elements. jQuery gives you easy access to changing both the style attribute, which you manipulate using the css() method, as well as the class(es) of an element, where several different methods lets you modify it.

Let's start by looking into changing the class attribute. The class attribute takes one or several class names, which may or may not refer to a CSS class defined in your stylesheet. Usually it does, but you may from time to time add class names to your elements simply to be able to reach them easily from jQuery, since jQuery has excellent support for selecting elements based on their class name(s).

I have defined a couple of very simple CSS selectors in my stylesheet, mostly for testing purposes:

.bold {
 font-weight: bold;
}

.blue {
 color: blue;
}
In the following example we will use three of the most interesting class related methods: hasClass(), which checks if one or several elements already has a specific class defined, addClass(), which simply adds a class name to one or several elements and the removeClass() methods, which will.... well, you've probably already guessed it.
<a href="javascript:void(0);" onclick="ToggleClass(this);">Toggle class</a>

<script type="text/javascript">
function ToggleClass(sender)
{
 
 if($(sender).hasClass("bold"))
  $(sender).removeClass("bold");
 else
  $(sender).addClass("bold");
}
</script>
The example is actually very simple. When the link is clicked, we send the link itself (this) as a parameter to the ToggleClass() method that we have defined. In it, we check if the sender already has the "bold" class - if it has, we remove it, otherwise we add it. This is a pretty common thing to do, so obviously the jQuery people didn't want us to write an entire three lines of code to it. That's why they implemented the toggleClass() method, with which we can turn our entire example above into a single line of code:
<a href="javascript:void(0);" onclick="$(this).toggleClass('bold');">Toggle class</a>
Of course, we can select multiple elements, where we can add or remove multiple classes, as well. Here's an example of just that:
<div id="divTestArea1">
 <span>Test 1</span><br />
 <div>Test 2</div>
 <b>Test 3</b><br />
</div>
<script type="text/javascript">
$(function()
{
 $("#divTestArea1 span, #divTestArea1 b").addClass("blue");
 $("#divTestArea1 div").addClass("bold blue");
});
</script>
First we select the span and the b tag, which we add a single class to: the bold class. Then we select the div tag, which we add two classes to, separated by a space: The bold and the blue class. The removeClass() methods works just the same way, allowing you to specify several classes to be removed, separated with a space. 

In the previous chapter, we saw how easy it was to get and set text and HTML content from and to an element. Fortunately, changing one or more attributes of an element is just as easy. We use the attr() method for this, which in its simplest form takes one parameter: The name of the attribute we wish to get:
<a href="http://www.google.com" id="aGoogle1">Google Link</a>
<script type="text/javascript">
$(function()
{
 alert($("#aGoogle1").attr("href"));
});
</script>
In this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:
<a href="http://www.google.com" id="aGoogle2">Google Link</a>
<script type="text/javascript">
$(function()
{
 $("#aGoogle2").attr("href", "http://www.google.co.uk");
});
</script>
This will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:
<a href="http://www.google.com" id="aGoogle3">Google Link</a>
<script type="text/javascript">
$(function()
{
 $("#aGoogle3").attr(
 { 
  "href" : "http://www.google.co.uk", 
  "title" : "Google.co.uk"
 });
});
</script>
The attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:
<a href="http://www.google.com/" class="google">Google.com</a><br />
<a href="http://www.google.co.uk/" class="google">Google UK</a><br />
<a href="http://www.google.de/" class="google">Google DE</a><br />

<script type="text/javascript">
$(function()
{
 $("a.google").attr("href", function(index, oldValue)
 {
  return oldValue + "imghp?tab=wi";
 });
});
</script>
We simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.

The simplest aspect of DOM manipulation is retrieving and setting text, values and HTML. These three things might seem like the same thing, but they're not. Text is a textual (no HTML) representation of the inner content for all regular elements, values are for form elements and HTML is the same as text, but including any markup.

Fortunately for us, jQuery comes with a method for each of the three, allowing us to both retrieve and set these properties: The text(), html() and val() methods. Here's a little example which will show you the difference between them and how simple they are to use:

<div id="divTest">
 <b>Test</b>
 <input type="text" id="txtTest" name="txtTest" value="Input field" />
</div>

<script type="text/javascript">
$(function()
{
 alert("Text: " + $("#divTest").text());
 alert("HTML: " + $("#divTest").html());
 alert("Value: " + $("#divTest").val());
 
 alert("Text: " + $("#txtTest").text());
 alert("HTML: " + $("#txtTest").html());
 alert("Value: " + $("#txtTest").val());
});
</script>
So a call to one of these methods with no parameters will simply return the desired property. If we want to set the property instead, we simply specify an extra parameter. Here's a complete example:
<div id="divText"></div>
<div id="divHtml"></div>
<input type="text" id="txtTest" name="txtTest" value="Input field" />

<script type="text/javascript">
$(function()
{
 $("#divText").text("A dynamically set text");
 $("#divHtml").html("<b><i>A dynamically set HTML string</i></b>");
 $("#txtTest").val("A dynamically set value");
});
</script>
And that's how easy it is to set text, HTML and values.

These three functions comes with one overload more though, where you specify a callback function as the first and only parameter. This callback function will be called with two parameters by jQuery, the index of the current element in the list of elements selected, as well as the existing value, before it's replaced with a new value. You then return the string that you wish to use as the new value from the function. This overload works for both html(), text() and val(), but for the sake of simplicity, we only use the text() version in this example:
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>

<script type="text/javascript">
$(function()
{
 $("p").text(function(index, oldText) {
  return "Existing text: " + oldText + ". New text: A dynamically set text (#" + index + ")";
 });
});
</script>
We start out with three similar paragraph elements, which text is their only difference. In the jQuery code, we select all of them and then use the special version of the text() method to replace their current text with a newly constructed text, based on the two parameters that jQuery provides for us: The index of the current element as well as its current text. This new text is then returned to jQuery, which will replace the current text with the new one. 

Introduction to DOM manipulation

One of the most important aspects of JavaScript and thereby jQuery, is manipulation of the DOM. DOM stands for Document Object Model and is a mechanism for representing and interacting with your HTML, XHTML or XML documents. It allows you to navigate and manipulate your documents through a programming language, which in the browser will almost always be JavaScript. DOM navigation and manipulation using standard JavaScript can be pretty cumbersome, but fortunately for us, jQuery comes with a bunch of DOM related methods, making it all much easier.

In the first "Hello, world!" example of this tutorial, we compared the job of finding an element and setting the text of it using first jQuery and then JavaScript. This is just the tip of the iceberg though, and in the upcoming chapters you will see just how easy it is to manipulate the content of your documents with jQuery. Read on.