Introduction to jQuery
jQuery is a popular and easy-to-use JavaScript framework. jQuery makes difficult JavaScript tasks easy, often by taking the pain out of cross-browser JavaScript. The entire jQuery library consists of only a single JavaScript file, which simplifies its inclusion.
You can use a content delivery network (CDN) to access a hosted version of jQuery. Google hosts jQuery and other libraries through its API website. This means that you can include jQuery in your web pages and JavaScript programs without having to host the file locally on your server.
You include jQuery in a web page in the same manner as you would any other external JavaScript file - with a <script> tag pointing to the source file.
Basic jQuery Syntax
When you include the jQuery library in a page, jQuery adds a function called jquery(). There is a shortcut to the jquery() function: $(). Rather than typing jquery() each time, you access the jQuery library by using a dollar sign followed by parentheses.
Like all JavaScript code, jQuery statements should end with a semicolon. You can use either single or double quotation marks as selectors within jQuery.
Connecting jQuery to Load Event
One of the most common ways to work with jQuery is by connecting to elements during the load (or onload) event of the page. In jQuery, you do this through the .ready() utility function of the document element.
You can access the document element like this:
$(document)
Then, you can then access the ready() function like this:
$(document).ready()
The $(document).ready() function removes the need for you to use the browser’s load event or to insert a function call into the load event. With $(document).ready(), all the elements of the Document Object Model (DOM) are available before the .ready() function executes.
Using Selectors
Selectors are key to working with jQuery and the DOM. You use selectors to identify and group the elements on which a jQuery function is executed. You use selectors to gather all the elements of a certain tag, of a certain ID, or with a certain class applied to them. You can also use selectors in much more powerful ways, such as to select a specified number of elements or to select only elements with a particular ancestry - for example, only those <p> tags that follow a <div> tag.
1. Selecting Elements by id
The general syntax for selecting an element by its ID attribute is:
$("#elementID");
For example, consider the HTML:
<a href="#" id="linkOne">Link</a>
With normal JavaScript, you access this element like:
getElementById("linkOne");
With jQuery, you access the element using this:
$("#linkOne");
2. Selecting Elements by Class
You select elements by class by prefixing a dot (.) to the class name. The syntax is this:
$(".className");
3. Selecting Elements by Type
You can also use selectors to access elements by type, such as all <div> elements, all <a> elements, and so on. For example,
$('div');
Using a type selector provides access to all the elements of the specified type on a page. Like the class selector, type selectors can return multiple elements.
4. Selecting Elements by Hierarchy
You can select elements by their position in relation to other elements on the page. For example, to select all the <a> elements that are within <div> elements, you use this syntax:
$("div a");
5. Selecting Elements by Position
The jQuery offers several ways to select more specific elements within a group. The following code selects the first <p> element within the page:
$("p:first");
Likewise, the last element is selected like this:
$("p:last");
You can also select elements by their direct position. For example, to select the second <p> element, you use this syntax:
$("p")[1];
The array index begins with 0 for this type of selector, so the first element is index 0, the second is index 1, and so on.
Another useful set of positional selectors are even and odd, which select every other element in a set. For example,
$("p:even");
The even and odd selectors are quite helpful when working with tabular data to alternate row colors. For example,
$(document).ready(function() {
$('tr:odd').css("background-color", "#abacab");
});
The code uses the $(document).ready() function along with the :odd selector to set the background color to hexadecimal #abacab, a light gray color.
6. Selecting Elements by Attribute
You can select elements that merely contain an attribute or those that contain an attribute with a specific value. For example, to select all images that have an alt attribute,
$("img[alt]");
To select only images that have an alt attribute set to a certain value:
$("img[alt='alternate text']");
This type of selector expects an exact match. The jQuery includes wildcard selectors that don’t require an exact match on attributes.
7. Selecting form elements
The jQuery contains native selectors related to web forms. For example, :input Selects all input elements on a page.
Functions
jQuery uses functions to perform actions on selected elements. Functions can be built in to jQuery or user-defined.
1. Traversing the DOM
The nature of programming on the web using JavaScript and jQuery frequently requires looping or iterating through several elements. For example, the .each() function takes a list of selected elements and iterates over each of them, doing something to each as it loops through the list. The jQuery contains numerous functions for looping and iterating. This process is known as traversing.
When using traversal functions, you almost always do so with the help of a user-defined wrapper function along with the $(this) selector. Like the this keyword in object-oriented programming, the $(this) selector refers to the current object - in this case, the item currently being traversed.
For example,
$('.percentage').each(function() {
if ($(this).text() >= .5) {
$(this).css('font-weight', 'bold');
}
});
This code uses a selector to gather all the elements that have the percentage class applied to them. Then, it accesses each of these elements using the .each() function in jQuery. Within the .each() function, a user-defined function performs a conditional to determine whether the value is greater than or equal to .5. If it is, the code calls the .css() function to add a font-weight property set to bold for that element.
2. Working with attributes
In addition to the class-related attribute functions, jQuery has functions to work with attributes of the DOM. The most generic of these is the .attr() function, although others, such as .html() and .val(), are useful as well.
You use the .attr() function to both retrieve and set attributes. For example,
// Get the alt attribute:
$("#myImageID").attr("alt")
// Set the alt attribute:
$("#myImageID").attr("alt", "new text")
3. Changing text and HTML
You can rewrite portions of HTML within a page or change text or values. The .html() function retrieves or changes the entire HTML within a selected element. For example,
<div id="myDiv">Here is a div</div>
The jQuery:
$("#myDiv").html('<span class="redStyle">This is the new content of the div</span>');
The <div> element identified by myDiv would now contain a <span> element with new text in it.
Like the .html() function, the .text() function supports both retrieval and setting of the text within a selected element. Unlike HTML, the .text() function gets or sets only text, so it’s not possible to alter the actual HTML of the selected element.
4. Inserting elements
You can easily use jQuery to add elements to a page. Two primary functions for doing this are the .after() and .before() functions. For example, a <div> element:
<div id="myDiv">Here is a div</div>
The jQuery that inserts another <div> element before it:
$("#myDiv").before("<div>This is a new div</div>");
5. Callback functions
Sometimes you need to run a function when another function completes, a construct called a callback function. A callback function is a function that is passed as an argument to another function that executes after its parent function completes. jQuery uses callback functions heavily, especially in AJAX.