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

(singke) #1
ptg16476052

524 LESSON 18: Using jQuery


Here’s the event handler for the click event for the links:
$("p.countryOption a").click(function (event) {
event.preventDefault();
$("p.countryOption").fadeOut();
$("#country").load($(this).attr('href'));
$("#country").fadeIn();
});

You should be used to most of this by now. The first line prevents the link from actually
taking you to the link referenced in the href attribute. The second line fades out the links,
because they’ll be replaced by the country data.
The third line actually performs the AJAX request. It instructs jQuery to load whatever is
in the href of the link the user clicked on into the element with the ID “country.” In this
case, the links refer to jQuery selectors of sorts. Remember the URLs in the links? They
consist of two parts, the first being the file to load, and the second being a jQuery selec-
tor, in this case, the ID of the country that I’ll be displaying information about. jQuery
loads the entire page, and then applies the selector to it to extract the information I care
about.
Here’s the full source code for the page:
<!DOCTYPE html>
<html>
<head>
<title>Learn More About South America</title>
<style>
#country { border: 1px solid black; padding: 15px; }
p.question { font-size: 200%; }
</style>
</head>
<body>
<p class="question">
Which country would you like to know more about?
</p>

<div id="country">Foo</div>

<p class="countryOption"><a href="countries.html #uruguay">Uruguay</a></p>
<p class="countryOption"><a href="countries.html #paraguay">Paraguay</a></p>

<script src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
$("#country").hide();

$("p.countryOption a").click(function (event) {
event.preventDefault();
$("p.countryOption").fadeOut();
Free download pdf