Chapter 2 ■ jQuery Fundamentals
When you specify a function and its code, you are just defining the function and logic in it. It won’t be executed
until the document-ready event is triggered. If you use a function name in its place, that function is executed
immediately when the browser interprets the line, without waiting for the DOM to be ready.
•
$("selector")—Selects HTML elements that match the specified selector and returns a
jQuery object.
•
$(HTMLElement)—Returns a jQuery object with the specified HTMLElement in it.
•
$(HTMLElement[])—Returns a jQuery object with the HTML elements specified in the
HTMLElement[] array.
•
$("HTMLString")—Creates new HTML elements from the specified HTMLString.
Chapters 3, 4, 5, and 6 cover these function arguments in detail. Here I am simply providing very basic examples
to familiarize you with the concepts.
The jQuery Function with the Function as an Argument
Using the jQuery function ($) with the function as an argument is the most used feature in the jQuery. If the code
is accessing or manipulating DOM elements, then that code must be defined inside this function. The body of
the function will be executed only when all the DOM elements are created and are ready to be used. Listing 2-10
demonstrates the use of the jQuery function with the function as an argument.
Listing 2-10. jQuery function with the function as an argument
This jQuery code is binding function() {...} to the document ready event. After the DOM is ready, this
function will be executed. Such functions, which are bound to events, are also called event handlers. Figure 2-16 show
the pop-up message after the DOM is ready.
38
www.it-ebooks.info
Chapter 2 ■ jQuery Fundamentals
Figure 2-16. Message displayed after the DOM is ready
The jQuery Function with the Selector as an Argument
Using a jQuery function with the selector as an argument enables you to select DOM elements that match the
selector, so that selected elements’ values can be accessed and/or manipulated by using jQuery object’s methods.
Listing 2-11 demonstrates the use of the jQuery function with the selector as an argument.
Listing 2-11. jQuery function with the selector as an argument
Figure 2-17 displays the page when viewed in a browser.
39
www.it-ebooks.info
Chapter 2 ■ jQuery Fundamentals
Figure 2-17. Image with the default opacity of 1
This code has an image tag. Inside the DOM-ready function, this image is selected by the jQuery selector,
$("img"), and then a function is bound to its mouseover event. When the mouse moves over the image, the mouseover
event is triggered and this function is executed, which changes the opacity of the image to 0.3. Opacity can range from
0 to 1. The higher the number, the sharper the image will be. Another function is bound to the mouseout event, and it
changes the opacity to its default value of 1. Figure 2-18 displays the image with opacity of 0.3 when the mouse cursor
moves over the image.
Figure 2-18. Opacity changes to 0.3 when mouse cursor moves over the image
The jQuery Function with the HTMLElement as an Argument
Using a jQuery function with the HTML element as an argument enables you to put an HTML element into a jQuery
object so that the jQuery object’s methods can be executed on the HTML element, in order to access or manipulate its
value. Listing 2-12 demonstrates the use of the jQuery function with the HTMLElement as an argument.
Listing 2-12. jQuery function with the HTMLElement as an argument
40
www.it-ebooks.info
Chapter 2 ■ jQuery Fundamentals
Figure 2-19 displays the page when viewed in a browser.
Figure 2-19. Current system datetime set to an HTMLElement
In this code, a div tag is created with the currentDateTime ID. When the DOM is ready, the document-ready
function is executed, which gets the HTMLElement from the DOM using the statement $("#currentDatetime").first().
The same HTML element can be selected by using the native DOM method called document.getElementById
("currentDatetime"). In the $(currentDateTime) statement, the HTMLElement currentDateTime is passed to the
jQuery function ($) as an argument. The jQuery object is returned due to this statement. On this jQuery object,
the prop() method is executed to set its innerHTML property with the current system date and time.
The jQuery Function with the HTMLString as an Argument
Using a jQuery function with the HTML string as an argument enables you to convert an HTML string into a jQuery object
so that the jQuery object’s methods can be applied to the HTML elements in the jQuery object or it can be appended to an
existing element. Listing 2-13 demonstrates the use of the jQuery function with the HTMLString as an argument.
Listing 2-13. The jQuery function with the HTMLString as an argument
Departments:
- Sales
- Marketing
41
www.it-ebooks.info
Chapter 2 ■ jQuery Fundamentals
- Technology
- Customer Support
Figure 2-20 displays the page when viewed in a browser.
Figure 2-20. Adding a new department to the list at runtime
In this code when an HTMLString called "
Implementation" is passed to the jQuery function ($), an
HTMLElement is created. This new
element (newDepartment) can be appended to an existing list of departments by
executing the method append() on the, $("#listDepartments") jQuery object. listDepartments is the ID of the
tag. Due to the statement $("#listDepartments").append(newDepartment), a new department ("Implementation")
is added to the list of existing departments at runtime.
2-9. jQuery Methods Chaining
jQuery code is concise due to the availability of various shorthand notations, execution of the same method on
multiple elements within the same jQuery object with one method call, and because of the chaining concept. Most of
the jQuery methods you’ll execute on jQuery objects will return another jQuery object. That means that more jQuery
methods can be executed on the return value of the previous call in a single statement.
Listing 2-14 demonstrates the use of method chaining.
Listing 2-14. Method chaining
Departments:
- Sales
- Marketing
42
www.it-ebooks.info
Chapter 2 ■ jQuery Fundamentals
- Technology
- Customer Support
Figure 2-21 displays the page when viewed in a browser.
Figure 2-21. Method chaining
This code uses the ul selector to get a jQuery object containing the HTML element. Once you have the
jQuery object, you can execute methods such as css(), append(), and so on, on it. These methods will manipulate the
HTML element contained in the object. The css() method sets the CSS property and the append() method adds new
element(s) to the existing HTML element as its children.
In the statement:
$("ul").css("color", "blue").css("text-decoration", "underline").append("- Implementation
").
css("color", "green")
–– $("ul") gets the HTML element from the DOM.
––
css("color", "blue") changes the CSS color property of HTML element to blue.
––
css("text-decoration", "underline") changes the CSS text-decoration property of the
HTML element to underline.
––
append("- Implementation
") appends a new child (item) to the HTML element
.
––
css("color", "green") changes the CSS color property of the HTML element to green.
All of this is done in one single statement.
In the code example, I set the CSS color property twice to demonstrate that when chaining, method execution is
performed from left to right.
Summary
This chapter covered how to reference the jQuery library file, the typical folder structure of a web application, and
conditional and loop statements. It also covered the most important aspect of the jQuery library—the DOM. You
looked into the details of its structure and how to navigate through it. You also read about the difference between
attributes and properties. Other important fundamental topics covered in this chapter are commonly used objects
in jQuery and different forms for jQuery functions. The following chapters will develop real-life application
functionalities based on the fundamentals you learned in this chapter.
43
www.it-ebooks.info
Chapter 3
jQuery Selectors
This chapter covers jQuery selectors, which are used to get (or select) HTML elements based on their ID, tag name,
class name, types, attributes, attributes values, and other criteria. The set of selected elements can be fine-tuned
further by using selector extensions or jQuery methods and the set can be expanded by using certain jQuery methods.
Once you have a desired set of elements, you can access and manipulate their attributes values, properties, and style.
In this chapter and next two chapters, you will work on recipes that show you how you can use jQuery to select
HTML elements directly or indirectly (by traversing through the node tree) at runtime in order to:
•
Access their style, properties, and attributes
•
Manipulate their style, properties, and attributes
Some points to note before you start working on the recipes in this chapter:
•
For the document-ready event, the $(function() {...}) shorthand notation is used
throughout this book. It is same as $(document).ready(function() {...}). In this chapter,
I have used the jQuery css() method to highlight items that are selected by the jQuery selector.
You can perform any valid actions on the selected elements. Chapters 4, 5 and 6 covers
commonly used actions.
•
If you need to put nested quotes (" and ') in any code, you can use any of the following
methods:
"
'
"
"
value1
value1
value1
value1
=
=
=
=
'value2' "
"value2" '
\"value2\" "
\"value2\" "
•
All of these are valid forms; it is just a matter of preference.
•
While displaying a page in the web console window with jQuery code in it, you see an error
such as “ReferenceError: $ is not defined”, the jQuery library is not included or it is
referenced with the wrong path or URL.
Before you start looking into methods used for selectors and DOM traversing, refer to Appendix B for the list of
browsers I used for testing and for details about how to invoke the web console to identify script syntax errors and
runtime errors.
3-1. Examples
In order to illustrate various concepts of the jQuery library, this chapter uses the following simple applications:
human resources, a publishing house, and a photo album.
45
www.it-ebooks.info
Chapter 3 ■ jQuery Selectors
3-1-1. Human Resources Example
For the human resources application, department and employee entities and their attributes will be displayed and
managed in the example code. The following tables contain human resources-related entities, their attributes, and
sample data. Table 3-1 has the department’s attributes and Table 3-2 includes the sample data for departments.
Table 3-1. Department’s Attributes
Attributes
DepartmentCode
DepartmentName
Table 3-2. Department’s Sample Data
Department Code
Department Name
D001
Marketing
D002
Sales
D003
Technology
Table 3-3 contains the employee’s attributes and Table 3-4 contains sample data for the employees.
Table 3-3. Employee’s Attributes
Attributes
EmployeeID
EmployeeName
EmployeeTitle
EmployeeJoiningDate
EmployeeSalary
EmployeeDepartmentCode
ManagerEmployeeID
Table 3-4. Employee Sample Data
ID
Name
Title
Joining Date
Salary
Dept. Code
E001
Jane Smith
Marketing Manager
03/12/2008
$95,000
D001
E003
Brian Adam
Sales Rep.
04/14/2009
$72,000
D002
46
www.it-ebooks.info
Manager ID
E001
Chapter 3 ■ jQuery Selectors
3-1-2. Publishing House Example
For the publishing house application, the book entity and its attributes will be displayed and managed in the example
code. The following tables contain publishing house-related entities, the attributes, and the sample data. Table 3-5
contains the book’s attributes and Table 3-6 contains sample data for the books.
Table 3-5. Book’s Attributes
Attributes
BookID
BookCategory
BookTitle
Table 3-6. Book Sample Data
ID
Category
Title
B001
.NET
Windows Phone Recipes
B002
.NET
Visual C# 2010 Recipes
B003
.NET
UML Applied
B004
.NET
Sharepoint 2010 Designer Guide
This information is sufficient to use in this chapter’s examples. You’ll add more entities and attributes as you
progress through other chapters.
3-1-3. Photo Album Example
For the photo album application, album and photo entities and their attributes will be displayed and managed in
the example code. The following tables contain photo album-related entities, their attributes, and the sample data.
Table 3-7 contains the album attributes and Table 3-8 contains the sample data for the albums.
Table 3-7. Album Attributes
Attributes
AlbumID
AlbumName
Table 3-8. Album Sample Data
ID
Name
AL01
Animals
AL02
Birds
AL03
Sea Animals
AL04
Insects
47
www.it-ebooks.info
Chapter 3 ■ jQuery Selectors
Table 3-9 contains photo attributes and Table 3-10 contains the sample data for the photos.
Table 3-9. Photo Attributes
Attributes
PhotoID
AlbumID
PhotoFileName
PhotoImage
Table 3-10. Photo Sample Data
Photo ID Album ID Filename
Image
Photo ID Album ID Filename
P001
AL01
images/cat.png
P011
AL03
images/
butterfly1.jpg
P002
AL01
images/dog.png
P012
AL03
images/
butterfly2.jpg
Image
3-2. Selecting the HTML Element by its ID
Problem
You want to know how to select the HTML element by using its ID.
Solution
The following jQuery selector syntax selects the HTML element with the specified ID:
$("#id")
id is the value of the HTML element’s attribute “id” and the return value is a jQuery object.
For example, for , id is btnTestIt and its selector
is specified as "#btnTestIt". Listing 3-1 demonstrates the use of jQuery selector to select the HTML element by its ID.
48
www.it-ebooks.info
Chapter 3 ■ jQuery Selectors
Listing 3-1. jQuery selector to select element by id
- Windows Phone Recipes
- Visual C# 2010 Recipes
- UML Applied
- Sharepoint 2010 Designer Guide
- Pro WPF in C# 2010
- Zend Enterprise PHP Patterns
- Web Designer's Reference
- Practical Ajax Projects with Java
- The Definitive Guide to HTML5 WebSocket
- The Essential Guide to HTML5 and CSS3
How It Works
In the code, book titles are listed using and - HTML tags. If you want to select a single node and then perform
an action on it, use the “#id” selector.
After the DOM is ready (i.e., all HTML elements are created and loaded in the browser memory), the following
code is executed as a result of the document-ready event handler.
$("#btnTestIt").click(function () {
$("#WEB-02").css("background-color", "yellow");
});
49
www.it-ebooks.info