jQuery in Action
260
CHAPTER 8
Talk to the server with Ajax
The flyout will be instrumented to fade out once clicked within its
boundaries.
boundaries.
The
URL
of the server-side resource, as well as the
CSS
class assigned to
the flyout element, can be assignable by the page author but will have rea-
sonable defaults.
sonable defaults.
The code that creates a jQuery command that meets these goals is shown in list-
ing 8.8 and can be found in the file chapter8/bootcloset/jquery.jqia.termifier.js.
ing 8.8 and can be found in the file chapter8/bootcloset/jquery.jqia.termifier.js.
(function($) {
$.fn.termifier = function(options) {
options = $.extend({
lookupResource: 'getTerm',
flyoutClass: 'lookerUpperFlyout'
},options||{});
this.attr('title','Click me for my definition!');
return this.click(function(event){
$.ajax({
url: options.lookupResource,
type: 'GET',
data: {term: this.innerHTML},
dataType: 'html',
success: function(data) {
$('<div></div>')
.css({
position: 'absolute',
left: event.pageX,
top: event.pageY,
cursor: 'pointer',
display: 'none'
})
.html(data)
.addClass(options.flyoutClass)
.click(function(){
$(this).fadeOut(1500,function(){$(this).remove();});
})
.appendTo('body')
.fadeIn();
}
});
return false;
});
}
})(jQuery);
Listing 8.8
The implementation of the termifier() command
Defines
command API
command API
b
Merges options
with defaults
with defaults
c
Establishes
click handler
on terms
click handler
on terms
d
Initiates request
for term definition
for term definition
e
Acts upon
response data
response data
f
Establishes click
handler on flyout
handler on flyout
g
Attaches flyout to
DOM and fade in
DOM and fade in
h