Different people learn in different ways. One discussion that comes up on a regular basis is that the jQuery documentation is sometimes hard to follow for those new to jQuery. This may stem from the reference style the official documentation takes. Here we will provide another style of documentation to help those who do not like to learn from the reference style. Instead, we will use the "How-To" style. A "how to" statement will be made, then followed up with a description and some sample code.
If you would like to help expand this the HowTo's, please review this document and the links below before proceeding. But otherwise we welcome your assistance and enthusiasm.
You will require a user account to contribute to the HowTo's. If you do not already have one click the "Create Account" link in the Login block, and follow the instructions. You will receive an email with your username and password. Once logged in, you are encouraged to change the auto-generated password as soon as possible.
Authenticated users may create a book page, and can edit pages they have previously created.
jQuery is a JavaScript library. But it does use JavaScript in a way that has not been traditionally taught. Between anonymous functions and JavaScript Object Notation, a novice JavaScript user may be a little confused.
This section covers the non-jQuery specific aspects of JavaScript that will be encountered, and some of the more common techniques.
Being able to properly identify a bug, and determine where it is in the code, is a definite skill when it comes to writing ANY code. But JavaScript does not have the same legacy as languages like C/C++, Perl, PHP, etc. We are highly dependent on what the browser can tell us, or an external script debugger. So debugging JavaScript is a little different than these languages.
What follows are recommendations. All web developers follow these to some degree or another, but these tips will help track down any JavaScript code issues quickly.
Internet Explorer is notorious for giving misleading messages and/or pointing to the wrong line or file. Troubleshooting JavaScript in Internet Explorer requires the installation of third party script debuggers at best, or manual debugging (described below) at worst.
Even if you are coding for an Internet Explorer only application, working in FireFox will help troubleshoot your JavaScript MUCH quicker than working in IE alone. Of course frequent testing of the code in IE is a must as well - there ARE some differences in how IE and Firefox will interpret the code.
Go to the Firebug website. Click the "Install Firebug" button (middle right area). Restart FireFox when you are done. Now activate Firebug by clicking the checkmark in the circle, in the very bottom right hand corner of the browser window. Take the time to explore what Firebug offers. Coding JavaScript without Firebug is almost like riding a bicycle that is missing a wheel. It can be done, but having two wheels makes it SO much easier.
Some developers find this tool especially helpful in determining why code will work in Firefox, but not in Internet Explorer.
If you find yourself working without a JavaScript console, or the reported error message just isn't quite right, doing some manual debugging is needed. This could be simply determining WHERE the error occurs, or it could be determining WHY the error occurs. Knowing where and why normally leads directly to the needed fixes.
When the JavaScript console is not available, or is reporting a wrong line, finding the location of the error can become tedious, but necessary. Here's one method:
NOTE: If you are using FireFox and Firebug, you can replace all the "alert()" methods below with "console.log()". Instead of getting an alert box for each message and having to click OK, your message will appear in the Consle tab of Firebug.
Place "beacon" type messages throughout your code - specifically in and around where you think the error is occuring. This can be a simple alert() statement. Give each beacon a unique number. For example:
alert("1");
var test = document.getElementById("myID");
alert("2");
test.innerHTML = "<h2>New Heading/h2>";
alert("3");
for (var x=0; x < myArray.length; x++) {
alert("4");
test.innerHTML = test.innerHTML + "" + myArray[x] + "";
}
alert("5");
(this is very contrived code to demonstrate the beacons only....)
Now, when you run the code, you'll see a message for each one of your beacons. If you get an error before you see the third beacon, then you know your error is between beacons "2" and "3". So that is the line (or area) you need to pay more attention too. If you see all the beacons except # 4, then you know you are never getting into your loop. A closer look there shows that your array probably is not what you expect it to be.
Once you find the troublesome line(s), you can remove the beacons.
When you know what line is causing the error, but you cannot see an immediate reason for the error, dump all the variables that are involved. When we say "dump", we simply mean to show the current content or value of the variables. For instance, if we were not getting into a loop, we might do this:
alert("myArray.length: " + myArray.length);
for (var x=0; x < myArray.length; x++) {
alert("x: " + x);
test.innerHTML = test.innerHTML + "" + myArray[x] + "";
}
Because we are checking the length of the array in the loop, we want to check how many elements the array has. If we get zero back, then we know we are never getting into the array ( 0 is not less than zero, so we have a false condition, which exits the loop).
When you can not see anything wrong with your code, the problem is probably in the data being used. So check those values.
Perhaps you have a situation where you declare a person object that may or may not get a "birthday" property declared, but we want processing to continue regardless. Outputting the properties and their values is great for us Humans, but the code cannot "see" missing items. However in code we can instead just check if the property exists.
Keep in mind that JavaScript considers anything that is not zero, null, or undefined to be equivalent to a positive value. So, we can write code like this:
if (myObject.birthdate) {
alert(myObject.birthdate);
}
If the birthdate property is not defined, then our IF condition will be "undefined" or false and the alert will never be executed.
There is one minor problem here though - if the myObject variable has not been defined, you'll still get an error here. The code would need to be changed to check for the object AND the property.
if ( myObject && myObject.birthdate ) {
alert(myObject.birthdate);
}
When troubleshooting, this type of code requirement is likely to come up on a regular basis. This can apply to any object or property, or even a simple variable or function.
Sometimes we have an object and the object is valid, but the property we are trying to check is not. We could do an alert for every property, but this could be time consuming. Sometimes a simple list of properties and their values is what we need. You can do this with a quick routine:
var output = "";
for (var prop in myObject) {
output = output + prop + "; " + myObject[prop] + "\n";
}
alert(output);
This code is taking advantage of the way JavaScript treats properties. We'll just trust this will work for now (the technique is explained elsewhere in the HowTo's). If we ran this against a custom "person" object, this code might result in the following message:
name: "Bob Smith"
phone: "(555) 555-5555"
address: "123 Main Street"
If we were looking for a "birthday" property, we can very quickly see that there is no such property.
This technique is a longer form of checking for the existence of an object or property, but is useful when you need a greater understanding of what is happening with your data or code.
JavaScript provides some short hand ways to create custom objects and arrays. These short hand methods are very useful when dealing with custom objects or needing to define objects and behavior from a string (such as when using Ajax).
JavaScript Object Notation is what we are referring to. However you may see this more commonly referred to as "JSON".
These two lines are identical
var array_one = new Array();
var array_two = [];
To represent an array we use the square brackets "[" and "]". Using it like we have in the sample above, we are simply creating a new array. Inside the square brackets, we can define the items we want. Or we can use the traditional Array techniques if desired.
var array_three = [ 1,2,3, "four" ];
array_three[array_three.length] = "five";
array_three.push("six");
These two lines do the same thing:
var obj_one = new Object();
var obj_two = {};
To represent an object, we can use the braces "{" and "}". These two lines will both create a new instance of an object. While we can use the traditional techniques for working with objects on either variable now, defining the properties of an object has a few more options.
Consider a custom object to represent a person:
//Traditional method
function Person() {
this.name = "";
this.age = 0;
}
var person_one = new Person();
//
//JavaScript Object Notation
var person_two = {
name : "",
age : 0
}
The difference between these two techniques is that the traditional approach defines a "class" and then instantiates an instance of that class. The second approach creates an instance of a new object and adds the needed properties. Both techniques have their place though. You'll see the JavaScript Object Notation style used when a "one-off" type object is needed.
Notice how the properties are defined. In the traditional style we use the "this" keyword (i.e. this.name = ""; ). In the JavaScript Object Notation style we use a different style (i.e. name : "" ). The pattern here is "property : value" with multiple properties separated by a comma. Where value can be any valid JavaScript value - literal numbers, strings, objects, functions, etc.
NOTE: Do not put a comma after the LAST property. Firefox can handle this, but Internet Explorer throws an error.
With that we can now create some complex objects:
var bob = {
name : "Bob Smith",
age : 30,
hobbies : [ "Computers", "Reading", "Gum Chewing" ],
toString : function () { return this.name; }
};
We have made use of simple properties, an array, and even an anonymous function (we'll talk about that in another post). And we now have an object representing Bob in one line of code (spread out over multiple lines for readability though.
Where you see this technique used often is when a function can take advantage of MANY arguments. Instead of defining the exact order the arguments take a single object can be used instead and the appropriate properties set.
function testIt(options) {
if (options.name) { alert("the name argument is: " + options.name); }
if (options.age) { alert("the age argument is: " + options.age); }
}
You will also see JavaScript Object Notation used extensively in Ajax scripting.
One final note. When you are passing around a JavaScript Object Notation string (such as a response from an Ajax call), you need to take care that your object is properly formed. The official way of declaring a property for an object is to put the name of the property in quotes:
var bob = {
"name" : "Bob",
"age" : 30
}
If this step is not done from inside executing JavaScript, there normally is no problems. But an object declaration in string format has to be treated slightly differently to convert that string into an object. At this time, you would likely see odd behavior.
This comes to light when using the $.ajax() method of jQuery.
// retrieved string one
{ name : "Bob", age : 30 }
//
// retrieved string two
{ "name" : "Bob", "age" : 30 }
//
//Ajax routine
$.ajax({
url : "mypage.php",
dataType : "json",
error : function () { alert("An error occured"); },
success : function () { alert("We were successful!"); }
})
In this sample, if our "mypage.php" routine returned the second string, we would see the success message. If it returned the second string, we would see the error message. Troubleshooting this situation would reveal that a) the string WAS retrieved, b) the request for "mypage.php" resulted in a 200 status code (which indicates everything went well), and c) we are still getting into the error function even though no apparent error occurred. The core problem is that the first string does not follow the official form of a JavaScript Object Notation string. Once we fix that, things work as expected.
When working with JavaScript Object Notation, we sometimes want to create a function (or method if we use the OOP terminology). The traditional method of creating a function will not work well. There are a couple of ways to create methods in this situation, but we'll focus on the one jQuery favors - anonymous functions.
There is little different between a regular function and an anonymous function. The declaration syntax is a little different, and there is no function name per se that can be called. However the memory location of the function can be stored, and thus the function can be recalled as needed.
For instance:
//traditional
function sample_one(parameter_one) {
alert(parameter_one);
}
//
// Anonymous / inline function
var sample_two = function (parameter_two) {
alert(parameter_two);
};
//
//Calling the methods:
sample_one("Hello");
sample_two("jQuery Rocks!");
The traditional approach is to use the "function" keyword and then declare the name, parameters, and desired actions. An anonymous function leaves out the function name part but a reference to the function is returned.
Where this becomes especially handy is when JavaScript Object Notation is being used. Imagine we had a Person object, and we wanted to add a "growOlder()" method to this object.
//traditional
function Person() {
this.name = "";
this.age = 0;
}
//
//Function declaration:
function person_growOlder() {
this.age = this.age + 1;
}
//
// JavaScript Object Notation
var bob = {
name : "Bob",
age : 30,
growOlder : function () { this.age = this.age + 1; }
};
With the use of an anonymous function, we can declare our function right where it is needed. We do not need to create the function elsewhere and use function references. This means finding code can be done a fair bit quicker as there are no references to be resolved (when troubleshooting at least). The end results though are the same.
As you can see, the JavaScript Object Notation approach is more concise, and self contained.
Now the question comes up "when would I use this technique?". Imagine you were creating a "birthday()" routine that would take some arguments. One of the arguments needed might be to do some processing after the birthday() method is finished. We can use an anonymous function to indicate this.
birthday({
person : bob,
cleanup : function () {
if (this.person.age > 40) { alert("How's the weather up there?"); }
}
});
//
function birthday(options) {
//exit if we don't have a person
if (!options.person) { return false; }
//
alert("HAPPY BIRTHDAY " + options.person.name + "!!");
this.person.growOlder();
//
if (this.options.cleanup) { this.options.cleanup(); }
}
In our call to the birthday function, we are creating an object on the fly to pass our arguments for the function. One of these arguments is a function we want executed when the birthday routine is done - the "cleanup" property.
Another name for this cleanup property is "a callback function". Which means that when our code is done, we want it to do a call back into this other routine. jQuery makes extensive use of callback routines, or even anonymous functions just for gathering required data. The slideUp/slideDown methods, and the Ajax methods are just two examples of where this is used.
This section covers basic usage of jQuery from getting started to finding elements and working with CSS.
Starting with jQuery needs three basic steps:
A sample web page might look something like this:
<html>
<head>
<title>My first jQuery</title>
<script type="text/javascript" src="path/to/jquery.1.2.1.pack.js"></script>
<script type="text/javascript">
//this is jQuery code
$(document).ready(function () {
alert("I came from jQuery!");
});
</script>
</head>
<body>
<h2>jQuery sample</h2>
</body>
</html>
The jQuery code you decide to use depends on your needs. The rest of the How-To's on this page help to highlight what can be done. These are more simplistic examples though. Please visit the jQuery documentation or the jQuery mailing list for more details. The more advanced things you see jQuery do are usually a combination of the basics though.
A note about the different jQuery files.
jQuery tries to accomodate all types of developers. Those who want to get their hands dirty and explore jQuery's inner workings should download the uncompressed version of the jQuery library. All others probably want to use the packed version as this has the smallest footprint that is supported by all browsers. The packed version removes all extra spaces and comments to compress the library, and then encodes it to make it even smaller. The minified version of the library does the same, except it does not encode it.
A common challenge of JavaScript is executing code only AFTER the referenced elements have been defined. For instance trying to find the contents of a form element will cause errors if that form element has not been rendered to the page yet. Traditional JavaScript uses the window.onload event for this (or a <body onload="initialize();"> type of call). jQuery handles this a little differently.
//assuming an initialize() function has been declared elsewhere on the page
$(document).ready( initialize );
OR
//make use of an anonymous function
$(document).ready( function () {
//initialization code goes here
});
jQuery makes a lot of use of "anonymous" or "inline" functions. In all cases a function reference can be used in their place. (a function reference is the name of a function delcared elsewhere, without the brackets, but this makes passing parameters difficult).
The samples above are roughly equivalent to the traditional onload event with a subtle difference. The onload event only fires after all page elements have completed loading. This may cause delays if you have a large image being referenced. The jQuery ready() method is fired once the DOM tree has been populated. This may happen before all page elements have been loaded. When working with jQuery, the ready() method is the preferred way of initializing a page. However there are no rules that say you cannot use an onLoad event in conjunction with jQuery.
An added bonus of the jQuery way is that you can have multiple ready() definitions. This is the case with all jQuery events. For instance:
$(document).ready(function () { alert("Number One"); });
$(document).ready(function () { alert("Number Two"); });
In this sample BOTH alerts will be fired as soon as the DOM tree is ready. These two ready() definitions could have been anywhere in our code, separtated by many lines of other code. More on this concept when we talk about jQuery events.
Traditional JavaScript uses the document.getElementById() function to find a page element. This requires all elements to be referenced to have an ID set. jQuery has similar functionality, but can also find elements based on their class name, ordinal position, or a combination of these techniques.
//Reference an element by ID
$("#id");
//
//Reference an element by a CSS class
$(".classname");
//
//Reference an element by it's position
$("td:eq(2)"); //finds the third TD tag on the page (zero based)
//
//combination of these
$("#content .myclass:eq(1)");
//references the second item with a class of "myclass" inside
//the #content element
The string contained within the $() declaration is known as a selector. These selectors should look familiar to anyone who has worked with CSS - the style is the same (except the ordinal position sample). We reference IDs with the # character, and classes with the '.' (dot) character. And we can find elements contained within other elements with the same type of style as our CSS selectors - id/class of container, a space, then id/class of contained item. The basic CSS selector rules apply here.
All the samples above return an object reference to the item(s) that match the selector. Each of these matched items is wrapped into a jQuery object so that we can have common functionality between all matched items. Under the hood, jQuery supplies an array of matched items - even if it has only found one item. So using an array index can get us a reference to the raw DOM object. Consider the following:
$("p")[1];
This code will find a reference to all paragraph tags, wrap them in a jQuery object, and then we indicate we want the second element from the resulting array. This gives us the same type of object as if we had used the document.getElementById() method to find that paragraph. However, this technique is rarely needed - jQuery provides methods to access most object properties.
jQuery has other techniques for selecting elements. It provides a number of "filters" and form element references as well as the basics we've already discussed. For full details, check out the online documentation.
A selector may result in more than one element being referenced. For instance doing $("div") would result in a reference to ALL DIVs on the page being found. If we wanted to set the text on all the DIVs to a common value we might do something like this:
$("div").text("this is a div");
This will apply the text() method to all the elements our selector has matched. In this case, all the DIVs. This is a very handy feature, though sometimes we need to do further processing on each of the matched elements. We could set up a loop and use the underlying array of elements, but jQuery provides us with an easier way - the each() method. Let's imagine that we had 10 DIVs that contained numbers, and we need a way to calculat the sum of all those numbers. We could make use of the each() method for this.
var total = 0;
$("div.theNumbers").each( function () {
total = total + parseFloat( $(this).text() );
});
alert(total);
The magic here is the each() method. It takes a function as it's parameter and that function is executed for each of the elements matched by our selector. Additionally, the position of the element in our list is passed to the function as a parameter. If we need to make use of this position detail, then we just need to provide a parameter name (i.e. function (pos) ). For our sample problem we don't need the position so have just ignored it.
Because the function is executed for each of our matching elements, we can make use of the this keyword. Within our function, this will refer to the current DOM element. So by saying $(this), we indicate we want the jQuery object for the currently mactched item. From there we can grab the text contained in the item via the .text() method. In our sample this text should be a number, however the .text() method will return a string representation of the number to us. So we extract the numeric value via the parseFloat function (which is a native JavaScript function). The above code would work fine if we had 2 or 200,000 DIVs on the page - as long as they each had the "theNumbers" class.
A very common task of JavaScript is to change the page contents. This can be simple text changes to existing page elements, or adding new HTML elements. jQuery provides us with two methods for this - the text() and html() methods. If we just want to set some text, we use the text() method. The value we want to set is included as a parameter to the method. The same with the html() method - except it's parameter can be a string of HTML or a reference to an HTML element.
//change the text of a target paragraph
$("#targetParagraph").text("This is new text");
//
//change the HTML of a target div
$("#targetDIV").html("<ul><li>Item One</li><li>Item 2</li></ul>");
Sometimes we want to look at the existing text or HTML of an element and use it to do further processing. Getting these values is as simple as calling the text() or html() method without any parameters. For instance, if we wanted to show an alert for these values we might do this:
alert( $("#targetParagraph").text() );
alert( $("#targetDIV").html() );
It should be noted that both the .text() and .html() methods will return strings. Even if our element only contains a numeric value, we will get a string of that nuber back (i.e. "3.14" vs 3.14). This is a problem when we do math. If math calculations are being done with these values, then we'll have to extract the numbers via the native JavaScript function of parseInt or parseFloat.
<div id="one">1</div>
<div id="two">2.5</div>
. . .
var total = $("#one").text() + $("#two".text();
alert( total );
// resuts in "12.5";
//
var total = parseFloat( $("#one").text() ) + parseFloat( $("#two").text() );
alert( total );
//results in 3.5 as expected.
When we are manipulating our pages, we sometimes need to get the value stored as an attribute to an HTML tag, or set an attribute to some value. This is accomplished via the .attr() method. This parameter takes two parameters - the attribute to work with, and the value to set the attribute to. Not specifying the second parameter will retrieve the current value.
//getting the ID
alert( $(".target").attr("id") );
//
//Setting the ID
$(".target").attr("id", "targetID");
//
//Changing where a form will be submitted to
$("#myform").attr("action", "otherpage.php");
The .attr() method can be used on any element. If the asked for attribute does not exist, null or undefined will be returned when requesting it's value. If setting a non-existent attribute, that attribute will be created.
If more than one attribute needs to be set then an object containing key/value properties can be used.
$("#myimg").attr({
src : "myimage.gif",
title : "My Image",
alt : "My Image",
border : 0
});
Getting or setting the values of form elements can be a challenging chore with traditional JavaScript. We use different methods to find or set the value of a text box, radio button, or select list. jQuery provides the val() method to make this easier for us. Using val() without a parameter will get the value of any referenced form element. Giving the method a parameter will set the form element to the value indicated by the parameter.
//getting values
alert( $("input#mytextbox").val() );
alert( $("select#mylist").val() );
alert( $("input#myradio").val() );
//
//setting values
$("input#mytextbox").val("New text value");
$("select#mylist").val("ItemOne");
$("input#myradio").val(3);
Getting and setting a form element's value is not usually what we want when we have checkboxes or radio buttons. Rather, we want the value of the selected/checked item. jQuery has a selector filter to help with this called :checked. If we had 10 radio buttons, each of which had a class of "group1", we can find the selected itme with this:
$(".group1:checked").val();
Remembering that our selector can reference more than one item, and that a checkbox can have more than one item checked, we run into problems. In this case we can make use of the .each() method to build that string.
var result = "";
$(".mycheckboxes").each( function () {
result = result + $(this).val() + ", ";
});
//
alert(result);
If we need to set the value of a checkbox or radio button, then we need to a way to reference the desired item. This could be done by giving that item an ID value when creating the page, or by using one of the selector filters. If we wanted to change the fourth check box to have a value of "Item Four", we could do this:
. . .
<input type="checkbox" id="box4" name="box4" value="4">
. . .
$("#box4").val("ItemFour");
OR
$("input:eq(3)").val("ItemFour");
// Note 1: Assuming the inputs on the page are only checkboxes
// Note 2: Remember that our position is zero based
Once we have a reference to an HTML element, sometimes we need to know what element contains it. We can get this information from the DOM tree by asking for the element's parent.
var pid = $("#mytarget").parent().attr("id");
Occasionally we need to find an item that is containing our target element, but is further up the DOM tree than the immediate parent. Imagine we had a particular table cell, and we need to know what DIV contains the table we are in. For this we use the .parents() method. This method returns an array of all the parent elements up to to the document itself. If we need a specific item out of that list, we can pass a selector to the method.
$("#target").parents("div");
We often need to find a particular element that is contained within our selected item. This is accomplished with the .children() method. This method returns an array of all the immediate children for an item. The results can be filtered by passing a selector to the method. So, imagine we had the ID for a table row, and we wanted to see the value of the table cell that had the class of "total".
$("#theRow").children("td.total");
If needing to find a child of a child, you'll need to call children multiple times, or use the .find() method.
$("#theRow").children("td").children("div.total");
OR
$("#theRow").find("td > div.total");
Adding and removing CSS classes is a great way to highlight changes to our pages. jQuery provides the .addClass() and .removeClass() methods.
$("#target").addClass("newclass");
$("#target").removeClass("newclass");
Both methods can take multiple class names, which will be added or removed as needed.
Another method can be used to acheive similar results - the .toggleClass() method. If the class does not already exist on the element,
it is added. Otherwise it is removed.
$("#target").toggleClass("newclass");
Changing the style of an element is very useful to show a reaction to a user event, or just to set up the look and feel of an element. jQuery provides the .css() method for this. The simplest form of this method is to specify a style as a parameter. With this single parameter jQuery will tell use the current value for that style. If we add a second parameter, jQuery will set the style in the first parameter to the value of the second parameter (key/value).
alert( $("#mydiv").css("font-family") );
$("#mydiv").css("font-family", "sans-serif");
This is fine when we only want to set a single value. When we want to set multiple styles we have the option of passing an object as the only parameter, with each property of the object being the style, and the property value being the value to set.
$("#mydiv").css({
"font-family" : "sans-serif",
"font-weight" : "bold",
"border" : "1px solid red"
});
CSS is often used to set the height and width of an element. But this height and width may be modified by our browsers when the page is rendered. A border, margin, or even padding could affect the value. Or maybe we have added an element from within JavaScript and we now want to know how much space it is taking. jQuery provides two methods for determining the rendered height and width, or setting the height / width values. These are the .height() and .width() methods. Calling these methods without a parameter retrieves the height/width in pixel units. Specifying a parameter will set the height/width to the parameter value.
var w = $("#target").width();
var h = $("#target").height();
$("#target).width(w / 2);
$("#target).height(h / 2);
If more detailed information related to height and width are needed (position, offsets, etc.), the dimensions plugin can be used.
A common question comes up very frequently - "how do I know if XXX exists". The XXX could be a particular DIV with a class, or it might be an ID. The issue is common enough that it has been listed in the jQuery FAQs (http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_...).
Some people attempt to just check the jQuery object for the specified selector:
//This will not work
if ( $("#myid") ) {
//do something
}
This will fail. The jQuery object will ALWAYS return something. When we say $( ) we are asking for a jQuery object. So we get one back. The above code will always equate to TRUE.
The jQuery object contains a list/array of the elements that match our selector. So we can ask for the length of this internal list. The jQuery kindly exposes this length for us as the .length property. If the length is greater than zero then we have at least one object that matches our selector.
if ( $("#myid").length > 0 ) {
//do something
}
So now the only question is what we are testing. This is defined by the selector we use. If we want to know if a particular ID exists, we would use a selector of "#theID". If we were trying to determine if a DIV with a particular class existed, we would use the selector of "div.theClass".
if ( $("#theID").length > 0 ) { alert("The ID exists"); }
if ( $("div.theClass").length > 0 ) { alert("The DIV exists"); }
In this way we can check to see if ANY element exists.
Removing a page element is very easy, once you have a reference to it. Use the standard methods for getting the reference (jQuery selectors, etc.) then use the .remove() method.
$("#myUnWantedDIV").remove();
This code would remove the referenced element (if found), and everything within the element. Basically, that node is removed from the DOM tree.
You can get a little fancier by using the jQuery manipulation tags. For instance, to remove everything in the parent of the target element, we could do this:
$("#myUnwantedElement").parent().remove();
Ajax is a technique for requesting data from the server, without reloading the page. In essence a browser object is used to make the request and we can manipulate both the object and the results as needed.
jQuery provides a number of Ajax methods that make the developer's life very easy.
The inherent JavaScript security restrictions prevent us from accessing files or other resources (outside of web accessible content) directly. This means we cannot access a database directly. There is a way around this though, and that is utilizing Ajax.
Via Ajax we can pass a request to a database with a server side resource, get some results back, and then update our page with those results. The results can be whatever we'd like - full tables, report data, or just what background image the user likes.
There are a number of considerations before undertaking this task.
Once we have this information we can then build the Ajax request.
Samples:
Let's do an example. Actually, we'll do two just so we can demonstrate different approaches. We'll use the employee details for our sample. Imagine we have a list of employee names on the page ( LI tags), as well as an empty DIV after each name (but within the LI tag). We want to add functionality so that when a name is clicked, we ask for the employee details and populate the corresponding DIV. We'll even add in some animations and make the DIV slide up/down.
Sample 1
Right, so first, where is the information coming from? We'll suppose a page has been created for this and is called "employee_detail.php". It takes an ID parameter - which is conveniently store in the ID attribute of our LI tag. The server side page returns an HTML table (for our first sample). We already know we want that table in our DIV. We could handle this situation like so:
$(document).ready( function () {
$(".employeeNames").click( function () {
$(this)
.children("div")
.load("employee_details.php", { id : this.id })
.slideDown();
});
});
We are using a shortcut here - the .load() method. We tell jQuery to ask for the results from "employee_details.php, and set the "id" parameter to the value represented by "this.id". "this" is always context sensitive, and is a way to reference the current element. The element we are dealing with in our click() function is the LI tag that received the click - so that LI tag is "this". When we get the results back, we add it to the referenced element - in this case the DIV tag that is a child of the clicked LI tag. The moment the LI tag is clicked, we slide the detail DIV down (assuming it was previously hidden).
Sample 2
Now using the same basic sample, lets imagine that we needed to highlight supervisors in a different color. We'll use a different server side file this time - "employee_json.php", which will return a JavaScript object with the employee data. This object has properties for name, position, start date, and phone number. We need to show this information in a table, but highlight the containing DIV with a different color if the position property is "supervisor".
$(document).ready( function () {
$(".employeeName").click( function () {
var clickedItem = this;
$.ajax({
url : "employee_json.php",
data : "id=" + clickedItem.id,
dataType : "json",
success : function (result) {
var tbl = "";
tbl += "Name:" + result.name + "";
tbl += "Position:" + result.position + "";
tbl += "Start:" + result.start_date + "";
tbl += "Phone:" + result.phone + "";
tbl += "";
//
$(clickedItem).children("div").html(tbl).slideDown();
if (result.position == "Supervisor") {
$(clickedItem).children("div").css("background-color", "#ddd");
}
}
})
});
});
Here we are setting up the same .click() handler as in sample 1. The difference is that we are using the $.ajax() method instead of the .load(). We tell the $.ajax() method what page to ask for, what data to pass to that page, and that we are expecting a JSON result. We also tell the routine what to do if everything happens successfully. Because the "success" function isn't run until later (remember Ajax is asynchronous), we store a reference to our clicked item and use that reference in our function instead of "this" (which would be the wrong reference at that time). In our success function, we simply build a string containing the HTML for a table, and then place that table into our DIV and show it via the slideDown() method. We do a check on the position, and if it is a supervisor position, we change the background color of the DIV.
Final Notes
Well we are not directly accessing a database, we are utilizing the results of a database request. We have seen two different approaches that can be used - use the results directly, or do other work with the results. In this way, jQuery (and JavaScript) provides some very flexible approaches to getting new data.
Imagine you have a DIV on your page, and when a user clicks a link we want to replace the contents of that DIV with the HTML stored in a different file on our server. The easiest way to accomplish this is with the .load() method.
$("#mylink").click( function () {
$("#mydiv").load("page2.htm");
return false;
});
Here we have set up an event handler. But it's the second line that really does what we're after. It gets a reference to our DIV, then says to load the contents of "page2.htm" into that DIV. That's it. All nice and easy.
But there are always those situations which do not quite fit into the "nice and easy" category. Perhaps we need to take some action after the content is loaded. The .load() method allows for some of these needs, but to really cover all the Ajax needs, look into the $.ajax() method.
In cases where you need to pass data to your called page, you can use an object containing property/value pairs as the optional second parameter.
$("#mydiv").load("page2.php", { id: 4, name: "Bob" });
And in the cases where you need to do further action after loading the content into the DIV (maybe assigning event handlers to the new content?) a function can be passed as the third parameter (or second if the data parameter is omitted).
$("#mydiv").load("page2.php",
{ id: 4, name : "Bob" },
function () { $("#mydiv a").click( function () {
alert("I was clicked");
return false;
}
}
);
Here we are changing the event handler of the anchor tags that were in the loaded content. But, we are not limited to assigning event handlers - we can do whatever we'd like in the .load() methods callback function.
Our users may get confused if they initiate an Ajax driven process but have no indication that something is happening. They may even think things are broken and abandon or abuse the application trying to fix it (clicking the link again and again.... ).
We can avoid this problem by simply showing a "loading" indicator of some sort. Some applications show the text "Loading...", while others use an animated image. Either way we can provide these visual indicators by hiding or showing content on our page.
To begin, we need the content. A typical approach is to place a DIV where we need it, and in that DIV we include an image.
We have assigned an ID value to our DIV so we can easily refer to it. We have also set our display style to "none" so that the DIV is hidden when the page first loads.
Now, we need to tell that DIV to show itself when an Ajax method is in process, and hide itself when that process is done. We use the .ajaxStart() and .ajaxStop() methods for this.
$("#ajaxindicator").ajaxStart( function() { $(this).show(); } );
$("#ajaxindicator").ajaxStop( function() { $(this).hide(); } );
OR
$("#ajaxindicator").ajaxStart(function() {
$(this).show();
}).ajaxStop( function () {
$(this).hide();
});
The second sample (after the OR) is identical to the first, except we are making use of jQuery's chaining abilities to continue referring to the same element. In both cases we are first getting a reference to our #ajaxindicator DIV (we could have called it #bob instead if we wanted - as long as the DIV's ID attribute was changed accordingly). Now that we have the reference to our DIV we say that when an Ajax method starts, we want to show the DIV ( $(this).show() ). Then we say that when the Ajax method stops we want to hide the DIV ( $(this).hide() ).
Within the .ajaxStart() and .ajaxStop() we can do anything we'd like that would make sense. Perhaps we need to remove some page elements, or want to set the background color or styles for the elements being affected. This is the place to do it.
There are other Ajax events we can respond to in a similar manner - there is the .ajaxSuccess(), .ajaxError(), and .ajaxSend() events. Making use of these other events would follow a similar pattern as our sample code above. All the details can be found on the official jQuery Ajax documentation.
All other jQuery Ajax methods are simply convenient methods to hide the details of how Ajax is done. But with the convenience we loose some capabilities. The $.ajax() method gives those capabilities back to us. Using the $.ajax() method we can even ignore the convenience functions of .load(), .get(), .post(), etc.
The $.ajax() method takes a single parameter - an object with property/value combinations for our needs. These options are all defined in the official documentation, but we will cover the basics here.
The following sample is serves the same purpose as the .load() method:
$.ajax({
url : "page2.htm",
success : function (data) {
$("#mydiv").html(data);
}
});
Remember whitespace is ignored, so that could ALL be on a single line. But this style is a little more readable.
We use the url property to indicate what page we want to load. When we have successfully loaded our data, we call a function (declared inline) and pass the data as a parameter. Then we set the HTML of our target DIV to whatever is in the data variable.
This is great, except all too often we need to pass details to the server side page, or handle the results in a different format - xml, json, etc. And what about when the request encounters an error? And how do we POST data to a server side page, rather than using an HTTP GET type of request?
Here's a typical sample of what the $.ajax() call would look like that can handle all of the above issues. We'll dissect this below.
$.ajax({
url: "serverpage.php",
type: "POST",
data: "param1=one¶m2=" + $("#input2").val(),
dataType: "json",
error: function (xhr, desc, exceptionobj) {
alert(xhr.responseText);
},
success : function (json) {
if (json.error) { alert(json.error); return; }
var output = "";
for (p in json) {
output += p + " : " + json[p] + "\n";
}
alert("Results: \n\n" + output);
}
});
Lets tackle this line by line:
With these lines alone we can emulate the .load(), $.get(), $.post(), and get $.getJSON() methods, but still only need to learn a single method. The $.ajax() method gives us the greatest flexibility over working with Ajax via jQuery. An exploration of the other options will expand our capabilities here even more.
Asynchronous JavaScript and XML (aka Ajax) is a great technique for refreshing your web page without forcing a full reload of the page. It allows developers to ask for only pertinent parts of the page, resulting in a much more responsive web site. But working with Ajax can be challenging for those just getting started.
An Ajax call is processed like this:
S B
E <---- Standard HTML Request ---- R
R ---- HTML Response -------------> O
V W
E <---- Ajax Request ------------- S
R ---- Ajax Response -------------> E
R
First, the browser requests a web page as usual. It gets a response and renders the page to the screen. At this stage, some JavaScript is involved to set up when an Ajax request is made. This could be a timer to simply keep part of the page up to date, or it could be in response to a user action - typing, clicking, etc.
At some point an Ajax request is sent to the server. This is done WITHOUT reloading the web page. The "XMLHTTPRequest" object is used to make this request. A response is then sent back. The server at this point doesn't know (or care) if it is dealing with a browser or not - it got a request and has responded. The browser knows when the response has arrived (via the XMLHTTPRequest object), and then does further processing on that response. It could be as simple as changing the innerHTML of a DIV to the HTML code returned, or it could be building complex tables based on the resulting XML.
(disclaimer - some coding languages DO make a distinction between a standard HTML request and an XHR (aka Ajax) request. That details is for a different web site though...).
The important point here is to note that there are two parts to an Ajax request - the server side, and the browser side.
We need to create a file that can be requested from the browser. This could be a regular HTML or text file, or it could be server side code (a la PHP, Perl, .NET, etc.). Regardless it must return something to our browser.
The JavaScript support forums/IRC Channels, etc. are full of requests for help that eventually boil down to the server side resource is resulting in an error. If you get an error from the server side resource(s), then the rest of the process will be suspect as well.
A common troubleshooting technique when dealing with Ajax is to load the server side resource directly. For instance if we are calling "thelist.txt", then we should be able to punch in the URL for that file. If that doesn't result in what we have expected then our URL is wrong, or the file has a problem. These would need to be resolved. If we are asking for "my_data.php", then we should punch in the URL for that file and see what we get back. If PHP or database errors are being reported, then these issues need to be resolved. If you are using a POST to pass data to your server, the request you need to make may be more troublesome. Using Firebug will help spot errors and see just what is being passed to your server.
We STRONGLY recommend using FireFox and Firebug when working with Ajax. Firebug reveals a great deal of detail about your Ajax requests - including the HTTP request and response, the parameters passed to the server regardless of the request method (GET/POST), and the results returned by the server. The results is much the same as asking for the page directly in the browser.
When you know your server side processing is doing what it should in a reliable manner, you are ready to look at the browser side of the equation.
In your browser, you need to make an Ajax request. jQuery makes this very easy. But the question is what you are doing with the response you will get. If you are asking for XML data, you will probably be processing that data to build parts of your interface. Or perhaps you are simply deciding what further action is needed. If you are getting raw HTML, you will likely be placing that value into your page somewhere. This part is highly dependent on your own needs. But we can help you in getting to that point.
We'll focus on using the $.ajax() method here. It will highlight all the important parts of the Ajax process we need to worry about.
While the above comments are hidden in some degree or other with the other Ajax methods in jQuery (.load(), .get(), etc.) they are all still there. Understanding Ajax on it's own is VERY useful to doing it with jQuery.
To highlight some of the above, here is some sample code:
$.ajax({
url : "employee_sales_json.php",
type : "POST",
data : "employee=" + $("#employee_id").attr("id"),
dataType : "json",
error : function (xhr, desc, exception) { alert(xhr.responseText); },
success : function (data) {
//assuming an Array of objects was retreived
var output = "<ul>";
for (var x=0; x < data.length; x++) {
var sale = data[x];
output += "<li>";
output += "Type: " + sale.type + ", ";
output += "QTY : " + sale.qty + ", ";
output += "Total: " + sale.total;
output += "</li>";
}
output += "</ul>";
$("#employee_sales").html(output);
}
});
You can see here that we have "posted" the employee ID to our "employee_sales_json.php" file. We have indicated we are expecting our results to be a JSON object. We are handling any unexpected errors by doing an alert on xhr.responseText. The first argument passed to the error function is the raw XMLHTTPRequest object. We could have easily put this into an "error div" and any HTML in the error message would be rendered. Finally we handle the data resulting from our request. The data is passed as an argument to the success function. The name of the parameter is irrellevant - some use "json", some use "data", some use "html". Call it something meaningful to you.
In this sample we are processing a JSON response and building up an output. The nice thing about using JSON like this is that this exact same server resource can be used in a different manner. Perhaps we have a select list that needs to show the recent "sale types" for the employee. This same code could then be utilized to populate that list.
The heart of any Ajax request is the XMLHTTPRequest (XHR) object. Requests are (normally) done in an asynchronous manner. This means we need some way to track what is happening to the object. For this reason the XHR object has two properties - "readyState", and "status". The status is simple - it exposes the HTTP status code. If everything went ok, the status would be "200". If the requested page couldn't be found, the status would be "404". The readyState isn't quite as straightforward though.
The readyState has 4 states we are concerned with:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
State zero indicates we have only instantiated the object, but have not begun using it.
State 1 indicates a request has been made.
State 2 indicates a response has been received
State 3 indicates that the browser and server are communicating.
State 4 indicates that we have received a response and the XHR object has completed it's processing.
Usually we are only concerned with state # 4. A common snippet of code makes use of the readyState AND the status.
. . .
if (xhr.readyState == 4 && xhr.status == 200) {
//we can proceed with processing.
}
Where jQuery is concerned, the "success" function is not fired until the readyState is at "4", and we have a "200" status. Any other status would indicate an error (well, not quite, but close enough for now). Any other readyState indicates the response has not been received yet.
While this level of detail is not really needed when using jQuery, it is still good to know in general. It helps to figure out some glitches, and gives a peek into what jQuery is doing for us. (Or we can just go look at the source code....)
Some of the features of the "Web 2.0" era websites is their ability to animate themselves. This is a good tool for adding an extra level of pizazz to a website, and if done well (and in moderation) can add a more professional look to your pages.
jQuery provides some methods for accomplishing basic animations.
jQuery has the .hide() and .show() methods for hiding and showing content respectively. These essentially set the CSS display property to none/block. But this doesn't help when you want something to fade in.
The good news is that these methods take an argument to indicate how long the hide/show process should take.
$("#mydiv1").hide("slow");
$("#mydiv2").hide(3000);
$("#mydiv3").show("fast");
$("#mydiv4").show("2000");
The argument we use can be one of the known strings ("slow", "normal", "fast"), or it can be a numeric value indicating the number of milliseconds. If a speed is specified, then all matched elements will have their opacity changed over the specified period of time to either hide or show the element(s) as required.
Sliding content down into place is a nice feature that can make an interface entertaining and engaging. But more importantly it can be used to reduce clutter when there is a lot of content to be shown. So it is also important to hide content when it's not in use. But the hiding of the content should complement the showing routine. jQuery provides three simple animation routines for this purpose - the .slideDown(), .slideUp(), and .slideToggle() methods.
The three methods all take the same arguments - a speed, and a callback. Both of these are optional.
In all three cases, you get a reference to the element(s), and then call the methods:
$("div.effects").slideDown();
$("div.effects").slideDown("slow");
$("div.effects").slideDown(5000);
$("div.effects").slideDown(500, function () { alert("Done!"); });
//
$("div.effects").slideUp();
$("div.effects").slideUp("slow");
$("div.effects").slideUp(5000);
$("div.effects").slideUp(500, function () { alert("Done!"); });
//
$("div.effects").slideToggle();
$("div.effects").slideToggle("slow");
$("div.effects").slideToggle(5000);
$("div.effects").slideToggle(500, function () { alert("Done!"); });
The .slideToggle() method is a shortcut. It will check to see if the element is visible - if it is, the .slideUp() method is initiated. If it is not visibile, the .slideDown() method is initiated.
While jQuery itself provides many amazing capabilities, we still need to develop the logic to do various things. But why recreate the wheel, so to speak, when someone else has already done the work and made it available to us to use. jQuery plugins provide anything from low level coding assistance to high level interfaces with only a few lines of code. How to use of these plugins is what this section is about.
The first challenge of using a plugin is finding one that works for your needs. Start with a visit to the jQuery Plugins page. Take some time to review what is here.
Tip: Click the All Plugins link under the Browse Plugins section on the left. Then use your browser's Find capability (usually CTRL-F) to search for a keyword related to what you are looking for. Use the Find Next option (usually F3) to find the next occurance. You'll find your plugins much quicker.
When you have found an interesting plugin, click on the name of that plugin to go to it's details page. Here you can download the necessary file, go to the Home Page (if one is specified), read the documentation (if available) or view outstanding issues with the plugins. It is a good idea to visit the home page for the plugin as that is usually where you'll find the best documentation.
When you find the plugin you are interested in, download the file and use it in your code.
The jQuery plugin page is NOT the only place to find plugins. There are many on the Net that have not been setup here. A Google Search is also a good starting point. For instance searching for the phrase "jQuery gallery" will also find some gallery type plugins. However using Google this way may mean more time is needed for searching and analyzing what you find. (Great way to learn things though.)
We can't tell you how to use EVERY plugin out there, but they all follow a similar pattern to get started. The problem is that each plugin does something different and we can only tell you how to get to the point where the plugin is available for use. Beyond that is highly dependant on the plugin itself. But we can address this somewhat.
<script type="text/javascript" src="path/to/plugin/library.js">
<style type="text/css">@import url(/path/to/stylesheet.css);</style>
OR
<link rel="stylesheet" type="text/css" href="/path/to/stylesheet.css" />
//sample of using the tablesorter plugin
$("#mytable").tablesorter();
Here is a sample of the includes for a live web page that is using multiple plugins.
<script type="text/javascript" src="js/jquery-1.2.1.pack.js"></script>
<script type="text/javascript" src="js/ui.tabs/ui.tabs.js"></script>
<script type="text/javascript" src="js/jqModal.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pack.js"></script>
<script type="text/javascript" src="js/jquery-calendar.pack.js"></script>
<script type="text/javascript" src="js/jquery.timeentry.pack.js"></script>
<script type="text/javascript" src="js/jquery.mousewheel.pack.js"></script>
<script type="text/javascript" src="js/jquery.corner.pack.js"></script>
<script type="text/javascript" src="js/myapp.js"></script>
<style>
@import url("js/ui.tabs/ui.tabs.css"); /* tab styles */
@import url("css/jqModal.css"); /* jqModal styles */
@import url("css/blue/style.css"); /* Tablesorter styles */
@import url("css//jquery-calendar.css"); /* datepicker styles */
@import url("css/style.css"); /* application specific styles */
</style>
Learning jQuery has an excellent posting on recommended practices when creating a custom plugin. If you are moving beyond a simple plugin, this post is a great guide.
The clueTip plugin is a good tool for showing "popup DIVs". These DIVs can contain more information (such as traditional tooltips), or can become part of an applications interface and allow interaction within the popup. The contents of the popup can either be hard coded on the page, or loaded via Ajax.
The documentation for clueTip is thorough and should be the primary source of information when using clueTip. However there are some topics that are not fully revealed. One such topic is passing dynamic data to an Ajax call, and then modifying the the results when they are retrieved and displayed.
NOTE: All clueTip options are defined at http://plugins.learningjquery.com/cluetip/#options. Please refer to this to learn more about the options used below.
For this sample, imagine you have a number of employee names listed as anchors, and when you click each one you want to see the details for that employee in a popup. We can do this by assigning a common class to these links (we'll use "employeeDetails"), and putting the employee ID into the ID of the anchor tag. To help keep the anchor IDs unique, we'll prefix the employee ID with "employee_". We'll assume the server side code is returning HTML, and that this HTML does not need any further processing before being displayed. And finally, if the user clicks the employee name in the popup, then we'll navigate to an edit page for that employee (interaction with the popup).
<a href="#" id="employee-123" rel="employeeData.php">Employee</a>
OR, from in code:
$(".employeeDetails").attr("rel", "employeeData.php");
clueTip uses the "rel" attribute to store the file it should call. The attribute used can be changed as an option to the clueTip method, but the default is fine in most cases. Think of the value we specify for the rel attribute to be the same as the "url" property of a $.ajax() call.
$(".employeeDetails").cluetip({
closePosition : "title",
sticky : true,
mouseOutClose : true
});
The values we have passed indicates we want a "close" link in the title area of the popup, the popup should not close when we move off the triggering element (make it sticky), but it should close if the mouse moves inside the popup then moves outside.
ajaxSettings : {
type : "POST",
data : "id=" + this.id
}
The ajaxSettings are identical to the $.ajax() method - except the "error", "success", "complete", and "url" properties.
onShow : function () {
$("#popupEmployeeName").click( function () {
window.location.href = "editEmployee.php?id=" + this.id;
$("#cluetip-close").click();
return false;
});
}
This is saying that when the popup is shown, we want to assign a click event handler to our #popupEmployeeName element. This handler will set the location of the web page, close the clueTip popup (by triggering a click event on the Close link), and prevent any further processing of the click. Our browser should navigate to the desired page at that point.
The onShow property is the right place to assign event handlers, or do any last minute tweaks to presentation of the data - like setting classes or styles.
Putting it all together, our sample call would look like this:
$(".employeeDetails").attr("rel", "employeeData.php").cluetip({
closePosition : "title",
sticky : true,
mouseOutClose : true,
ajaxSettings : {
type : "POST",
data : "id=" + this.id
},
onShow : function () {
$("#popupEmployeeName").click( function () {
window.location.href = "editEmployee.php?id=" + this.id;
$("#cluetip-close").click();
return false;
});
}
});
jQuery UI is a set of themable widgets and interactions, built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.
The core of the library revolves around different mouse interactions, namely drag and dropping, sorting, selecting, and resizing.
The UI Datepicker plugin provides a dynamic and handy popup calendar for selecting dates. It is very flexible and can be configured and themed in different ways.
The definitive sample of what can be done with the Datepicker can be found at the official documentation or at the demo site.
To get started, download the CSS and JavaScript files. Both of these are available via the demo page. (Scroll down a little to the "Use jQuery UI Datepicker" section...).
With these two files, include them AFTER the jQuery library is included.
<script type="text/javascript" src="jquery-1.2.1.packed.js"></script>
<style type="text/css">@import url(ui.datepicker.css);</style>
<script type="text/javascript" src="ui.datepicker.js"></script>
Next you set up an input box to be a date field:
<input type="text" id="start_date">
And finally you apply the datepicker to the field.
<script type="text/javascript">
$(document).ready( function () {
//apply the date picker to the input field
$("#start_date").datepicker();
//
//another sample, with some options
$("#start_date").datepicker({
showOn: 'both',
buttonImageOnly: true,
buttonImage: 'calendar.gif',
buttonText: 'Calendar'
});
});
</script>
The full list of options can be found on the documentation page or via the demo page.
This section shows how to assign event handlers, remove them, and trigger individual events.
Lets face it, web pages need to react to the users. We use events to handle this. Traditional JavaScript can be troublesome with regards to event handling due to browser differences. There are a number of addEvent functions available on the web to help with this (and they DO work well), but jQuery takes care of this for us.
There are a few different ways to handle events. The simplest is to pass the handler to the event helper.
$("#mydiv").click( handlerFunction );
//
//Or with an anonymous function
$("#mydiv").click( function (eventObject) {
alert("I was clicked");
return false;
});
In the first sample we are using a function reference, while in the second case we declare our function inline. We have the option of using the event object within our function if desired. It is passed as a parameter to the called function, so we just need to provide a variable name for it. But we can also ignore the event object if we don't need it.
Notice that the anonymous function returns false when it is completed. Returning false in an event helper will prevent the default processing from occurring. Imagine the click event on an anchor tag - our code would execute, but the anchor itself is supposed to navigate to the specified HREF. We can stop this by having our code return false. This largely depends on your needs and what you are trying to do. In some cases you want the default processing (typically blur/focus/keypress type events), and in others you do not (click events for example). jQuery does not force a behavior on you.
Just like regular JavaScript where there is an event handler for mouse, keyboard, and resizing events, jQuery provides an event helper for each of these. For instance if you needed to respond to the mouseover event, you can use the .mouseover() event helper.
$("#mydiv").mouseover( function() { $(this).text("Hi Mouse!"); } );
Another method to assign an event handler is to use the bind() method.
$("#mydiv").bind("click", data, function (e) { alert("I was clicked"); });
The bind() method takes three arguments.
A slight variant of the bind() method is the one() method. The one() method takes the same arguments as the bind() method, but will only execute the event handler once for each matched element. If we were dealing with a click event, using one() would equate to all other click events on our object being removed, and only this one being used. This can be useful when you are assigning behaviors dynamically.
Sometimes we need to stop a page element from handling an event it has been previously configured to respond to. To do this, we use the .unbind() method.
$("#mydiv").unbind("click");
If the unbind() method is called without any arguments, then ALL event handlers are removed from our matching elements. If an event type is specified (string value just like in the bind() method), then all handlers of that particular type are removed. If a handler function is passed as the second parameter, then only THAT handler function is unbound.
When assigning event handlers dynamically, using the .one() method helps, but can be simulated with
$("#mydiv").unbind("click").click( function () { alert("Hello"); } );
This would force only a single click handler.
It is handy to be able to just "pretend" an event has happened so that the corresponding event handlers are called. To trigger an event like this jQuery allows us to just call the correct event helper without any arguments.
$("#mydiv").click();