jQuery Introduction
References
What is jQuery?
jQuery is a collection (library) of JavaScript functions.
These functions allow you to do more with less code.
The jQuery library contains the following features:
- HTML element selection
- HTML element manipulation
- CSS manipulation
- HTML event-handling functions
- Special effects and animations
- HTML Document Object traversal and modification
- AJAX
- Utilities
Adding the jQuery Library to your HTML Page
The jQuery library is stored in a single JavaScript source/include file which contains all of the jQuery functions. You must include the jQuery library file into your HTML page before you can use the jQuery functions.
You include the jQuery library file in your HTML page with a standard JavaScript source/include <script> tag in the <head> section, like this:
<head>
.
.
<script src="jquery.js"></script>
.
.
</head>
(You can, instead, include the jQuery library's source/include file from one of several Web servers which have been set up for this purpose. See the last paragraph in this section about "hosted jQuery libraries".)
If you decide to use a local copy of the jQuery library as the source/include file, you will need to download the source/include file and save it to a local directory, for your local testing.
Then when you are ready to upload your HTML page to your Web server, you will also need to upload the jQuery library's source/include file to your Web server.
When you download the jQuery library source/include file to your local directory, you can save it as its original, version-specific filename, or you can rename the file to jquery.js. I recommend that you rename it to jquery.js so you don't have to be constantly changing your HTML pages when an upgraded file becomes available.
You can download and save one of two versions of the jQuery library. One version is minimized (minified) and uncompacted; the other version is compacted. I recommend that you download the uncompacted minified version of the library file, since it does not require uncompacting before the browser uses it. The minified version of the jQuery source/include file has all of the whitespace characters removed from it.
You can download either version of the jQuery library file here:
http://docs.jquery.com/Downloading_jQuery#Download_jQuery
If you don't want to store the jQuery library on your own computer and/or Web server, you can use a hosted jQuery library from several sources. These hosted jQuery libraries are listed on the same page as the download links, given above. Look for the "CDN Hosted jQuery" section of that page. There are two sub-sections: One for the libraries hosted by the jQuery docs folks, and one for other hosted CDNs. (CDN stands for "Content Delivery Network".)
jQuery Includes
If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, you can put your jQuery functions in a separate .js file.
Most of my sample code will show the functions in the <head> section, but in the real world it is often preferable to place them in a separate file.
If, for instance, you have placed your jQuery functions in a file called my_jquery_functions.js, you would include them in your HTML page with code like this:
<head>
<script src="jquery.js"></script>
<script src="my_jquery_functions.js"></script>
</head>
jQuery Syntax
jQuery was designed to make it easy for you to:
- select (query) an HTML element, and
- perform an action on it.
In keeping with this design goal, the basic syntax of jQuery is:
$(selector).action()
Please note these important points about the above syntax:
- The dollar sign ($) identifies the statement as being a jQuery statement.
- The selector "queries" the page for an HTML element/tag that matches its selection criteria. When the selector finds such an element/tag, jQuery can then do the action given in the next part of the statement.
- The action does something to, or with, the selected element/tag.
Here are some examples of jQuery statements, each one of which uses the jQuery syntax given above:
- $(this).hide() - hides the element that this code is in, with the code most likely being in an event handler
- $("p").hide() - hides all of the paragraphs in the page
- $("p.test").hide() - hides all of the paragraphs which have a class="test" attribute
- $("#test").hide() - hides the element which has an id="test" attribute
- $("#test").html() - allows you to change the html content (the innerHTML property) of the element which has an id="test" attribute
The Document Ready Function
It would not be good for you to use any of jQuery's functions before the HTML page has finished loading into the browser. In order to make sure that the page has finished loading into the browser, jQuery provides a main function that you should use to contain all of the other jQuery functions that you use.
This main container function is $(document).ready(). The other jQuery function calls which it contains, can run only after the HTML page (document) has been loaded and is ready for jQuery commands.
The $(document).ready() function is used like this:
$(document).ready(function()
{
// jQuery code goes here...
});
(And please note that the ready() function call has what looks like another function() call as its parameter. This mysterious-looking parameter is in fact a standard JavaScript anonymous function. See the section below this section, regarding the anonymous function.)
We will see specific examples of using the $(document).ready() function and the anonymous function shortly....
The Anonymous Function
Most jQuery code uses an odd-looking function parameter, without a name, to accomplish its actions.
This odd-looking function parameter is actually a standard JavaScript anonymous function.
An anonymous function is a function that is not given a name when it is defined. You can't call an anonymous function later in the page, and you must use it at the time that it is defined.
In somewhat plainer language, the above paragraph means that the anonymous function is created and used at the same time.
You can (either now or when you get to the "jQuery Example" sections) look at jQuery Sample 1 and jQuery Sample 2 to see how anonymous functions are used in jQuery code.
But first, we need to take a closer look at how jQuery Selectors work...
jQuery Selectors
jQuery selectors allow you to select HTML elements (or groups of elements) by element name, by attribute name, or by content. They select ("query") the HTML elements/tags that you want to apply an effect/action to.
There are three kinds of jQuery selectors:
- Basic jQuery Selectors
- jQuery Attribute Selectors
- jQuery Content Selectors
There is an excellent jQuery Selector reference page at w3schools.com.
The pages which most helped me to make sense of the various types
of jQuery selectors are at
http://api.jquery.com/category/selectors/,
especially the sections under "Selectors" which are "Basic", "Attribute", and "Content Filter".
The sections below provide more details about the Basic, Attribute, and Content jQuery selectors...
Basic Selectors
The Basic Selectors are based on the Cascading Style Sheet specifications, as outlined at the World Wide Web Consortium (W3C) CSS Site. Here are some examples:
- All Selector: $("*") selects all of the elements in the page.
- Class Selector sample: $(".intro") selects all of the elements which have a class="intro" attribute.
- Element Selector sample: $("p") selects all of the <p> elements in the page.
- ID Selector sample: $("#demo") selects the (first) element which has an id="demo" attribute. (Please note that only one element in the page should have any particular id attribute anyway!)
- $(this) Selector: $(this) selects the current HTML element.
- Multiple Selector sample: $("div,span,p.myClass") selects all of the <div> elements, <span> elements, and <p class="myClass"> elements in the page, and applies whatever action is specified to all of these elements.
Attribute Selectors
You use Attribute Selectors to select HTML elements (tags) with given attributes. Attribute values in selector expressions must be surrounded by quotation marks. (jQuery's Attribute Selectors use what are known as XPath expressions.)
Also note that the syntax of attribute selectors (and XPath expressions) includes square brackets around the attribute information in the jQuery selector.
Also note that the syntax of attribute selectors includes an additional set of quotes if the selector itself has quotes in it.
Here are some examples of attribute selectors:
- $("[href]") selects all elements which have an href attribute.
- $('[href="#"]') selects all elements which have an href attribute with a value equal to "#".
- $('[href!="#"]') selects all elements which have an href attribute with a value that is NOT equal to "#". (Notice the "!" (exclamation point), which is the JavaScript operator for "NOT".)
- $('[href$=".jpg"]') selects all elements which have an href attribute with a value that ends with ".jpg".
- $('[href^="news"]') selects all elements which have an href attribute with a value that begins with "news".
-
$('input[name*="man"]') selects all of the <input...> elements
that contain a name attribute containing "man". This selector would,
for instance, select these
tags:
<input name="milkman" />
<input name="Superman" />
<input name="manual" />
Content Filters
jQuery Content filters can be used to select elements based on the element's contents.
Here are some examples:
- $("div:contains('John')") selects all of the <div> elements containing the text "John". Please note that this filter is case-sensitive.
- $("td:empty") selects all of the <td> elements that are empty. An empty element has no text or child elements.
- $("div:has(p)") selects all of the <div> elements which have a <p> element in them.
- $("td:parent") selects all of the <td> elements which have children, including text.
jQuery Example 1
This first jQuery example is file jQuerySample1.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>jQuery Sample 1</title>
<script src="jquery.js"></script>
<script>
/* <![CDATA[ */
$(document).ready(function()
{
$("#buttonOneA").click(function(){
$("#firstP").hide();
});
$("#buttonOneB").click(function(){
$("#firstP").show();
});
$("#buttonTwoA").click(function(){
$("#secondP").hide();
});
$("#buttonTwoB").click(function(){
$("#secondP").show();
});
});
/* ]]> */
</script>
<style type="text/css">
body { font-family: Arial,sans-serif; background-color: #ffd; }
#mainDiv { width: 800px; margin: 0 auto; position: relative; }
#firstP { background-color: #dff; width: 400px; position: absolute; left: 20px; top: 150px; padding: 1em; }
#secondP { background-color: #fdf; width: 400px; position: absolute; left: 500px; top: 150px; padding: 1em; }
</style>
</head>
<body>
<div id="mainDiv">
<h3>jQuery Sample 1</h3>
<div id="buttons">
<button id="buttonOneA">Hide Paragraph One</button>
<button id="buttonOneB">Show Paragraph One</button>
<button id="buttonTwoA">Hide Paragraph Two</button>
<button id="buttonTwoB">Show Paragraph Two</button>
</div>
<p id="firstP">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae ligula urna. Mauris fringilla
felis eu leo gravida ullamcorper. Integer lacinia commodo accumsan. Ut velit mi, luctus condimentum
tincidunt quis, suscipit non lectus. Nunc enim sapien, facilisis sed sodales dignissim, ullamcorper
quis nisl. Suspendisse sit amet justo ut sapien pellentesque.
</p>
<p id="secondP">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae ligula urna. Mauris fringilla
felis eu leo gravida ullamcorper. Integer lacinia commodo accumsan. Ut velit mi, luctus condimentum
tincidunt quis, suscipit non lectus. Nunc enim sapien, facilisis sed sodales dignissim, ullamcorper
quis nisl. Suspendisse sit amet justo ut sapien pellentesque.
</p>
</div>
</body>
</html>
Please note these points about the above code:
-
The line of code
$(document).ready(function()
makes sure that the page has been loaded by the browser before any of the jQuery code in the ready function is used.
-
The ready function itself, and all four contained selector functions, are
anonymous functions.
-
All four of the jQuery selectors are ID Selectors.
-
We will talk more specifically next week about jQuery API functions. For now,
please note that the hide() function makes a selected tag invisible, and the
show() function makes the selected tag visible again.
- We will also talk more specifically next week about jQuery event functions. For now, please note that the click() function responds to mouse clicks on the selected tag.
jQuery Example 2
This second jQuery example is file jQuerySample2.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="Samples.css">
<title>jQuery Example 2</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function()
{
$("p").mouseover(function(){$(this).css({'color': 'red', 'background-color': 'white'});});
$("p").mouseout(reduceText);
});
function reduceText()
{
var cssObj = {'color': 'black', 'background-color': '#ffaaaa'};
$(this).css(cssObj);
}
/* ]]> */
</script>
<style type="text/css">
body
{
font-family: Arial,sans-serif;
background-color: #ffaaaa;
}
</style>
</head>
<body>
<div id="mainDiv">
<h3>Second jQuery Example</h3>
<p id="firstP">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae ligula urna. Mauris fringilla felis eu leo gravida ullamcorper. Integer lacinia commodo accumsan. Ut velit mi, luctus condimentum tincidunt quis, suscipit non lectus. Nunc enim sapien, facilisis sed sodales dignissim, ullamcorper quis nisl. Suspendisse sit amet justo ut sapien pellentesque.
</p>
<p id="secondP">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae ligula urna. Mauris fringilla felis eu leo gravida ullamcorper. Integer lacinia commodo accumsan. Ut velit mi, luctus condimentum tincidunt quis, suscipit non lectus. Nunc enim sapien, facilisis sed sodales dignissim, ullamcorper quis nisl. Suspendisse sit amet justo ut sapien pellentesque.
</p>
</div>
</body>
</html>
Please note these points about the above code:
- The mouseover action for the paragraphs, uses an anonymous function, which we discussed above.
- The css function in the mouseover action sets two CSS properties, using the standard JavaScript object notation, which is a series of key-value pairs in curly braces.
- The mouseout action for the paragraphs, calls a standard JavaScript function, reduceText(). Note that only the name of the function, without the parentheses, is given as the argument in the mouseout() function.
- The variable cssObj uses standard JavaScript object notation, which is a series of key-value pairs in curly braces. This variable is used to set multiple CSS properties in the next statement's css() function.