jQuery in Action
Putting it all together
261
Perhaps not as much code as expected, but there's a lot going on in there! Let's
take it one step at a time.
take it one step at a time.
First, we use the pattern that we learned in chapter 7 to establish the
API
for
the
termifier()
command
b
. The only parameter expected is an object whose
properties serve as our options. To be friendly, we provide a default set that we
merge into the passed options using the services of the
merge into the passed options using the services of the
$.extend()
utility function
c
. The defined options are as follows:
lookupResource
--Specifies the
URL
of the server-side resource to be used
flyoutClass
--The
CSS
class name applied to newly created flyout elements
As a helpful tip to our customers, we add a
title
attribute to the target element
so that if they hover the mouse cursor over the highlighted term, they will see a
message letting them know that clicking the term will do something wonderful.
message letting them know that clicking the term will do something wonderful.
We establish a
click
handler on every element in the matched set
d
. Remem-
ber that the function context (
this
) for a jQuery command is the matched set, so
applying other jQuery commands to the matched set is as easy as calling the com-
mands on
mands on
this
.
In the listener for the
click
event, we initiate the Ajax call that will retrieve the
term definition. For maximum control, we use the
$.ajax()
function
e
and pass
it an object that defines the following options:
The
URL
specified by the command options (either the default or one pro-
vided by the page author)
An
HTTP
method of
GET
(because the request is clearly idempotent)
A request parameter named
term
that's set to the content of the event tar-
get (the function context within the listener)
Identification of the expected response data as
HTML
A
success
callback
f
that uses the response data to create the flyout
A lot of the more interesting things happen in the
success
callback for the Ajax
request. First, a new and empty
<div>
element is created, and then the following
operations are performed on it (using the magic of jQuery chaining again):
CSS
styles are added to the
<div>
element that absolutely position it at the
point of the mouse click event, change the mouse cursor to the hand
shape, and hide the element from view.
shape, and hide the element from view.
The response data, passed as the first parameter to the success callback
and which we know contains the term definition, is inserted as the content
of the
and which we know contains the term definition, is inserted as the content
of the
<div>
element.