Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

518 LESSON 18: Using jQuery


There are other methods for adding content in different locations in relation to a selected
element. For example, if I change the append() call to prepend(), new items will be
added to the top of the list rather than the bottom. You can also use the before() method
to add content before another element, and the after() element to add it after. The
difference is that when you use those methods, the content is placed outside the tags
matched by the selector, rather than inside those tags.

Special Effects


It can be a little jarring when elements just appear or disappear instantly. Most JavaScript
libraries, including jQuery, provide a library of effects that enable you to animate transi-
tions on the page when items appear, disappear, or move. jQuery has a few basic effects
built in to the core library. Supplemental effects are also available as part of jQuery UI,
which you can obtain at http://jqueryui.com/.
The four effects that are part of jQuery are fade in, fade out, slide up, and slide down. I’m
going to build on the previous example to show you how they can be used to soften the
transitions when you add items to the page or remove items from it. Adding the effects to
the page just requires a few small tweaks to the event handlers that I already created.
The first effect I added applies the fade-out effect when users click a list item to remove
it. To cause an element to fade out, you call the fadeOut() method on the results of a
selector that matches that element. Here’s the code:
$(document).on('click', "#editable li", function () {
$(this).fadeOut('slow', function() { $(this).remove() });
});

When you call fadeOut(), it sets the display property for the element to none—
essentially, it’s a fancy replacement for hide(). Figure 18.14 shows a list item that’s in
the pro cess of fading out.
In this case, I want to actually remove the element from the page entirely. To do so, I
need a callback, which is included as the second argument to fadeOut(). The callback is
run whenever the animation is complete, and in this case, it removes the element from the
page. The first argument is used to specify the speed of the animation. Setting it to slow
means that it will take 600 milliseconds to complete. By default, the animation takes 400
milliseconds. You can also set it to fast (200 milliseconds), or you can enter a number
of milliseconds yourself.
Free download pdf