Jquery Free Lesson

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Introduction to jQuery

Instructor: Frank Stepanski

Overview

jQuery aims to change the way that web developers


think about creating rich functionality in their pages.
Rather than spending time juggling the complexities
of advanced JavaScript, designers can leverage their
existing knowledge of Cascading Style Sheets
(CSS), Extensible Hypertext Markup Language
(XHTML), and good old straightforward JavaScript
to manipulate page elements directly, making more
rapid development a reality.

Audience for this Class

This class is considered a beginner class and can be taken by either a web designer or
web developer with no previous experience with jQuery.

For a web designer, good knowledge of XHTML and CSS is required. It would be very
helpful if you have existing knowledge or experience of JavaScript. This class uses
programming syntax and terminology so pre-existing knowledge of JavaScript or a
programming language is required.

For a web developer, knowledge of programming language syntax and terminology is


already assumed so no other experience would be necessary.

Tools Needed

There is no specific tool to develop in jQuery so you can use any free text or web editor
like Notepad++ or HTML-Kit or Komodo Edit or commercial products like Adobe
Dreamweaver.

Introduction to jQuery 1 of 15 Author: Frank Stepanski


Why jQuery?

If you’ve spent any time at all trying to add dynamic functionality to your pages (as well
as figure out browser differences), you’ve found that you’re constantly following a
pattern of selecting an element or group of elements and operating upon those elements in
some fashion. You could be hiding or revealing the elements, adding a CSS class to them,
animating them, or modifying their attributes.

Using raw JavaScript can result in dozens of lines of code for each of these tasks. The
creators of jQuery specifically created the library to make common tasks trivial.

So the basic concept of jQuery could be described as:

1. Creating something new


2. Selecting it
3. Then doing something with it.

About jQuery

It’s one of the most popular JavaScript libraries around and was created by John Resig
during his college days at the Rochester Institute of Technology. Its popularity has been
helped by a number of high-profile sites using jQuery such as the BBC, Digg, Intel,
MSNBC, and Technorati.

Introduction to jQuery 2 of 15 Author: Frank Stepanski


The core features of jQuery are:

• Gives developers a common set of functions for all browsers.


• Uses selectors which is an expression for identifying target elements on a page that
allows us to easily identify and grab the elements we need
• Gives access to page elements without having to wait for all images to load in
place of using the browser’s onload event, which delays anything you do until the
page is fully loaded.
• Let’s you create and delete HTML.
• Has a great selection of animation and visual effect
• Contains enhancements to basic JavaScript constructs such as iteration and array
manipulation.

The real power in this jQuery statement comes from the selector, an expression for
Identifying target elements on a page that allows us to easily identify and grab the
elements we need; in this case, even every <tr> element in all tables.
The jQuery library provides a general-purpose abstraction layer for common web
scripting, and is therefore useful in almost every scripting situation. Its extensible nature
means that we could never cover all possible uses and functions in a single book, as
plugins are constantly being developed to add new abilities.

Downloading jQuery

jQuery is available in two versions: a packed version for use in production sites and an
uncompressed version that is more readable (if you want to review the source).

http://docs.jquery.com/Downloading_jQuery

No installation is required, to use jQuery you just need to place it in a public location.

Since JavaScript is an interpreted language, there is no compilation or build phase to


worry about. Whenever we need a page to have jQuery available, we will simply refer to
the file's location from the HTML document.

Just include the file in the same location as your HTML page and you’re ready to use
jQuery.

Introduction to jQuery 3 of 15 Author: Frank Stepanski


<script src=jquery-1.10.2.js" type="text/javascript"></script>

Google CDN

An alternative method for including the jQuery library that’s worth considering is via the
Google Content Delivery Network (CDN). A CDN is a network of computers that are
specifically designed to serve content to users in a fast and scalable manner. These
servers are often distributed geographically, with each request being served by the nearest
server in the network.

So, instead of hosting the jQuery files on your own web server as we did above, you have
the option of letting Google pick up part of your bandwidth bill. You benefit from the
speed and reliability of Google’s vast infrastructure, with the added bonus of the option
to always use the latest version of jQuery.
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Uncompressed or compressed?
If you had a poke around on the jQuery download page, you might have also spied a
couple of different download format options: compressed (also called minified), and
uncompressed (also called “development”).
Typically, you’ll want to use the minified version for your production code, where the
jQuery source code is compressed: spaces and line breaks have been removed and
variable names are shortened.

The result is exactly the same jQuery library, but contained in a JavaScript file that’s
much smaller than the original. This is great for reducing bandwidth costs for you, and
speeding up page requests for the end user.

The Document Object Model

One of the most powerful aspects of jQuery is its ability to make selecting elements in the
DOM easy. The Document Object Model is a family-tree structure of sorts. HTML, like

Introduction to jQuery 4 of 15 Author: Frank Stepanski


other markup languages, uses this model to describe the relationships of things on a page.
When we refer to these relationships, we use the same terminology that we use when
referring to family relationships—parents, children, and so on.

A simple example to understand how the family tree metaphor applies to a document:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>the title</title>
</head>
<body>
<div>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>This is yet another paragraph.</p>
</div>
</body>
</html>

Here, <html> is the ancestor of all the other elements; in other words, all the other
elements are descendants of <html>. The <head> and <body> elements are not only
descendants, but children of <html>, as well.

Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their
parent. The <p> elements are children (and descendants) of <div>, descendants of
<body> and <html>, and siblings of each other.

An important point to note before we begin is that the resulting set of elements from
selectors and methods is always wrapped in a jQuery object. These jQuery objects are
very easy to work with when we want to actually do something with the things that we
find on a page.

We can easily bind events to these objects and add slick effects to them, as well as chain
multiple modifications or effects together. Nevertheless, jQuery objects are different from
regular DOM elements or node lists, and as such do not necessarily provide the same
methods and properties for some tasks.

Introduction to jQuery 5 of 15 Author: Frank Stepanski


The $() factory function

The fundamental operation in jQuery is selecting a part of the document. This is done
with the $() construct. Typically, it takes a string as a parameter, which can contain any
CSS selector expression.

Making Sure the Page is Ready: $(document).ready(function)

While JavaScript provides the load event for executing code when a page is rendered,
this event does not get triggered until all assets (images, script, frames and other
embedded objects) have been completely loaded.
$(document).ready(function() {
alert(‘ready event was triggered’);
});

With this code in place, an alert will be displayed when the page is loaded.

Note: If your script requires images to be loaded first before executing then you can use
the load() method instead:
$(document).load(function() {
alert(‘all assets have been loaded’);
});

The shortcut version would be:


$(function() {
alert(‘all assets have been loaded’);
});

CSS Selectors

You will often need to select page elements in online work. The selection capabilities of
browsers are minimal and mostly involve the JavaScript getElementByID function,
which requires you to add an ID value to any element you want to select (making
selection of multiple items difficult or at least time consuming).

Introduction to jQuery 6 of 15 Author: Frank Stepanski


CSS offers a much stronger set of tools for selecting page elements to set styles, and
Query adopts many of the CSS selectors. Using the jQuery selectors lets you select page
elements so you can work on them in JavaScript, not just with CSS styles.

Figure 1 – Basic and Hierarchal Selectors in jQuery

Documentation: http://api.jquery.com/category/selectors/

Let’s go through some examples so you get a feel for how to use these basic selectors.

<body>
<ul id="list1">
<li class="a">item 1</li>
<li class="a">item 2</li>
<li class="b">item 3</li>
<li class="b">item 4</li>
</ul>
<p class="a">This is paragraph 1</p>
<p id="para1">This is paragraph 2</p>
<p class="b">This is paragraph 3</p>
<p>This is paragraph 4</p>
</body>

Introduction to jQuery 7 of 15 Author: Frank Stepanski


Basic Selectors:

Note: Comment out (//) all but one statement at a time.

<script type="text/javascript">
$("document").ready(function() {
//$("p").css("border", "3px solid red");
//$(".a").css("border", "3px solid red");
//$("#list1").css("border", "3px solid red");
//$("p.b").css("border", "3px solid red");
});
</script>

1. $("p") – Selects all paragraphs.


2. $(".a") – Selects everything that has a class of “a”.
3. $("#list1") – Selects the element that has an ID of “list1”.
4. $("p.b") – Selects all paragraphs that have a class of “b”.

Filters

Filters work with selectors to provide even more fine-grained control over how elements
are selected in the document. jQuery filters fall into six main categories: Basic, Content,
Visibility, Attribute, Child and Form.

Note: Some documentation doesn’t differentiate between selectors and filters. They just
“mush” them all together.

Introduction to jQuery 8 of 15 Author: Frank Stepanski


Figure 2 – Basic Filters in jQuery

Basic Filters:

<script type="text/javascript">
$("document").ready(function() {
//$("p:first").css("border", "3px solid red");
//$("p:last").css("border", "3px solid red");
//$("p:even").css("border", "3px solid red");
//$("p:odd").css("border", "3px solid red");
//$(".a:first").css("border", "3px solid red");
//$(".b:even").css("border", "3px solid red");

});
</script>

5. $("p:first”) – Selects the first paragraph.


6. $("p:last”) – Selects the last paragraph.
7. $("p:even”) – Selects all even paragraphs (starts at 0, so the first is ‘even’).
8. $(".a:first”) – Selects the first element that has an “a” class applied to it.
9. $(".b:even”) – Selects all even number elements that have a class of “b”.
10. $("p:odd”) – Selects all odd paragraphs.

Introduction to jQuery 9 of 15 Author: Frank Stepanski


Attribute Filters

Attribute filters provide the ability to further filter out the results a selector statement
based upon attributes that are on the elements being selected.

Figure 3 – Attribute Filters in jQuery

Attribute Filters:
<script type="text/javascript">
$("document").ready(function() {
//$("p[class]").css("border", "3px solid red");
//$("p[id=para1]").css("border", "3px solid red");
//$("p[id^=para]").css("border", "3px solid red");
});
</script>

11. $("p[class]”) – Selects all the paragraphs that have a class.


12. $("p[id=para1]”) – Selects all paragraphs that have an id equal to “para1”.
13. $("p: [id^=para1]”) – Selects all paragraphs with an id that starts with “para”.

Introduction to jQuery 10 of 15 Author: Frank Stepanski


Try for Practice

For as quick practice exercise, use a few of selectors and filters on this online example:

http://www.w3schools.com/jquery/trysel.asp?filename=trysel_basic

Content and Visibility Filters

Examine the content of the elements that are returned by the selector expression or their
visibility property to determine if they should be included or excluded from the result set.

Child Filters

Child filters allow you to refine the selection by looking at the relationship that the
element has with its parent element.

http://api.jquery.com/category/selectors/content-filter-selector/

Introduction to jQuery 11 of 15 Author: Frank Stepanski


Figure 4 – Content and Visibility Filers and Child Filters in jQuery

http://api.jquery.com/category/selectors/child-filter-selectors/

Let’s take a look at some examples.


<body>
<ul id="list1">
<li class="a">item 1</li>
<li class="a">item 2</li>
<li class="b">item 3</li>
<li class="b">item 4</li>
</ul>
<p class="a">This is paragraph 1</p>
<p id="para1">This is paragraph 2</p>
<p class="b">This is paragraph 3</p>
<p>This is paragraph 4</p>
</body>

<script type="text/javascript">
$("document").ready(function() {
//$("p:contains(3)").css("border", "3px solid red");
//$("li[class=a]").css("border", "3px solid red");
});
</script>

1. $("p:contains(3)") – Select the paragraphs that contain the text “3”.


2. $("li[class=a]") – Selects the list items that have a class attribute that is equal to “a”.

Introduction to jQuery 12 of 15 Author: Frank Stepanski


Form Selectors

They are used to select form elements only so they work just like regular selectors other
than that they start with a colon (:) like a regular filter.

Figure 5 – Form Selectors in jQuery

http://api.jquery.com/category/selectors/form-selectors/

Figure 6 – Form Filters in jQuery

Introduction to jQuery 13 of 15 Author: Frank Stepanski


<script type="text/javascript">
$("document").ready(function() {

//$("form :input").css("border", "3px solid red");


//$("form :text").css("border", "3px solid red");
//$("form :text:enabled").css("border", "3px solid red");
//$("form input:checkbox:checked").wrap('
<span></span>').parent().css({border:"3px red solid"});

});
</script>

1. $("form :input") – Selects all input elements.


2. $("form :text") – Selects all text elements
3. $("form :text:enabled") – Selects all text elements that are enabled.
4. $("form :checkbox:checked") – Selects all checkboxes that are checked. You need to
add a little extra to add CSS to checkbox items.

Traversing Document Information

jQuery makes you traverse through your document pretty easy compared to the lines and
lines of JavaScript code you would have to write to do the equivalent.

Figure 7 – Some utility Functions in jQuery for Traversing the Document

http://api.jquery.com/category/miscellaneous/dom-element-methods/
http://api.jquery.com/category/traversing/

Introduction to jQuery 14 of 15 Author: Frank Stepanski


<script type="text/javascript">
$("document").ready(function() {

var elems = $("li").get();

// use the find function


$("ul").find("li.b").css("border", "3px solid red");

// use the each function


var leftmargin = 0;
var border = 3;
$("p").each(function() {
$(this).css("border", border+"px solid red");
$(this).css("margin-left", leftmargin);
border += 2;
leftmargin += 10;
});
});
</script>

1. $("p").length – Returns the number of paragraphs (size() and length do same thing)
2. $("li").get() – Returns an array of all list items as DOM elements.
3. $("li").get(0) – Returns the object type that is stored in the first element of the array.
4. $("ul").find("li.b") - Selects list items with a class of “b” inside a unordered list.
5. $("p").each(function() { } – For each paragraph found, a function will execute. This
function will apply specific CSS styles to the elements. $(this) refers to each
paragraph that was found.

jQuery Statement Chaining

One of jQuery’s most powerful features is its ability to chain multiple functions together
to perform several operations at once in one line of code.

$(selector).fn1().fn2().fn3();

These functions will get executed in order (left to right) to whatever result set was
returned from the selector statement.

Copyright 2014 © Frank Stepanski

Lessons, files and content of these classes cannot be reproduced and/or published
without the express written consent of the author.

Introduction to jQuery 15 of 15 Author: Frank Stepanski

You might also like