them o ut. The most essential are the a ppend() and r emove() methods, whic h are
described in this section.
As its name suggests, the append() method appends a n element at the end of an ex-
isting one, so that the appen ded element becomes the last of its c hildren. The method
accepts as an a rgument the content that is to be appen ded. You can specify a string of
plain text or HTML markup, but yo u can also pass a jQuery or Element object. Note
that, if you attempt to append an ele ment that already exists in the document, that
element is removed from its current position to be inserted to a new one. If append()
is invoked on a jQuery object that contains more than one element, then the element
to be appended is c loned as necessary a nd appended to all the elements within that
jQuery ob je ct.
For instan ce, to append a <p> element to all the <div> elements in the document, you
invoke append() in the following manner:
$("div").append("<p class=’answer’>42</p>");
Note that append() returns the jQuery object on which it is invoked. Sometimes,
however, it is more convenient to get the jQuery object that contains the newly adde d
content instead . In this case you can use the appendTo() method like this:
$("<p class=’answer’>42</p>").appendTo("div");
Although both of the ab ove lines have exactly the same eect on the document, the re
are two important dierenc es between them. We have already mentioned that they
return quite dierent jQuery objects. The second diere nce is connected with the
behavior of the $() function. If y ou tried to append pla in text using appendTo(),
then tha t text would be interpreted as a selector that identifies the target element and
not as a string of text to be appended. It is therefore not possible to append plain text
using th e appendTo() method.
When you want to remove one or more elements from a documen t, you can use the
remove() method. T his meth od simply removes all the elements contained in th e
jQuery object on which it is invoked. For example, to remove all the <h3> elements
from the document, you write:
$("h3").remove();
jQuery Events
To register a n event handler in jQuery, you simply call one of its event-handler regis-
tration methods, passing to it a reference to the event-handler function definition. For
example, you can register an event handle r for click events like this:
$("img").click(myClickHandler);
B.4. jQu ery 291
Note that the above call to click( ) registers the myClickHandler() function on all
of the <img> elements found in the document.
Here are some of the event ha ndler registration methods defined by jQuery:
click() dblclick() keydown()
keypress() keyup() load()
mouseover()
These are common event types and you can find their descriptions in the JavaScript
referenc e on page 402.
jQuery also defines its own Event object, which is always passed as an argument to a
jQuery event handler. You can find additional information about the event that you are
handling by querying the Event object’s prope rties. These are some of the properties
of the jQuery Event o bject:
altKey button clientX
clientY ctrlKey shiftKey
which
You can find descriptions of these properties in the JavaScript reference on page 402.
Note that which is no longer supp orted by Web stan dards but it is emulated by the
jQuery library to carry additional information about keyboard and mouse events. It
seems that in JavaScript, at the time of writing th is book, there is no standardized
property to work with keyboa rd events. The properties charCode and keyCode are
deprecated, while the key property, which replaces them, is not yet adequately sup-
ported by browsers.
Let’s put it all together in a simple example that waits for mouseover and keydown
events, and writes the value of the which property to the JavaScript Console window
each time an event occurs.
var writeWhich = function(event) {
console.log(event.which);
};
$(function () {
$("p").mouseover(writeWhich); //Listens to mouseover events over
//each <p> element
$(document).keydown(writeWhich); //Listens to keydown events
});
There are some remarks we should make about the above exam ple. First of all, in
order for the mouseover event to be triggered on a particular paragraph, that paragraph
should have a nonzero size. This means you have to put at least on e printable character
inside your sample paragraph if you want to test the example. Next, keyboard events
can only be trig gered o n elements that have focus. Few elemen ts other than for m
elements can re ceive focus, so keyboard events are often attach ed to the document if
they are not to be handled by forms. In the above example, the keydown event is used,
292 Appendix B. Ways to Continue
because this event is also trig gered by pressing non-character keys such as arrow or
function keys. On the other hand, if you use the keypress event and want to detect
whether any of the modifier keys (Shi ft, Ctr l, or Alt) is also pressed, then you
must also query the corresponding shiftKey, ct rlKey, o r altKey properties, which
return a Boolean value. Note that most of the key combin ations using the modifier
keys Ct rl and Alt r epresent shortcuts for browser commands an d will therefore be
intercepted by the browser. For example, the key combination Ctrl+T will open a
new browser tab and will not fire a keypress event on the document.
One more usefu l feature of the jQuery event A PI is that it allows you to trigger events
manually. You already know th at event handlers are normally invoked automatically
when certain events occur, but some times it is useful to be able to trigger an event
from within your code. This is ma de possible with the trigger( ) method, which
accepts as the first argument a string specifying the type of event. For example, you
can trig ger a click event on all the elements with a class of special like this:
$(".special").trigger("click");
You can also pass arguments to the event-handler function when yo u manually trigger
an event. On e way of doing this is to p ass an object a s th e first argument to the
trigger() method, instead of ju st passing a string specifying the type of event. If
you do this, then a new jQuery Event object will be created and the properties of the
passed object will be added to it. You must still specify the event type, of course,
which you d o by setting the type property of the passed object. For example, you can
trigger the keydown event like this:
$("p").trigger({type: "keydown", which: 42});
Animation
When you add or remove an element from a page, or otherwise change the page ap-
pearance , you can do that either instantaneously or you can an imate the change by
gradua lly modifying certain pro perties such as size or opacity. It is often not a very
pleasing experience for a visitor if an element just disappears into thin air. It is much
nicer if it slowly slides up or fades out, for example. jQuery makes such animatio ns
easy by defining some convenient a nimation methods.
There are some general facts about jQuery animations that you should know:
Every animation has a duration, which a program mer can change. Yo u can
specify a dur ation either as a number of milliseconds o r by providing a string of
predefine d text. You can use the strings "fast" and "slow", which stand for
200 ms and 6 00 ms, respec tively. If no duration is specified, then the animation
lasts for 400 ms, which is default.
All the jQuery an imated eects are asynchr onous. When you invoke an ani-
mation method, it returns immediately and the animation is performed in the
backgr ound. This means that the code which follows will be executed while the
animation h as not ye t necessarily completed.
B.4. jQu ery 293
If there’s some code that you don’t want to execute while the animation still
lasts, you can register it as a callb ack function. The callback function will be in-
voked automatically when the eect complete s. You cannot pass a ny arguments
to the callback function, but the this keyword will be accessible inside the
function referring to the element that was animated. So if you need to pass ad-
ditional information to the callback function, you can do that using the data()
method, which allows you to associate arbitrary data with an element.
If you invoke an a nimation method on an already animated element, then the
new animation eect is put into an animation q ueue and is not anim ated until
all the eects before it are completed. Note, however, that each element has its
own animation queue.
There exist nine basic eects that jQuery d efines for hiding and showing elements, and
one method intended for custom animations. The simplest are eects that only animate
the CSS opacity property: fade In(), fadeOut(), and fadeTo(). These three
eects change the element’s visibility but don’t remove the elem ent from the page even
if it b ecomes completely invisible (when opacity becomes zero ). The fadeIn() and
fadeOut() methods animate opacity towards one a nd zero, respectively. However,
if you want to animate opacity to any other value, use the fadeTo() me thod, which
accepts the target opacity value as the second argument. The first argument is the
animation d uration, which you must always spe cify when c alling fadeTo().
If you want to remove the elemen t from the page layout (i.e., set the CSS display
property to none), then call hide(). This method gradually shrinks the element’s
width and height to zero and reduces its opacity to zero at the same time. If you
want to show the element again, then ca ll show( ), which reverses the process. By
default, hide() and show() do not animate the ch ange, but hide and show selected
elements instantly. If you want to get an animated eect, then pass an optiona l duration
argument. You can also toggle an element from visible to hidden and vice versa by
simply callin g toggle(). Tog gle eectively calls hid e() if the element is visible,
and it calls show() if the element is hidden.
The last thr ee of the predefined eects are slideUp(), slideDown(), and slide
Toggle(). slideUp () is similar to hide() but it o nly hides the element by ani-
mating its height to zero an d then setting its CSS display property to none. The
element’s width and opacity don’t change. The slideDown() property shows the el-
ement again by reversing the process. slideToggle( ), as its name suggests, toggle s
between slideUp() and slideDown ().
These are some examples of the basic animation methods in action:
$("p").fadeTo(500, 0.5); //Changes opacity to 0.5 in 500 ms
$("p").hide(500); //Hides all the paragraphs in 500 ms
$("p").show(); //Shows them back immediately
$("p").slideUp(); //Slides them up
$("p").slideToggle(function(){ //Registers a callback function
$(this).text("That’s all folks!"); //and slides the paragraphs
}); //back down
294 Appendix B. Ways to Continue
You can pro duce more universal animated eects with the animate( ) method. In
its simplest form, the me thod accepts a so-called animation properties object, which
is no more than a plain JavaScript object whose properties are CSS property name s.
The specified values of these properties are target values towards which the animation
will run. N ote, however, that only numeric properties can be animated and you cannot
animate things like colors and fonts. If you use a number as a property value, then
pixels are assumed. You may also spec ify dierent units, which you may do if you
use a string as a property value. There’s another option you have if you use a string:
you can specify a relative value by prefixing a value with either "+=" to inc rease or
"-=" to decrease the value of the specified property. For example, you can animate
moving all the selected e le ments to a sing le absolute position like this:
$("p").animate({left: 100, top: 100});
In order for this to work, th e CSS position property of the selected ele ments must
be set to absolute, of course.
The next example in flate s the width and height of the selected elements by 10 pixels:
$("p").animate({width: "+=10", height: "+=10"});
Apart from n umeric values, it is also p ossible to use the values "hide", "show", and
"toggle". The value "hi de" first saves the current numeric state of the property and
then animates it towards zero. At the end, it sets the display property of the animated
element to none. To animate a property ba ck to its saved value, you use "show". Not
surprisingly, "togg le" performs either a show or a hid e, depending on the curren t
element state.
As an example, the next code mimics an eect similar to that produced b y the slide
Toggle() method excep t that elements slide to the left:
$("p").animate({
width: "toggle",
"padding-left": "toggle",
"padding-right": "toggle"
});
Note the quotes around the h yphenated property names. Because they contain hy-
phens, they are no t legal JavaScript identifiers and have to be quoted. You can, of
course, also use the camelCased alternatives paddingLeft and p addingRight if
you do n’t like to use quotes.
Sliding Puzzle
At the end of this concise review of the jQuery library, we look at a somewhat more
sophisticated example of a 15-puzzle. The 15-puzzle is a sliding puzzle com posed of
15 numbered square tiles, arranged inside a square frame in random order as shown in
this p ic ture.
B.4. jQu ery 295
..................Content has been hidden....................

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