ptg16476052
520 LESSON 18: Using jQuery
Finally, I want the new items I add to the list to fade in rather than just appearing. Here’s
the updated event handler with the fadeIn() call included:
$("#addElement").submit(function (event) {
event.preventDefault();
var content = "<li>" + $("#addElement input[name='liContent']").val() +
"</li>";
$(content).hide().appendT o("#editable").fadeIn('slow').css("display",
"list-item");
$("#addElement input[name='liContent']").val("").focus();
});
This event handler is a little bit more complex. First, I initialize a new variable with the
content to add to the page, just to make the code a little more readable. Then I go through
all the steps required to fade the new content in. At this point, I should explain one of the
other nifty features of jQuery—method chaining. Nearly all jQuery methods return the
object of the method. So if I use hide() to hide something, the method returns whatever
it was that I hid. This makes it convenient to call multiple methods on the same object in
succession.
In this case, I call hide(), appendTo(), fadeIn(), and css() on the jQuery object rep-
resenting the new content that I created. First, I pass the content variable to $(), which
allows me to call jQuery’s methods on the content. Then I call hide() on it so that it
doesn’t appear instantly when I append it to the list.
After that, I use appendTo() to append it to the list. The difference between append()
and appendTo() is that with append(), the object of the method is the selector that rep-
resents the container, and the method parameter is the content to be appended, whereas
with appendTo(), the content to be appended is the object and the selector for the con-
tainer is the method parameter. In this case, using appendTo() makes it easier to chain all
of these method calls.
After I’ve appended the hidden content to the list, I call fadeIn('slow') to make it grad-
ually appear. Then, finally, I call css("display", "list-item") on the new content.
When fadeIn() is done, it sets the display property for the list item to block, which
causes the bullet for the list item not to appear in some browsers. Setting the display
property to list-item ensures that a bullet is displayed.
AJAX and jQuery
One of the primary reasons programmers started adopting JavaScript libraries was that
they made it much easier to use AJAX techniques on their websites and applications.
What’s AJAX? It’s a description for functionality that uses a JavaScript feature called