Further Reading
A very basic Ajax tutorial with ready-to-run examples is available at www.w3schools.
com/ajax/default.asp
. In Robin Nixon’s book Learning PHP, MySQL, JavaScript, and
CSS
you’ll find more explana tions about how Ajax works together with tips on using
XML instead of plain text for conveniently structuring data that you pass back to your
Ajax applications. If you’re inter ested in using the jQuery library (briefly introduced
in the next section) for programming your Ajax applications, you will proba bly want
to get David Sawyer McFarland’s book
JavaScript and jQuery. If you are up for more
technically prof ound explanation of the topic, you might want to loo k into
JavaScript:
The Definitive Guide
, a boo k by David Flanagan.
B.4 jQ uery
Currently by far the m ost popular and widely used JavaScript library is jQuery. There
are many reasons why you would decide to use jQuery in your own projec ts, and they
can all be brought under the same umbre lla with the motto “w rite less, do mo re. If
nothing e lse, programmers like to use the jQuery library because it simp lifies mun-
dane everyday tasks and hides the dierences between browsers, whic h have made
progr ammers reach f or bottles of aspirin from time immemorial. Also important is the
fact that jQuery is stable and well documented.
Getting jQuery
Technically, jQuery is simply a file containin g an a ssemblage of JavaScript co de,
which you include as you would any other external JavaScript file. T hat is, you use the
src attribute of a <script> HTML element. However, you still have two possibilities
regarding the library location: either yo u can download the jQuery file to your own
compute r or you c an simply link to one of the versions hosted on the web. Needless to
say, each of these two approaches has its advantages and downsides but I leave them
for y ou to discover on your own. For the sake of this section, we’re going to use the
jQuery library version hosted on the
jquery.com CDN (Content Distribution Network)
server:
<script src = "http://code.jquery.com/jquery-1.11.2.min.js">
</script>
The jQuery() Function
There’s one sin gle global function named jQuery() defined in the jQuery library.
Because this is the c entral query function for jQuer y, it is intensely used and the library
also defines the g lobal symbol $ as a shortcut alias for it. The jQuery() function
returns a jQuery o bject, which contains zero or more DOM elements and a bunch of
convenienc e methods for working with those DOM elements. Note that jQuery() is
not a con structor but a factory func tion and does therefo re n ot need the new operator
to create a jQuery object. Most jQuery methods return the same jQuery object that
they operate on. This allows for so-called method cha ining, which is q uite frequen t
in jQuery programming. Meth od chaining is a compact form of calling methods one
286 Appendix B. Ways to Continue
after the other in a single “c hain. For example, if you want to add a class of hidden
to all < p> elements tha t have a class of details, hiding them at the same time by
sliding the m up, you can use the following chain of methods:
$("p.details").addClass("hidden").slideUp();
In this example you see how the $( ) function finds and selects elements simply b y
using CSS selector syntax. Passing a CSS selector as an argument is the most common
way of invoking the jQuery() function, but it’s not the only one. You can also pass an
Element, Document, or Window object, and the $() function simply wraps a jQuery
object around whatever object it is passed, allowing you to use jQuery methods to
manipulate the element. For example, you can change the background color of an
element inside an event handler attached to it simply by passing this to the $()
function a nd use the jQuery css() method:
$(this).css("background-color", "blue");
The third way to invoke $() is to call it with a string of plain HTML code as an argu-
ment. Note that doing this does not select elements, but instead c reates n ew elements.
For example, you can create a n <h3> heading like this:
var h3 = $("<h3>Latest Additions</h3>");
The created element is not automatically added to the document, of course. You can,
for example, use the appendTo() method to append the newly created element as the
last child of an existing element:
h3.appendTo("#about");
The above created <h3> heading thus becomes the last ch ild of the element with the
id of about.
The last way to invoke $( ) is with a function as an argument. When you do that, the
passed fu nction will be called after the document has completed loading. This is in
fact the same thing as using the onload property of the Window object to make sure
that JavaScript starts executing only afte r the document is fully loaded and the DOM
is ready to be manipulated. Knowing that, it comes as no surprise that most jQuery
progr ams are written as an anonymous function passed as an argument to $():
$(function() {
//JavaScript and jQuery code
});
Instead of the above form, you’ll sometimes come across the older and more involved,
but equivalent code:
B.4. jQu ery 287
$(document).ready(function() {
//JavaScript and jQuery code
});
Iterating Selected Elements
You have just learned about dierent ways to select HTML elements using the global
jQuery() (a.k.a . $() ) function. It is important to understand that $() a lways returns
a jQuery object containing zero or more elements. Because jQuery objects are array-
like (they have the leng th p roperty as well as numeric properties from zero to len gth
- 1) it is possible to iterate selected elements using the for loop, but in practice yo u’ll
seldom n eed to do this. For one thing, y ou can use the each() method to loop over
the elements in a jQuery object, but even this is not very commonly used. Most of the
time you’ll use jQuery me thods, whic h automatically iter ate all the elements with in
the jQuery object on which they are invoked. For example, you can change fon t color
of all the <h1> elements o n the page like this:
$("h1").css("color", "darkblue");
Or, you can underline text within any elem ent having a class of important :
$(".important").css("text-decoration", "underline");
Getting and Setting Values
The most fre quent operations on jQuery ob je cts a re those that manipulate dierent
values connected with elements stored in jQuery o bjects, like getting or settin g values
of HTML attributes or CSS styles. Ther e are some general truths about jQuery getter
and setter methods worth noting:
jQuery uses a single method for both getting and setting a value. If you invoke
the method with a new value as an argument, then that value is set. If, however,
you do not provide a value, the method returns the current value, if any.
If a jQuery object contains more than a single element, then a value is set on all
the elements in the jQuery object.
If, however, you want to g et a value, then only the first element in the jQuery
object will be queried for the value.
You ca n set more values with a single call to a method if you pass as an argument
an object whose properties specify names and values to be set.
The examples that follow are intended to give you the basic feel of how the jQuery
getters and setters work.
The next lines of code show how to get and set HTML attributes using the attr()
method. You can also co mpletely remove an attribute f rom the selected elements using
removeAttr():
288 Appendix B. Ways to Continue
var src = $("img").attr("src"); //Gets the value of the src
//attribute of the first image on
//the page.
$("a").attr("target", "_blank");//Sets the target attribute of all
//the <a> elements to _blank. All
//the hyperlinks on the page will
//now load in a new window.
$("a").removeAttr("target"); //Removes the target attribute from
//all the <a> elements on the page.
//All the hyperlinks will load in
//the current window again.
The following are examp le s of getting and setting CSS properties and the class
HTML attribute. The css() method is used to get and set individual CSS properties,
while addClass(), removeClass(), and hasClass() are meant for manipulating
the class HTML attribute:
//Queries the background color of the first <div>:
var color = $("div").css("background-color");
//You can use camelCase:
var color = $("div").css("backgroundColor");
//Sets the font color of all the <div> elements.
$("div").css("color", "yellow");
$("div").css({ //Sets multiple properties at once. The
width: 50, //argument of css() is a JavaScript object
height: 50, //literal.
borderRadius: 5
});
//Adds a class to the element with id of notes:
$("#notes").addClass("highlight");
//Removes a class from all the <p> elements.
$("p").removeClass("highlight");
//Does the element with id of notes have a class of empty?
var empty = $("#notes").hasClass("empty");
Another set of methods allow you to manipulate HTML form values and elements’
content, either in p la in text or HTML markup :
var addr = $("#address").val(); //Gets a value from the text box
//with id of address.
$("#getAmount").val(usd * rate); //Sets a value of a text box.
var title = $("title").text(); //Gets the title of the document.
B.4. jQu ery 289
$("title").text("Working Title"); //Sets the title of the document.
var div = $("div").html(); //Gets the HTML contained in the
//first <div> in the document.
//Sets the HTML content of all of the <div> elements in the
//document:
$("div").html("<h1>Z-Files</h1>");
Custom Element Data
jQuery has a powerful capability to associate arbitrary data with document e le ments
or with Document or Window objects. T he data() method allows you to a ttach data
to the elements contained in a jQuery object. You can either pass a name and value as
two arguments of the method or you can pass a single object, whose properties will be
associated with the elements of the jQuery ob je ct.
You can also use data() to get values, of course. If you pass a single argument to it,
that argument is interpreted as a name wh ose value is to be returned. When, however,
you c all the method without any argument, an object is returned that contains all th e
name/value pa irs attached to the first element inside the jQuery object.
If yo u want to c ompletely remove all or some of the data associated with an ele ment
or elem ents, then use the removeData() method.
These are some examples:
$("#sprite").data("counter", 10); //Sets counter on sprite to zero
console.log($("#sprite").data("counter")); //Writes 10
$("#sprite").data({x: 13, y: -8}); //Sets x and y on sprite
console.log($("#sprite").data()); //Writes {counter: 10, x: 13,
// y: -8}
$("#sprite").removeData("counter"); //Completely removes counter
console.log($("#sprite").data()); //Writes {x: 13, y: -8}
$("#sprite").removeData(); //Removes all previously set data
Note that you can also use the da ta() method to return values set by an HTML5
data-* custom data attribute, where the same name transformations apply as with the
JavaScript dataset property described on page 398. It is, however, not possible to
add new custom data attributes to HTML elements using this method.
Manipulating Document Structure
You can use html() and text() to alter the document structure. However, an HTML
document is not represented as a linear sequence of elements, but rather as a tree of
nodes. In sertions, deletions, and replacements of elements are therefore not trivial
operations, and the jQuery library defines quite a number of han dy methods to carry
290 Appendix B. Ways to Continue
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.108.168