Вы находитесь на странице: 1из 400

_

sitepoint


JQUERY

JavaScript, jQuery

JQUERY, -
^
SECOND
EDITION

JQUERY
NOVICE TO NINJA
NEW KICKS AND TRICKS
BY EARLE CASTLEDINE
& CRAIG SHARKIE

i t sitepoint*


JQUERY

JavaScript, jQuery

^ *
- - - -
-- -

2012
., .
jQuery

2-

.
.
.
.
.
.

32.988.02-018
004.738.5
., .
28 jQuery. 2- . .: , 2012. 400 .: .
ISBN 978-5-459-01619-2
jQuery, JavaScript-,
. jQuery
10 000 -
.
jQuery,
, -.
, ,
jQuery Mobile.

ISBN 978-0987153012 . 0 0 2012 SitePoint Pty. Ltd.


ISBN 978-5-459-01619-2 , 2012
,
, 2012

Sitepoint. .

.
, , ,
. , ,

, .

, 198206, -, , 73, . 29.


005-93, 2; 95 3005 .
27.06.12. 70x100/16. . . . 32,250. 2000. 543.
.
180004, , . , 34.

........................................................................................ 15
..........................................................................................22
........................... 23
1. jQ uery........................... 24
2. , .......... 40

3. , . . . . .................. 70
4. - ..................................................... 105
5. , , ......................................144

6. , Ajax .................................... 186

7. , ................. 231
8. , ...................................................291
9. , . .327

. ...............................................381
. , JavaScript............... 391
. ,
........................................ 396

..........................................................
................................................................. 16
............................................................................16
............................................................. 18
S ite P o in t................................................................... 19
-, .................................... 19
SitePoint Podcast......................................................... 19
................................................................................ 19
..................................................................................20
......................................................................... 20
................................................
, ................. 20
.................................................. 20
, ................................21

....................................................................
................................................................................. .22
.................................................................................... 22

................................................................................ 23

1. jQ u e ry ................... 24
jQuery ?..............................24
- .......................................... 25
CSS3..................................................................... 25
................................................................. 26
jQuery U I ................................26
........................................................... 27
7

.............................................. 29
.................................................29
?...................................................30
jQuery -............... 30
jQuery .. . . .......................................... 31
Google Content |Distribution Network (C D N )................... 32
C D N ................................................................... 33
Nightly G ithub................. 34

?..................................................................... 34
jQ u e ry ............................................................... 35
jQuery................................................................... 35
jQ u e ry .......................................................36
HTML, . . . .37
jQuery......................................... 39

2. , .. .40
, - ....................... 41
: jQuery.....................................................42
................................................................... 42
...........................................................45
..........................................
..................................................................................46
..........................47
............................47
: CSS jQ u e ry .. . .48
CSS- ........................................................... 48
CSS-...........................................................49
........................................................
............................................ 52
:
jQ u e ry ............................................................ .53
........................................ 53
.. .............................. 55
.......................................................55
..............................57
........................................................... 58
8

.......................................... 61
............................................................. 62
:
...........................................................63

fadeln fadeO ut.. .63
.................................... 64
c a llb a c k ..............................................................................64
.......... ........................................................... 65

........................................
.....................................................67
...................................... 69

3 . , ................... 70
.....................................................................
CSS-...........................................................70
............................................................... 72
............................................................................73
............................................................. 75
.........................................................76
................................................................. 79
.......................................... 80
...................................... 81
.....................................................81
. 2 ...................................... 84
jQuery U I...........86
!............................................................... 88
........................................................................................ 88
scroll............................................................ 8
.............................................. 90
.............................................................91
............................................ 93
.................................................................... .95
re size .......... .......................................
.........................................................96
9

, ............... 98
textarea,
........................................................... 99
........................................................... 100
. ............................ 104

4 . - ................................................. 105
.......................................................................................105
() ......................105
console.log........... 109
ColorBox: -.................. . . . . 1 1 1
J c ro p .........................................114
- ...................................................................................... 117
-
....................................................................117
- .................................... 131
iPhoto- - .................................... 137
, !...................................... 143

5 . , , ................................ 144
............................................................................................... 144
/ .............................. 145
/.............................................150
. . . . 151
......................................................... 153
..................................................................157
................................................................157
...............................................161

jQuery UI....................................................... 162
...........................................................................................164
..................................................................164

jQuery U I....................................................... 166
........................................................... 169
..................170
..................................................... 171
10

.......................................................................................175
.......................................175
................178
........................................................................ 185

6. , Ajax .............................. 186


. .................................. 186
jQuery . . 187
........................... 192
(... !)...........................................196
A ja x .......................................................................... 197
A ja x ? ....................................................................197
HTML-.............................. 198

Hijax............................................................... 199
HTML- ........... 200
......................................................... 201
: on o ff...................................... 202
$.getJSON................................ 203
Twitter-...............................................205
Ajax jQ uery........................................ 205
A ja x ......................................................... 207
$.getScript........... 207
GET POST..................................... 208
Ajax- jQuery........................................................... 209
: A ja x .................................................211
A ja x ................................................... 211
........................................................... 225
Ajax ?
!..........................................................................230

7. , ......... 231
.............................................................................................231
....................................................... 232

Validation............................................................. 237
.......................................... 240
ii

............................................................. 242
........... 243
.................................................244
Autocom plete.................................. 250

.............................................253
................................................................... 259
.................................................................................. 259
............................................................................260
()........................................................... 263
...............................................267
sortable
jQuery U I........................273
.................................................275
...................................................277
.................................. 277
Dialog
jQuery UI....................................................... 281
Growl- ...............................................284
.................................... 287
..................................................................... 290

8. , .............................................. 291
.............................................................................................291
selectable
jQuery U I ........................292
............................................................. 298
. .. 300
.......................................................................................... 304
.....................................................304
....................................................... 307
.......................................................................................... 309
...................................... 309
......................................................... 313
........................................................................315
. . . . 324
!..............................................................................326
12

9 . ,
....................................................... 327
....................................................................327
........................................ 328
............................................................. 335
jQ u e ry .......................................... 336
................................................................................ 347
jQ u e ry ........................356
........................... 356
. .357
JavaScript- jQuery-........... 359
..............................................................................360
, ......................361
.................................. 361
................. 363
............................... 365
StarTrackr!: ..........................................................................380

. .......................................... 381

. , JavaScript..........................391

. ,
.................................. 396

.


,

, .


, ,
,
.
,
- .
j Query ,
-,
.
:
- Ajax-. ,

. , ,
, , jQuery.
jQuery
jQuery UI.
( accordion, tabs d ia lo g ),
.
jQuery UI
, ,
jQuery.
jQuery ,
-
.
,
. jQuery
, :

,
.
, -
API
. ,
- ,
, -
. , ,
j Query .
16


-,
-,
j Query, .
JavaScript
, ,
, . j Query,
,
,
.
,
HTML CSS,
j Query CSS- .
, ,
j Query, ,
HaJavaScript. JavaScript,
. ,
.



HTML- CSS-- jQuery.
, ,
Ajax, ... ,
HTML CSS !
jQuery UI
jQuery Mobile.
.
, ,
. , ,
.
1. jQuery.
jQuery, ,
:
JavaScript-
JavaScript. CSS,
jQuery,
, jQuery
.
2. , . jQ uery

JavaScript,
. ,
jQuery ,
17

, CSS-
j Query.
3. , , j Query
:
,
j Query.


.
.
4. -. ,
j Query:
-. , Lightbox-,
, ,
iPhoto- .
5. , , .
j Query,
:
, ,
. :
- 1990-
- RIA (Rich Internet
Applications) XXI !
6. , Ajax .

,
, ,
Ajax. ]Query
, Ajax- -
, .
,
.
7. , . ,
-,
-. , j Query
, .
, ,
, .

: d a te p ic k e r, s lid e r
Drag and Drop.
,
. !
8. , . ,
Web 2.0, ,
,
, - .
18

, j Query
, ,
,
.
9. , , j Query

(Document Object Model, DOM) Ajax-,
UI.
, :
,
, .
j Query UI,


. ,
j Query Mobile,
.
. , j Query
,
. , Ajax,

, ,
.
. , JavaScript. , ,
j Query JavaScript.
JavaScript.
, JavaScript.
. ,
.
, ,
.
: j Query- pushstack
.
, j Query-
, .
. SitePoint
http://www.sitepoint.com/quiz-jquery.


j Query , ,

. SitePoint
JavaScript jQuery,
, - .
19

SitePoint
SitePoint1 ,
. ,
. ,
: - , - ,
. ,
.
-.
.
JavaScript12 j Query.

-,
- http://www.sitepoint.com/books/jqueryl/
3.
,
. , ZIP,
, .

SitePoint Podcast
SitePoint Podcast, , ,
- .
, -
. 4, ,
, http://www.sitepoint.com/podcast/.
iTunes.



,
books@sitepoint.com.
,
, .
,
.

1 http://wvvw.sitepoint.com/forums/
2 http://www.sitepoint.oom/fbrums/fbrumdisplay.php?f= 15
3 http://www.sitepoint.oom/books/jquery2/code.php
4 - ,
. . .
20


,
, - , ,
-, SitePoint ,
,
JavaScript- (
), jQuery ( ) ,
JavaScript-.
,
Commodore 64, a Spectravideo 318,
, .



,
, ,
.
, ,
. SitePoint
j Query .
SitePoint.
, , .

,


.


,
:
<hl>A Perfect Summer's Day</hl>
<p>It was a lo v e ly day fo r a walk in the park. The b ird s
were sin gin g and the kids were a ll back at school.</p>

,
,
, :
, 21

.css
.fo o te r {
background-color: #;
border-top: lp x s o lid #333:
}
, .
_.55 ()
border-top: lpx s o lid #333:

,
:
function animateO {
n e w v a ria b le = "H e llo ";
}
, , ,
, :
fu n ction animateO {

return new va riab le ;


}
,
- , .
,
, :
URL.open("h ttp ://www.sitepoint.com /blogs/2007/05/28/user-style -sh e
^ e ts -c o m e -o f-a g e /M);

, !
, ,
.

, ...
,
. .

, ...

|
... .

!
,
.


( )
-,
, . 8-
, 90- XX ,
.
JavaScript-,
Scala,
, ,
.
TurnTubelis1,
-.
,
ECMAScript ,
.


, , ,
.
, -,
AOL, Microsoft, Yahoo!, Ziff-Davis Atlassian.
HTML5 JavaScript
IPTV- Telstra Media, ,
j Query.
, , ,
,
. JavaScript 1995 ,
,
JavaScript: (JavaScript: The
Good Parts). ,
,
.
.
1 http://www.tumtubellst.com/

,
halickaya@minsk.piter.com ( , ).
!
http://www.piter.com
.

1 jQuery
, HTML-.

CSS,
-, .
HTML ,
Facebook Twitter.
?
JavaScript, ,
-.
JavaScript - ,
. ,
JavaScript,
, :
, , , , ...
, (,
-, Amazon, Google, Microsoft, Mozilla, Twitter Word Press,
): jQuery!

,
.
, jQuery
HTML CSS ,
JavaScript. , ,
jQuery -.

jQuery
?
, jQuery
DOM, Ajax-.
, , ,
( )
JavaScript?
jQuery ? 25

, jQuery
DOM, Ajax-.
, ,
- (
,
!). , ,
JavaScript.

-
,
jQuery , ,
- . ,
JavaScript-, , -
. , ,
Mozilla Firefox Internet Explorer 8,
Internet Explorer 7 . ,
,
, Opera Linux.
, .
-
, .
11 , ,
, ,
.
jQuery -
, , , , .
jQuery,
.
,
Internet Explorer 6. ,
,
Internet Explorer 6, , jQuery
, , .
jQuery .
,
-, jQuery
, (
),
.

CSS3
-
, jQuery
CSS3. , Internet Explorer 6 !
26 1. jQuery

, CSS3
. ,
, jQuery, CSS3
.


,
, jQuery ( JavaScript!):
, . .
,
jQuery JavaScript, ,
.
, , supports,
,
. ,
, ,
, , .
.
.
supports jQuery, ,
,
,
.

Modernizr1
,
.
, ,
.

jQuery UI
jQuery ,
,
jQuery.
, Dimensions Unwrap
. jQuery
jQuery, .
jQuery : ,

, jQuery.
1 http://modemizr.com
jQuery ? 27

jQuery , jQuery
Mobile ( 9). jQuery UI
,
.
. 1.1.

Tabs Slider

I First Second

Lorem ipsum dolor stt amet. consectetur adlplsknng elit, sod do Datepicker
eiusmod tempor incididunt ut labore e t doiore magna atlqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex commodo consequat.

Su W Fr Si

1 2
Dialog
3 4 s fti "~7' 9
ip Open Dialog
10 13 14 it : ;

17 is 19 20 21 22'23)
Overlay and Shadow Classes
24 26 27 23 29 30

31

Lorem Ipsum dolor sit amet, consectetur adiplsiclng Progressbar


elit, sed do eiusmod tempor incidldunt ut labore et
doiore magna aiiqua. Ut enim ad minim veniam,
puts nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
Highlight / Error

Hey! Sample ui-state-highlight style.

. 1.1. jQ u e ry UI

accordion, s lid e r, dialog, datepicker


! ,
jQuery, ,
jQuery UI ,
,
,
d atepicker !

jQuery UI.
, ,
jQuery
ThemeRoller.


jQuery .


28 1. jQuery

,
jQuery-. .

jQuery, .
, , .

,
.
,
jQuery, jQuery
, ,
. . 1.2.

PLUGINS
Browse b y category Browse by name Browse by date


Ajax (142)

Animation and Effects (178)

Browser Tweaks (56)

Data (96)

DOM {99)

. 1.2. jQ u e ry

, - ,
, ,
. ,
, , .
, - ,

, .

?
jQuery1
. : ,
,
,
,
. ,
, , jQuery2.
- GitHub3.

1 http://plugins.jquery.com
2
http://blog.jquery.com /2011 / 12/ 08/what-is-happening-to-the-jquery-plugins-site
https://github.com /jquery/plugins.jquery.com
jQuery ? 29



-,
. jQuery

,
CSS- . jQuery
,
, , . ,
, !
jQuery HTML-

.
HTML- .
,
- , ,
,
, .


Google Trends1, ,
jQuery. ,
BuiltWith12. . , ,
,
.
jQuery -:
IBM, Netflix, Nokia, Wikipedia Google (
jQuery ),
Microsoft, jQuery MVC
Visual Studio.
jQuery ,
, ,
, , . jQuery
40 % , JavaScript,
jQuery-
.
jQuery
, .

1 http://www.goog le.<x>m/trends
2 http://trerKls.builtwith.com/javascript/jQuery
30 1. jQuery

.
,
, - .

?
- !
JavaScript
: ,
, ,
,
.
,
.
, , jQuery
. jQuery
19 , , JPG.
, (,

jQuery UI), ,
.
( )
, JavaScript- .
, , jQuery ,
!
,
JavaScript
.
, JavaScript (
), jQuery
DOM, Ajax-.
,
, .
,
, jQuery, , .
: jQuery!


jQuery -
jQuery (,
, ),
-.
JQuery - 31

, .
, ,
jQuery HTML-,
JavaScript.

JAVASCRIPT!

, jQuery JavaScript!
-, JavaScript,
, - , JavaScript.
, - ,
JavaScript.

jQuery
jQuery
- jQuery1, .
, ,
jQuery.
,
jQuery- Content Delivery
Network (CDN), Google CDN CDN Microsoft. CDN
,
.
,
.
JavaScript
. ,
HTML-: s c r ip t s
ja v a s c r ip t HTML- .
,
HTML-.
, HTML-
jQuery. < scri pt>
head -. <head> HTML-
jQuery :
<head>
< title > H e llo jQuery w o rld !< /title >
< script ty p e = 'te x t/ja v a s c rip t' src= jq u e ry -1 .7 -m in .js ></script>
< script ty p e = 'te x t/ja v a s c rip t s r c = 's c r ip t . j s ></script>
</head>

s c r ip t jQuery,
s c ri p t . js,

1 http://jquery.com
32 1. jQuery

j Query. , :
jQuery.
.
jQuery , ,
head .
, head .
,
, body, :
</section>
<script ty pe = "te x t/ja v a s c rip t" src="jquery-1 .7-min.js"></script>
<script ty pe= "text/javascript" src="script.js"> < /script>
</body>
</html>

s c r i pt j Query, -
s c r ip t , js.
(
).
, j Query
, ,
, .
j Query,
.

Google Content |Distribution


Network (CDN)
j Query, ,
Google CDN.
Google CDN
, j Query (
jQuery , ). , ,
jQuery - ( ),
Google .

Google
j Query.
Google CDN ,
j Query Google,
.
- ( URL-
JavaScript- ),
.
j Query UI. Google CDN
jQuery - 33

:
,
!1
jQuery, Google CDN,
. (
, ) :
<head>
< title > H e llo jQuery w orld!< /title>
< script type=,,t e x t / j a v a s c r ip t " src="h t t p : //ajax.googleapis.com/
b* ajax/lib s /jq u e ry /1 .7 .0 /jq u e ry.m in .js"> < /s crip t>
< script t y p e * 'te x t / j a v a s c r ip t ' s r c = ' s c r i p t . j s ></script>
</head>

,
s c r ip t jQuery,
Google.

JQUERY
GOOGLE CDN
URL-, Google,
, jQuery (
1.7.0).
, ( ,
, 1.7) ,
1.7 (1.7.1,1.7.2 . .). (1), Google
, jQuery 1.8 !
: , .
, URL-
CDN HTML- jQuery,
,
.


Google , 12
.

CDN
Google ,
. jQuery
CDN3, Microsoft .

1 ,
Google CDN , -
. . .
2 http://code.google.com /api^ajaxlibs/docum entation
1 http://code.jquery.com
34 1. jQuery

, Microsoft
CDN.
1.

Nightly
Github
, jQuery,
Downloading
jQuery2.
Nightly.
jQuery, , .

- ,
, .
, ,
Github , ,
. Github
, jQuery.
jQuery , -
.
: Nightly, jQuery
Github . ( )
. , ,
jQuery,
.


?
jQuery
, , jQuery,
, :
( ) ( ).

, jQuery :
, . JavaScript-
jQuery,
.
.

1 http://asp.neVajax!ibrary/cdn.ashx
2
http://docs.jquery.oom / DownloadingJQuery
jQuery 35

.
jQuery ( !1),
, :
JavaScript-. , ,
jQuery, ,
, ,
JavaScript.

jQuery
, jQuery -, ,
. jQuery
, , ,
.
.

jQuery
jQuery -
( ) jQuery.
? jQuery
, - .
jQuery,
,

JavaScript. , : jQuery
hi de ( ).
,
, .
jQuery jQuery.

, , jQuery (
),
jQuery , .
jQuery ,
.
$.
,
JavaScript. ,
( ,
). ,

http://code.jquerY.eom /jquerY-l.7.0.m in.js


36 1. jQuery

j Query, ,

.


, jQuery
, ,
JavaScript,
. ,
, .

jQuery
, jQuery jQuery
. jQuery. . 1.3
jQuery (
, ).

s e le c to r a ctio n param eters

jQuery(' ' ) . css ('c o lo r ', ' b l u e ' );

$('') . css ( 'c o l o r ', 'b lu e ');

. 1.3. jQ u e ry

: jQuery ,
, ( ) .
jQuery, .
-.
,
.
. , ,
jQuery, .
, jQuery,
. ,
.

(HTM L- <>). jQuery- css,
CSS- , .
CSS- col or
blue. ? !
css 2.
HTML, 37

css (c o lo r blue),
.
,
( ),
JavaScript
(,
).
.

,
. !

HTML,

jQuery HTML CSS.
CSS , , di v#headingwould
di v id heading,
.
CSS
(Document Object Model, DOM).
DOM jQuery
HTML-
, .

jQuery.
DOM ,
HTML .
HTML-, (, di v )
( ),
.
id / class,
HTML-. HTML-
DOM,
-, ,
( -) , ,
.
DOM . 1.4.
, body : hi . ,
,
.
i d
:
<div id="farewell">Come back and v i s i t us soon!</div>
38 1. jQuery

. 1.4. D O M

di v i d, farewel 1.
, :
. DOM

class. ,
:
< class="warning,,>Sorry. this field must be filled in !</p>
<span class="warning">Please try again</span>

"warning". CSS "warning"
. class
( ) .
CSS-
i d - (#)
cl ass (.):
#footer { border: 2 solid black }
.warning { color: red }
CSS ,
id farewel 1, ,
"warning" .
jQuery-, ,
CSS DOM : jQuery
, CSS, ,
.
, jQuery!
jQuery.. 39

jQuery...
jQuery ,
- ,
-.
,

. ,
jQuery!
, jQuery
, . jQuery
, .
,
. ,
, jQuery
JavaScript .
2 jQuery
-. ,
, .
,
2



Ajax Web 2.0,
.
.
StarTrackr!.
GPS RFID-
,
.
,
.
? ,
, .
, . ,
, , , ,
jQuery. . .
!

JavaScript,
. , -,
, StarTrackr!
.
, JavaScript
, , jQuery .
, .
1 jQuery. ,
, jQuery :
-, .
, ,
. , jQuery
, , , ...
, - 41

!
( ,
, - JavaScript). ,
.

, -

HTML- -,
: ,
. , JavaScript,

- ( ),
- .
, j Query ,
. -
.
chapter_02/01_document_ready/scri p t. js
$(document).ready(functionO {
a l e r t ( 'Welcome to StarTrackr! Now no longer under p o lic e ...'):
i n v e s t ig a t io n ! );
}):
( )
: ,
. j Query,
, , .
,
, j Query
.

$(DOCUMENT).READY()
^ ^ ^ , jQuery, ,
( ), $(document). ready()
.
document-ready. , ,
, document-ready.
.

document-ready ,
. jQuery ,
"(document)" "ready":
$(function() {
a le rt('R e ad y to do your b id d in g !');
}):
42 2. ,

, ! ,
,
.
, -,
JavaScript.
, document-ready
,
jQuery, , ,
: document,
ready, ,
( a le rt).

: jQuery
, .
,
-. ,

. ,
- ,
.
jQuery ,
.
jQuery.
,
, , !
jQuery,
jQuery:
jQuery(<selectors go here>)

:
$(<selectors go here>)


jQuery $ . ,
,
, (.

jQuery 9).



. ?
jQuery , -
: jQuery 43

: ,
, .
(. 2.1).

O ur C e le b ritie s <h2 class="heading">

We have an ever changing roster of newlv chinner}


celebrities.
c But it can take as little as a week for the
little critters to realise th <p d a s s -infb"> u have to be fast
T
IU I4CUIIC r n u t:

<table id="celebs" dass="data">


203 Johny Stardus S39.95

141 Beau Dandy (.) Singer New York $39.95

2031 M o Fat (pic) . Producer New York SI 9.95

. 2 .1 . class id H T M L -


. HTML-
$.
( <tr>)
:
$(' t r ')

!
.
, . :

.

, <di v>,
<hl> <input>, :
$('')
$ ('diV)
$('h l ')
$('in p u t')
,
. ,
. ,
-, .
HTML-, . 2.1, ,
di v, tab! ,
id celebs, table
44 2. ,

cla ss data. tab le


, .
chapter_02/02_selecting/index.html ()
<table class=,,data id=,,celebs,,>
<thead>
< tr>
<th>ID</th>
<th>Name</th>
<th>Occupati on</th>
<th>Approx. Location</th>
<th>Price</th>
</tr>
</thead>

( id ) (c la s s ) jQuery
CSS.
id, - (#),
, jQuery:
$ ( '#celebs )

, , jQuery,
, CSS- id. id
, , .
jQuery .
CSS- cla s s
1ass.
jQuery , (.),
:
$ ( ' .d a ta ')

, ,
DOM,
c la s s .
jQuery ,
. (
), c la s s data,
.
id!

?
CSS, $( . data ) , ,
$ ('ta b le .d a ta '). class
, class data,
. , CSS,
,
.
: jQuery 45


,
.
-,
, . ,
, - table.
:
$('#celebs t r ')
,

.
. ,
<span>,
<>, , , <div>.
,
<div>, class fancy.
:
$('div.fancy span')
,
, !


, . ,
, ,
- .
(
),
length . ,

. alert ,
.
chapter_02/02_selecti ng/scri p t . js
$(document).ready(function() {
alert($('#celebs tr').len g th + ' elements!'):
}):
al ert ,
tabl 7.
, ,
! HTML, ,
: tabl < t>, -
46 2. ,

. ,
: ,
<tbody>.
chapter_02/03_narrow1ng_select1on/scr1pt.js
$(document).ready(function() {
alert($('#celebs tbody t r ' ) .length + ' elements!'):
}):
ale rt
, 6, j Query
.
alert 0, , .
,
.
$(' #cel ebs'),
, a al ert
, 1.
,
.

, , ,

jQuery .
, .
, ,
, ,
.
chapter_02/04_fi 1ters/scri p t.js
$(document).ready(function() {
alert($('#celebs tbody t r :even') .length + ' elements!');
}):
,
( ), ,
. :even
even- , ,
. alert
, 3, .
odd- .
jQuery, : :odd (
), : fi r s t , : 1a s t,: eq() (, ) .
.
: jQuery 47


, ,
.
,
-.
. , ,
, <div>, <hl> <input>
, :
$('p.div.hi,input')
,
-,
jQuery. jQuery,

!


, -
.
.
:
,
, id
class.
DOM
, . jQuery

DOM.
- .
,
,
jQuery!
CSS,
; CSS.
, , ,
CSS3.
, ,
,
. ,
jQuery,
1 !
1
http://api .jquery.com/category/selectors/
48 2. ,

: CSS
jQuery
jQuery .
. ,
.
jQuery, CSS:
, .
, ,
- , !

CSS-
CSS-, ,
. jQuery css,
:
ch apter_02/05_reading_css_properties/script.js
$(document).ready(function {
var fontSize = $('#celebs tbody t r : f i r s t ' ) .css('fo n t-size') :
a le rt(fo n tS iz e ):
}):
,
(
, : fi rst ,
).

CSS-

CSS- ,
:
, ,
.

CSS-
, jQuery .
, ,
, , CSS-.
, , , di v 200 CSS-
, ,
, jQuery , 200 ,
.
, ,
.
: CSS jQuery 49

CSS-
, jQuery,
. , - (
al ert), ,
, . ,
.
chapter J )2 /0 6 _ z e b ra _ strip in g /sc rip t.j s
$(document).ready(function {
$('#celebs tbody tr:e v e n '). css('background-col or \'# d d d d d d ');
}):
, , ! css,
CSS-,
: , .
background-col or
#dddddd (- ). ,
, ,
. . 2.2.

ID Name Occupation Approx. Location Price


203 jo h n y S tard u st (bio) F ro n t-m a n Los A n g e le s S 39.9S

141 Beau D an d y (pic.bio) Sin g er New Y o rk S39.95

20 3 1 Mo* Fat (pic) Pro d u cer N ew Y o rk S 19.95

007F K e llie K e lly (b io .p ress) Sin g er O m aha S11.95

805 D arth Fad e r (pic) DJ Lo n d o n $1 9.95

6636 G le n d a tro n ix (bio.oress) K e ytarist Lo n d o n $3 9.95

. 2 .2 . , ,
jQ u e ry

?

, document-ready.
, DOM,
#ce1ebs, -
. ,
t r , .
,
document-ready .

! , , - ,
! ,
, ?
50 2. ,

CSS- .
jQuery ,
.
chapter_02/07_mult1ple_propert1es_l/scr1pt. js ()
$(#celebs tbody tr:ev en ') .css('background-color', '#dddddd');
$('#celebs tbody t r :even) .css( color . #666666');
.
, ,
. , j Query
.
JavaScript,
, ,
/. CSS
CSS- ()
CSS- ().
chapter_02/08_multipie_propert1es_2/scr1pt.j s ()
$('#celebs tbody t r :even') .css(
{ ' backgroundcol o r ': '#dddddd , *col o r : #666666}
);
,
,
/ .
css. ,
/, .
/ ,
,
. ,
. .
ch ap te r_ 02 /09 jnu ltiple _ prop ertie s_ 3/script. j s ()
$('#celebs tbody t r :even') .css({
'background-color': '#dddddd'.
'color': '#666666'.
'fo n t-siz e ': ' ll p t '.
'line-height': '2.5em'
}):

?
, JavaScript
. , jQuery,
( background-color fon t-size)
camel-,
, (, backgrounds lor).
, , JavaScript (,
flo a t class), .
, , , ,
.
: CSS jQuery 51

!
, jQuery. ,
, - .

Firebug, , CSS-
(. 2.3).

( t a b le id * "celeb s* ' c la s s d a t a <,>


<tbody>
<tr>
<tr style*4background-color: rgb(221, 221, 221); >
<tr>
<tr style*background-color: rgb(221, 221, 221);*>
<tr>
^ <tr style~background-color: rgb(221, 221, 221);">
</tbody>
</tablc>____________________________________________________

. 2.3. Fireb u g

FIREBUG
Firebug ( , Google Chrome Developer Tools1)
DOM ,
CSS-, HTML- JavaScript- ( jQuery).
, -,
,
. Firebug Mozilla
Firefox1
2 JavaScript-3, ,
.

HTML/CSS,
? jQuery:

- ,
CSS-. ( )
HTML- class
.
, jQuery-
css , . ,
: -
, , ,
CSS-
.

1 https://chrom e.google.eom /webstone/category/ext/l 1-web-development


2 https://addons.m ozilla.org/en-US/firefox/addon/firebug/?src=search
3 http://getfirebug.conyfirebuglite
52 2. ,


CSS ,
? , !
CSS jQuery
HTML- . ,
j Query
cl ass DOM.
addClass
, , CSS-,
.
addCl ass ,
. ,
, HTML-:
$ ( ' di v ' ) .addClass( 'c l a s s j i a m e ');
$ ( 'd i v ' ) .addClass( classjiamel class_name2 class_name3');
zebra.
CSS- HTML:
chapter_02/10_adding_classes/index. html ()
<head>

<ti tle>StarT rackr!</ti 11e>


<1 ink re l "style sh e e t" h ref "zeb ra .css type="text/css" />

</head>
CSS-:
chapter_02/10_addi n g c l asses/zebra. css
.zebra {
background-color: #dddddd;
color: #666666;
}
, JavaScript, ,
css j Query- addClass.
chapter_02/10_addi n g c l asses/scri p t . js
$('#celebs tbody t r :even') .addClass( 'zebra');
. ,
Firebug , ,
.
, . 2.4.
.
- , CSS-
j Query- (, ,
) .
: jQuery 53

<table class*"data,>
<thead>
<tbody>
<tr class,zebra,>
ctr>
ctr class"2 ebra*>
<tr>
<tr class,,2ebra',>
^ <tr>
</tbody>
</table>
. 2.4.

,
( ).
removed ass.
, addCl ass, (
:
$(' #cel ebs t . zebra'). removed ass (' zebra');
,
.

:
jQuery
.
jQuery: , .
, :
, - ,
.


jQuery.


,
. ,
, , .
, ,
, .
ch ap te r_ 0 2 /ll_ h id in g/i ndex.html ( )
<input type="button" id="hideButton" value="hide" />
HTML-
id hideButton. ,
54 2. ,

, i d
di scl aimer .
c h a p t e r _ 0 2 / llh id in g / s c r ip t. j$ ()
$( #hideButton' ) . c l i c k ( fu n c tio n () {
$('#discl aimer') .hideO;
}):
, ,
disclaimer ,
.
,
, hide.
: ?
. , , ,
jQuery.
, (
click), .


,
. (
, ), -.
, , .
(
JavaScript-), , .
, -,
, ,
.
.
, , document -
ready. , :
, ( ), ,
jQuery.
click ,
jQuery di scl aimer, :
$(#hideButton') . click(function() {
$( 'fdisclaim er') .hideO;
}):

this
, ,
. ,
, .
,
JavaScript- this.
: jQuery 55

JavaScript jQuery,
jQuery:
chapter_02/12_this/scri p t.js ( )

$ ( '# hideButton') . c l i c k ( f u n c t i o n ( ) {
$ (th is) . h i d e O : //
}):
$(this) ,
, .

?
, jQuery ,
. ,
, , !
: .
, , . -
, ,
.


!
,
, .
HTML-,
id showButton.
chapter_02/13_reveali ng/i ndex.html ( )
<input type=,,button" id="showButton" value=,,show />

jQuery,
,
show.
chapter_02/13_revealing/script.js ( )
$ ( '#showButton') . c li c k ( f u n c t i o n () {
$( ' f d i s c l a i m e r ' J.showO :
}):




. , :
, , ,
. , , ,
56 2. ,

.
.
chapter_02 / 14_t oggl e l / i ndex. html ( )
<input type="button" id="toggleButton" value="toggle" />

,
.
chapter_02/14_toggle_l/script.js ()
$ ( #toggleButton ) . c l i c k ( f u n c t i o n ( ) {
i f ( $ ( *#disclaimer') . i s ( ' : v i s i b l e ')) {
$ ('# d is c la im e r').h id e ( );
} e ls e {
$ ( '# d isc laim e r').sh o w ();
}
}):
i s. ,
jQuery, ,
, . ,
#disclaimer : visible.
i s : ,
form di v, . .

^ 0 1 IF
^ ^ (
HTML CSS), ,
, . ,
:
i f (c o n d itio n ) {
// , co n d itio n - true
} e ls e {
// , co n d itio n - fa ls e
}
condition , JavaScript true, false.
,
. ,
. if / e l se
jQuery- is , .
, !

is true false ,
. , ,
, . ,
, toggle
.
,
jQuery- ,
57

. show/hide toggle
:
chapter_02/15_toggle_2/script.j s ()
$('#toggleButton) .click(function() {
$('#disclaimer' ) .toggle():
}):

, .


toggle,
(
if/e ls e ). !

, ,
toggle (), .
, ?
jQuery, .
.
ch apter_ 02 /16 _ toggle_text/script.j s ()
$ ( #toggleButton') . c lic k ( fu n c t io n ( ) {
$ ( '# d is c la im e r ') .to g g le ();

i f ($( ^ d is c l a i m e r ' ) . i s ( ' : v i s i b l e )) {


$(th i s ) . v a l ( ' H i d e ' );
} else {
$ ( t h i s ) . v a l ( Show );

}):
.
. ,
(: , $(thi s )
, ,
button).

disclaimer
, .
:
JavaScript, ,
58 2. ,

.
.
JavaScript? .
JavaScript?!
, , ,
JavaScript:
(
), ,
, , , JavaScript
,
.
,
, 3 % ,
JavaScript1, , , 30 000
! ,

.
.

di scl aimer, : ,
, HTML-
. JavaScript
. , ,
Show/Hide (/) ,
.
CSS ,
j Query- css.

j Query; ,
JavaScript. !


, j Query
, ,
. HTML-,
j Query,
-. , paragraph:
$ ( ' <> new paragraph!</>')

j Query
: HTML DOM
j Query.

http://cleveloper.yahoo.com/blogs/ydn/posts/2010/10/hovv-many-users-have-iavascript-disabled
59

, j Query-. ,
, , ,
:
$ ( ' <> new paragraph!</> ) .addClass( 'new');

. ,
j Query ,
HTML-. ,
-.

HTML- ( <div>)
innerHTML <di v> HTML-. ,
, , -
HTML-.

,
-.
j Query. , , i nsertAfter.
(
, ) ,
.
.
toggle j Query.
ch ap te r_ 0 2 /1 7 _ in se rt_ a fte r/scrip t.js ()
$ ('< in p u t type="button v a lu e *to g g le i d - toggleBu tton> ')
.i n se rtA fte r( ' #di s c la i mer') ;
$ ( '#toggleButton') . c l i c k ( f u n c t i o n ( ) {
$( ^ d is c l a i m e r ' ) .to ggle O ;
}):
. 2.5, -
disclaim er ,
HTML-.

Disclaimer! This service is not intended fc


people so their privacy should be respect.

^ t o g g le )

. 2.5. , JQ u e ry

i nsertAfter -
disclaimer. ,
di scl aimer,
disclaimer, in sertA fte r,
i nsertBefore, , i nsertBefore
60 2. ,

- ,
.
ch apter_02/18_insert_before/script.js ()
$ ('<input type="button" value="toggle" id="toggleButton">')
.in se rtB e fo r e ( '#disclaimer');

: DOM,
- ,
DOM. , , <div>
<span>, .
-
(
), prependTo appendTo.
chapter_02/19_prepend_append/script. j s ()
$('<strong>START!</strong>') .prependTo('fdisclaimer');
$('<strong>END!</strong>') .appendTo(^disclaimer');
. 2.6, (START!)
(END!) di v- disclaimer,
. ,
.
, .

START! Disclaimer! This service Is not Intended for the those with
criminal intent. Celebrities are kind o f like people so their privacy
should be respected. ENDI

. 2 .6 . p repen dT o ap p e n d T o


, : ,
, , in sertA fteraction
.
!

%
,
. HTML-,
,
.

:

$ ('< d iv > \ {
id : sp e cia l Bu tto n .
te x t: 'C lic k M e!',
61

c lic k : fu n ctio n (){


alert("Advanced jQ uery!")
}
} ) . in s e rtB e fo re ('# d is c la im e r'):


( <div>).
/, CSS-
. , HTML-
.
.


, 3 %
JavaScript,
,
. ,
, ,
JavaScript . ,
,
JavaScript.

<nonscript>, . ,
, ,
HTML- jQuery.
HTML- , jQuery. ,
,
J avaScript.
, HTML-
-.
chapter_02/20_removing_elements/index.html ( )
< id=,,no-script">
We recommend that you have JavaScript enabled!
</p>

.
JavaScript , jQuery
.
jQuery , ,
, remove:
chapter_02/20_removing e le m e n ts/sc rip t.j s ( )
$ ( '# n o -s c rip t' ) . remove():

remove
DOM, ,
. remove - ,
62 2. ,

, .
:
chapter_02/21jremovi ng w ithsel ector/script. js ()
$('#celebs t r ' ) .remove(' :contains("Singer")'):
tr <di v^- #cel ebs,
, Singer.
,
.
-
3 % , JavaScript,
97 % !
,
:
jQuery UI,
.
, .

, .

-.


:
, ,
... ,
- ? jQuery
: text html.
text html
.
.
chapter_02/22_modifying content/script.js ()
$(p').html('good bye. cruel paragraphs!'):
$ ( ' h2' ) . t e x t ( ' A11 your t i t l e s are belong to u s ):

, : paragraph h2
. text html ,
HTML .
diapter_02/23_text_vs_html/script.js ()
$('' ) .html ( '<strong>Warning!</strong> Text has been replaced ... '):
$('h2') .text( '<strong>Warning!</strong> Title elements can be ...'):
,
, <h2> ,
, <strong>.
: 63

, : te x t
, a html HTML.
:
?
,
j Query.
chapter_02/24_get_content/script. js ()
a le rt($ ( h 2 : f i r s t ' J . t e x t O ) :
tex t - ,
<h2> (Wei come! ).
, ,
,
.

:

,
, .
j Query, -
, .
j Query ,
-. ,
, j Query,
.


,
. , - <blink>
!



fadeln fadeOut
( ) j Query
.
, show fadeln hide fadeOut.
chapter_02/25_fade_in_out/script.j s ()
$ ( #hideButton' ) .click(function( ) {
$ ( ^ d is c l a i m e r ' ) . fadeOut0 :
}):
, .
,
64 2. ,

. j Query
, .
,
: s 1ow, fast norma 1, : fadeln (* fa s t').

, : fadeln(lOOO).


j Query fadeToggl , ,
, , . ,
toggle ,
. ,
, toggl .
chapter_02/26_toggle_fade/scri p t . js ()
$('#toggleButton') .click(function() {
$ ('#disclaimer') . toggle('slow');
}):
, ,
. ,
j Query,
, .
,
, . ,
, slideDown, slidellp
si ideToggl . ,
.
chapter_02/27_sl id e t o g g le / s c r ip t . j s ()
$ ('#toggleButton' ) .click(function() {
$ ('#disclaimer') . siideToggle('slow');
}):

callback
( )
, callback.
, ,
. callback ,
.
chapter_02/28_cal1back fu n c tio n s / s c rip t. js ()
$( fdisclaim er') . siideToggle( 'slow ', functionO {
alertCThe slide has finished sliding!')
:
65

ca llba ck
effect ,
.


JavaScript ( callback )
. ,
! , ,
.

, - . ,
.
,
.

cal 1back . ,
, d is c la im e r
, .
chapter_02/29_cal1back functions_2/script.js ( )

$( ^ d is c la im e r ) . s lid e U p ( s l o w ' . fu n ctio n O {


$ ( ' #h i deButton' ) . fadeOut():
}):
, ,
, .


, ,
,
,
.
, ,
jQuery.



,
, . ,
,
.

, mouseover mouseout.
CSS, ,
66 2. ,

.
, JavaScript.
chapter_02/30_hover_h1ghl1g h t/sc r1 p t.c ss ()
$('#celebs tbody tr').mouseover(function() {
$(thi s ) .addClass('zebraHover');
}):
$('#celebs tbody tr').mouseout(function() {
$(this).removed ass( 'zebraHover'):
}):
, $(thi s ) ,
zebraHover ,
. CSS-
.
chapter_02/30_hover_highlight/zebra.css ()
tr.zebraHover {
background-color: #FFFACD;
}
, ,
. :
jQuery hover,
mouseover mouseout.
chapter_02/31_hover_action/script.js ()
$('#celebs tbody tr').hover(function() {
$(this).addClass('zebraHover');
}, functionO {
$(this).removedass( 'zebraHover'):
}):
hover?
:
mouseover, mouseout.

CALLBACK ?
jQuery . ,
toggle .
callback. hover
: ,
mouseover, mouseout.
,
.

class,
, , ,
: toggleClass. ,
67

. , ,
- , .
, ,
.
, .
j Query.
chapter_02/32_toggle_class/scr1pt.j s ()
$('#celebs tbody tr').click(function() {
$(this).toggleClass('zebraHover');
}):
.
, ? toggl 1ass
, .
.


StarTrackrl
.

,
.
, .
:
,
, ,
.

, , , .
,
, ,
.

. ,
, span
spoi 1:
chapter_02/33_spoi 1e r r e v e a l / i ndex. html ( )
Who lost their recording contract today?
<span class=,spoiler'>The Zaxntines!</span>
, :
,
, . , ,
68 2. ,

, . ?
? cl ick? , .
chapter_02/33_spoi 1e r r e v e a l e r / s c r i p t . j s ()
$(' .sp o ile r') .hide():
$(<span class="revealer">Tell me!</span>')
. insertBefore(' .spoiler);
$ ( '.revealer' ) .click(function() {
$(this).hide():
$( thi s ). next () .fadelnO:
}):
,
, .
spoi 1 i nsertBefore
.
Tell me! (!), span .

cl i ck.
reveal ( $(thi s )),
fadeln spoiler,
, next , .
DOM
-,
( ,
).
DOM
(. 2.7), , span
reveal er. jQuery
prev, ,
, .

<>
Who lost their recording contract today?
<input class~"revealer" type-^button" value-"TeIl Me!*/>
<span classspoiler stylo<"display: none;>The Zaxntines!</span>
</p>

. 2 .7 . D O M

jQuery ,
;
prev next.
, API- jQuery1
.
, spoiler jQuery,
fadeln,
.
1
http ://docs.jquerv.com/Traversing
69


,
jQuery. ,
.
! ,
- ,
.
:
, ,
j Query ,
.
CSS HTML,
. , ,
j Query; , ,
, ,
.
j Query
,
, .
,
3
,
,
, .
, , - ,
, . , ,
- .
, ,
Web 2.0, ,
. ,
Web 2.0?
, , ,
,
. ,
, jQuery.

jQuery .

,
, ,
, ,
.

CSS-

: , ,
, ,
.
jQuery- animate,
71

CSS-
.
animate.
chapter_03/01_anim ating_css/script.js ()
$() .animate({
padding: '20\
fontSize: '
}. 2000 );

-,
20
30 2 (2000 ).
animate ,
,
/, ,
css.
: ,
, animate.
backgrounded or background-color marginLeft margin-left.
, "background-color" "margin-
1eft". , ,
.
,
, 2,

: slow, fast normal. CSS-
, (), . ,
, , 50 16pt.
,
: , , += -=
,
. ,
, ,
hover.
ch apter_ 03 /02 _ relative_ css_an im ation /script.js ()
$ ( '#navigation 1i ") .hover(function() {
$(this).animate({paddingLeft: '+=15px'}, 200):
}. functionO {
' $(this).animate({paddingLeft: ' -=15px'}, 200);
}):
, ,
.
animate
, ,
72 3. ,

2. show, hide
toggle .
chapter_03/03_animate_show_hide ()
$(^disclaim er') .animate({
opacity: 'hide',
height: hide'
}. 'slow');

.
, , !
animate ,
.

CSS-
2022 , HTML5 , , CSS3, ,
- (Living Standard1). HTML5 CSS
, .
, . ,
!
, . -
, HTML4,
10 . , - ,
. : ,
- - , jQuery

. , , -
, ,
. ,
, , HTML5
CSS, jQuery.


animate, ,
, .
,
.
, ,
, jQuery
, , , -
.
jQuery . ,
:
, jQuery -

1 http://wiki.whatwg.Org/wiki/FAQ#W hat_does_.22Living_Standard.22_m ean.3F


73

. ,
Color Animations1.


jQuery1
2
. , (
, ) ,
jQuery.
1,
. GitHub. ,
,
.

Color Animations HTML-


,
jQuery- , CSS-.

2 -, ,
:
chapter_03/04_color_animation ()
$ ( '# d is c la im e r ') .animate({ backgroundColor': # f f 9 f 5 f 1}. 2000):

- ? ,
, camel- ? ,
camel- .
, .
,
. , , ,
,
, . , ,
, .

,
,
.
.
jQuery, ,
.
BjQuery : linear () swing (
). jQuery- animate
, .

1 http://plugins.jquery.com /pnoject/color
2 http://plugins.jquery.com /
74 3. ,

. 3.1, ,
.

linear swing

. 3.1. , jQ u e ry

swing
, , .
swi ng ,
1i near, jQuery swi ng ,
.
linear
: .
,
.
,
, .
linear, swing.
, ,
. .
chapter_03/05_easing/script.j s ()
$ ( 'p :f ir s t).toggle(function() {
$(this) .animate({ 'height: '+=150px'}, 2000, 'lin e a r'):
}. functionO {
$(th is ) .animate({height: '-=150px'}, 2000. 'swing'): Q
}):
jQuery-,
, .
0 ,
. toggle (

) .
thi s, ,
( ).
+= 150
linear.
-=
150 swing.
75

, !
jQuery!


, swing
, ,
. swing linear
.
,
jQuery. Easing1,
jQuery.

JQUERY UI

Easing
jQuery UI, .
,
jQuery III.
, Color Animation,
Class Transitions Easing. jQuery UI,
- .

JavaScript-
Easing HTML- - jQuery.
30
.
,
. 3.2, .

. 3.2.

1
http://pluglns.jquery.com/project/Easing
76 3. ,

, .
,
, .
, .
,
animate. .
.
chapter_03/06_other_easing_options/script.j s ( )
$ ( ' : f i r s t ' ) .animate({height: '+=300'}. 2000, 'easeOutBounce');
$ ( :f i r s t ' ) . animate({height: ' -=300px'}, 2000, easelnOutExpo');
$ ( p :f i r s t ) . animate({h e ig h t: 'h id e '} . 2000. easeO utCirc');
$ ( p :f i r s t ) . animate({h e ig h t: 'show'}, 2000. easeO utElastic );

, ! ,

.
, -1.
, ,

jQuery UI. ,
, ,
jQuery-.
, j Query
canvas12.


,
. - ,
,
. , animate
: jQuery!


, animate,
.
-
StarTrackr! Daily Whos Hot Right Now? List (
StarTrackr! ?) ( SDWHRNL).
,
,
.

1 http://w w .robertpenner.com /easing/


2 http://jqueryui.eom/demos/effect/#easing/
77

,
.
. 3.3 , -.

Who's Hot Right Now?___________________________________

Beau D a n d y

Jo h n n y S ta rd u s t

After smashing into the limelight with a controversial run as local weather
forecaster with something to say", Johnny Stardust has gone from success to
success. His current spot as front-man of super-group P a h o o p t makes his exact
location a valuable commodity.

C le n d a tro n ix

. 3.3.

HTML- d i v,
.
di v,
.
chapter_03/07_bouncy_content_panes/index.html ()
< section id="bio">
<h2>Who's Hot Right Now?</h2>

<h3>Beau Dandy</h3>
<div>
<img src=.,/images/beau_100.jpg" width="100"
height="100" alt="Beau Dandy'7>
<p>Content about Beau Dandy</p>
</div>

<h3>Johnny Stardust</h3>
<div>
<img src=". ./images/johnny_100. jpg" width="100"
height="100 alt=Johnny Stardust"/>
<p>Content about Johnny Stardust</p>
</div>

<h3>Glendatronix</h3>
<div>
<img src=". ./iinages/glenda_100. jpg" width="100"
height="100" a11=G1endatronix/>
<p>Content about Glendatronix</p>
</di v>
</ section>
78 3. ,

, ,
,
.
,

.

# ?
: ,
, ,
. , ,
. ,
, .

-,
.
chapter_03/07_bouncy_content_panes/script.j s ()
$ ( #bio > d i v ' ) . h i d e ( ) :
, ,
.
,
, . jQuery
: : f 1rst
show , :
$ # > d i v : f i r s t ) .showO:

G CHILD
, .
ch ild , (>).
, .
child,
div, d iv - bio,
.
API- jQuery
1.

, ,
jQuery.
, ,
cl ick, (
) ,
2. ,
,
.

http://dcxs.jquery.com/SelectDrs/child
79

chapter_03/07_bouncy_content_panes/scr1pt. j s ()
$('#bio h3' ) ,c1ick(function() {
$(this).next().animate(
{'h eig h t': 'toggle'}. 'slow', 'easeOutBounce'
);
}):
easeOutBounce ,
, ,
. !


, , ,
animate. ,
:
animate(parameters. options):

,
, /.
: duration, easing complete ( cal 1back).
: step queue. , ,
animate .
chapter_03/08_animation_queue/script. js ()
$ (':fi rst *) .animate(
{
height: '+=100 .
color: green'
}.
{
duration: 's lo w ',
easing: 'sw ing ',
complete: fu n ctio n O { a le r t C d o n e !') :} ,
queue: fa ls e
}
):

, .
,
queue.
,
. , j Query- ,
.
, . , ,
, -
.
,
. ,
80 3. ,

. ,
,
.
queue,
j Query- stop, queue dequeue.
.
, ,
j Query.



, cal 1back.

this . ,
jQuery-
(-). ,
j Query, .
j Query-
.
.
hide, si ideDown fadeOut.
, :
$( ' :f i r s t ') .hide().slideDown( slow) .fadeOutO;
.
, .

DOM, ,
.

. ,
.
:
$ (':fi r s t ')
.hi de()
.slideDownC'slow')
.fadeOutO;
, j Query
, .
, ,
.
,
, , $(thi s ).
next(). animate . next
DOM, animate
, .
81


: .
j Query!


j Query,
delay.
,
. ,
:
$ ( ' :f i r s t ')
.h ide O
.slideD ow n ('slow ')
.delay(2000)
.fadeOutO;
, ,
2 . ,

.


:
,
Flash,
-, . , Flash
. , Flash
.
, , Flash-
j Query.
(blob), ,
, .
: HTML, CSS
JavaScript. Flash? Flash!
,
. CSS,
, , ,
. , HTML- ,
.
chapter_03/09_animated_navigation/index.html ( )
<ul id="navigation">
<1 i >< href="#">Home</ax/li>
<1i >< href=#">About Us</a></li>
< l i x a href="#>Buy!</ax/ii>
< l i x g href="#M>Gift Ideas</a></li>
</ul>
82 3. ,

di v,
,
. ,
.
chapter_03/09_animated_nav1gat1on/scr1pt.js ()
$ ( ' <div id=s"navigation_blob"></div>') .css({
width: 0
height: $ ( #navigation 1i :f i r s t a ') . h e ig h t( ) + 10
} ) .appendTo(^navigation');

,
.
, ,
. , (
) ,
. 10 ,
, ,
.


css() widthQ jQuery
(em, in, pt . .) .
, width, , , 30 em, a jQuery 480
.
, , ,
10 . ,
jQuery , .

,
, . ,
,
hover. , :
, , ,
, , .
.
chapter_03/09_animated_navigation/script.js ()
$( 'N a v ig a t io n ' ) .hover(function {
// , mouseover

}. fu n ctio n O {
// , mouseout

}):
.
, , .
83

chapter_03/09_ani mated_nav1gati on/scr1p t . js ()


11 , mouseover
$( '#navi gati _ ob') ,animate(
{
width: $(this).widthO + 10,
left: $(this).p o sitio n ().left
}
{
duration:slow ,
easing: easeOutCirc,
queue: false

,
:
.
- j Query-
position. , , ,
: 1eft top
.
left, , .
fal se queue ,
,
-. ,
,
.
- j Query , ,
.
, ,
, .
chapter_03/09_ani m atednavi gati on/scr i p t . j s ( )
II , mouseout
$('#navigation_blob')

{
width: $(this) .widthO + 10.
left: $(this).position().left
}.
{
duration:'slow ',
easing: 'easeOutCirc',
queue: false
})
,animate(
{
left: $( ^navigation 1i :firs t a ').p o sitio n ().left
}, 'fa s t'
):
84 3. ,

animate:
,
( ).

, jQuery.
! , width: hide
, mouseout. ? jQuery
, . ,
( , )
.

, ,
.
.

Easing, , ,
, .
, ,
.

. 2
, jQuery,
,
.
,
,
. ,
.
,
(
. 3.4).

. 3.4.

.
,
.
. ,
, ,
, .
85

CSS: ,
di v, .
, ,
.
, 20 ,
30 .
, .
.
chapter_03/10_ani mated_navigati on_2/navi gati on.css ()
#container {
position: relative;
}
Navigation {
position:absolute;
width: inherit;
top: 0;
right: 0;
margin: 0;

Navigation li {
height:20px;
flo a t:le ft;
list-style-type: none;
width:70px;
padding:3px;
border-right:lpx solid #3687AF;
background-color: #015287;
background-repeat: no-repeat;
background-position: center 30px;

#navigation li a {
color: #FFFFFF;

#navigation #home {
background-image:url( 'homejcon.png');
}

, ,
, stop
mouseover mouseout. (),
,
, .
duration easing .
86 3. ,

- ,
.
chapter_03/ lO animated n a viga ti o n _ 2 /sc rip t. j s ()

$('#navigation l i ).hover(function() {
$(this)
.stop(true)
.animate(
{height: '60px'}.
{duration: 500, easing: 'easeOutBounce'}
)
}
fu n c tio n O {
$(th i s )
.stop(true)
.animate(
{ h e ig h t:' 20px'},
{duration: 500, easing: 'ea se O u tCirc'}
)
}
);
, ,
!


jQuery UI
1, jQuery UI
,
, datepicker (), accordion (
) drag and drop (),
-. ,
,
jQuery UI. ,
jQuery ,
. ,
jQuery UI, , , 1.8.17, 367
( 196 ). ! ,

,
jQuery UI, -, jQuery,
, ,
.
1,
, Build custom download (
1
http://jqueryui.oom/download
87

) -
jQuery UI, , ,
.
: Core (
), Interaction (), Widgets (), Effects ()
Themes ().
j Query UI,
Interaction () Widgets ().

, . -
,
.
,
. , -
, .
-,
,
. ,
, .
,
, .
. 9
, .
,
.
, ,
. devel opment -bund1
, .
,
j Query UI, jQuery-ui -1.8.17-mi n. js
( ),
, .
,
HTML-. , ,
j Query UI lib
( jQuery), css.
jQuery UI
Effects,
.
.
Color Animation
Easing. Effects,
,
jQuery UI.
, .
,
88 3. ,

,
.
chapter_03/ll_jquery_ui effects/scrip t.js ()
$( 'p : f i r s t ')
.effect( 'shake'. {times:3}. 300)
.effect( 'h ig h lig h t'. {}. 3000)
.hide('explode'. {}, 1000);
, ! ,
.
effect, ,
hi de, show toggl .
, blind, clip, puff, fold slide.
,
. ,
, highlight,
,
.
,
, .
,
j Query UI, ,

!

!
j Query:
, , cal 1back, ,
animate.
j Query .
.
, .
, ,
.

j Query, ,
: , ,
.
j Query- ,
. ?

,
-. , ,
!
89

. , ,
,
,
.

scroll
,
, .
scroll, , -
- , di v.
, ,
, '
.
scroll
, ,
. JavaScript, ,
, jQuery ,
.
, scrol 1 ,
!
, ,
scrol 1
overf 1ow: scrol 1; di v -.
chapter_03/12_scroll_event/scroll.css ()
#news {
height: ;
width: ;
overflow: scroll:
}

-. scrol 1
,
scrol 1.
()
chapter_03/12_scrol1 event/scri p t. js
$('#news') .scroll(function {
$(#header')
.append(<span class=Mscrolled">You scrolled!</span>');
}):
, ,
You Scrolled! (
!). , .
:
,
.
scroll.
90 3. ,


, .
-?
-
. ,

. ,
, -
. scrol 1.
CSS
. height
,
(, , !).
chapter_03/13_floating_nav_l/scroll .css ( )
#navigation {
position: relative:
}
#content {
height: 2000px;
}
. ,
. scroll
top ,
.
chapter_03/13_f1o a tin g _ n a v _ l/sc rip t.j s ( )
$(window).scroll(function () {
$( 'Navigation' ).css( to p '. $(document). scroll TopO);
}):
-, , :

. , ?
scrol .

: $(document).scrol ITopO.
.
, , , .
, scrol 1? ,
, scroll.
,
, ,
.
,
. ,
. ,
91

position: relative top


scrol 1, .
, . , -
? , .
chapter_03/14_f1o atin g_ n av_ 2 /scrip t. j s ()
var Swindow = S(window),
Snavigation = $("#navigation");
Swindow.scrolKfunctionO {
if ( !$navigation.hasdass("fixed") && (Swindow. scroll Top >
^Snavigation.offsetO.top)) {
Snavigation.addClass(" fi xed") .data("top".
^Snavigati on.offset(). top);

data top
. ,
, , , ,
. 13_floating_nav_l/script. js,
,
. .
ch apter_ 03 /14 _ flo atin g_ nav_2 /scrip tJs ()
Swindow.scrol 1(functionO {
if (! Snavigation. hasCl ass ("fixed") && (Swindow.scrollTopO >
^Snavigation.offsetO .top)) {
Snavigation.addClass("fi xed") .data("top".
^Sna vi gati on. offset (). top);
}
else if (Snavigation. hasCl ass ("fixed") && (Swindow.scrollTopO
Snavigation.dataC'top"))) {
Snavigation.removed ass("fi xed");
}
}):
, f i xed
, .
data.
, f i xed .


, (
) HTML-,
, ,
-.

, .
, ,
92 3. ,

.
-.

.
href #.
, , ,
, s c r o llT o p jQuery.

, .
JavaScript, :
, c l i c k ,
( ), preventDefault
:
$( 1a [href#] ') . click(function() {
$ ( h tm l' ) .animate({scrollTop: 0 } . 'slo w ');
return false : // fa ls e .
}
a ttrib u te .
([]),
, .
href #.
, , ,
.
(qui rks mode), $(' html ) . (
, ? - SitePoint CSS1,
.)
, ,
, ,
.
, $(' body ').
: $( 'h tm l. body' ). , ,
Opera, ( ,
) .
, jQuery --
! . , jQuery
.
, jQuery . ,
. , -
,
( ,
), ScrollTo.
ScrollTo,
12, -

1 http://reference.sitepdnt.com/css/doctypesniffing
2 http://plugins.jquery.com/projed/Sadno
93

, , .
,
.
,

.
chapter_03/15_page_scrol1/script. js ( )

$ ('a[href*#]*) .click(function(e) {
$.scrollTo(0.'slow');
e.preventDefaultO;
}):
,
scrol 1 ]Query.
ScrollTo , ,
, .
,
,
, : $( 'div#scrolly') .scroll(0. 'slow ').
ScrollTo

. ( +=50),
(
), , -,
max,
. ,
, .

ScrollTo1.


,
,
. , , ,
? , .
-
,

div.
, ,
.
,
.

1 http://flesler.blogspot.com/2007/10/jqueryscrolltD.html
94 3. ,

, .
, ,

.
,

.
. ,
!
:

, , ,
, ,
j Scroll Pane.
jScrollPane j Query,

, .
,
Google Code1.
: JavaScript-
jquery. jscrol 1pane .mi n. js, CSS- jquery.
jscrol 1pane.css. CSS-

. , ,
,
. :
,
(. 3.5).

Fine Print
labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation uilamco laboris
nisi ut aiiquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voiuptate veitt
esse cillum dolore eu fuglat nulla pariatur. Excepteur stnt occaecat cupidatat non proident, sunt in

. 3.5.


jScrollPane.
, ,
.

jScrollPane12.
, .

1 http://code.google.eom/p/jscrollpane/
2 http://jscrollpane.kelvinluck.com/
95

chapter_03/16_custom_scrollbar/script.js ()
$('#fine_print') . jScrol1Pane({
verticalGutter: 20
}):
,
, , .
j Query ,
, .
, 1,
jScrollPane. ,
, Mousewheel
- (jquery.mousewheel. js), jScrollPane
, ,
, , !


,
. , ,
(
-). ,
, .
j Query
, , ( jQuery UI)

. , !

resize
resi ze j Query,
. ,
, ,
, , ,
.
chapter_03/17_resize_event/script. js ()
$(window).resize(function() {
alert("You resized the window!");
}):
i ndex. html
.
. ,
,
, .

1 http://plugins.jqueiy.coirVproject/m ousew heel


96 3. ,


CSS, ,
, .
,
,
,
, .
StarTrackr!
:
resize.
, . - StarTrackr!, ,
650 . ,

850 .
chapter_03/18_layoutswitcher/wide.css
body #container {
width: 850px;
}
body C o n t a in e r p {
width: 650px:
}
body #header {
background-image: u r l ./css/images/header-corners-wide.png');
}
body #celebs table {
width: 650px;
m argin -le ft: 5px:
}
,
body . ,
,
,
.
j Query-
. , , ,
body 900 , head,
, .
chapter_03/18Jayout_switcher/script. js ()
i f ( $ ( 'b o d y ') .w idthO > 900) {
$('<1ink rel="stylesheet" href="wide.css" type="text/css" />')
.appendTo('head'):
} e lse {
$('1i nk[href=wi de.css] ' ) . removeC);
}
97

.
: ,
, , .

. !
. ,
, 900
. ,

1000 . ,
. ,
() .

, , ,
,
, ,
, JavaScript ( ,
jQuery) .
,
.
chapter 03/1 8 1 a y o u ts w it c h e r /s c r ip t.j s ()
$(document).ready(function() {
sty le sh e e tT o g gle O ;
$(window).re siz e (sty le sh e e tT o g g le );
}):
function style sh e e tT o ggle O {
i f ($ ('body') .widthO > 900) {
$ ( <link rel="stylesheet" href="wide.css" type="text/css" />')
.appendTo('head'):
} else {
$( 4ink[href= "w ide.cssT ) .remove ;
}
}
stylesheetToggle :
, ,
. ,
resi ze,
. , ,
function, .

,
setTimeoutC ), .
,
.
, ,
.
98 3. ,

,
j Query
Resizable, ,
.

. , (
).
j Query ,
.
j Query UI,
.
,
Resizable, , , UI Core, ,
, , .
Resizable .
, ,
resizable.
chapter_03/19_resizable_elem ents/script. js ()
JC p'J.resizableO ;
StarTrackr!,
: paragraph
!
: -
. Resizable
.
jQuery UI,
.
. 3.6.

Welcome!

Lorem ipsum dolor sit amet, consectetur adipisidng ellt, sed do


elusm od tem por Inctdtdunt ut labore et dolore magna allqua. Ut
enlm ad minim venfam, quls nostrud exerdtatlon ullamco laboiis nisi
ut allqulp ex ea com m odo consequat. Duls aute Irure dolor In
reprehendedt In voluptate vellt esse d llum dolore eu fuglat nulla
pariatur. Excepteur sint occaecat cupldatat non proident, sunt In A

D isclaim er Not u n d e r .... A

. .. ,

,
: textarea.
99

textarea,


.
j Query ,
,
.
HTML- ,
. ,
. ,
, ,
, ,
. , , , ,
.
Resizable
j Query UI.
chapter_ 03 /20 _ re sizable _te xtare a/script.js ( )
$ ('textarea' ) . resi zable({
grid : [20. 20].
minWidth : 153.
minHeight : 30.
maxHeight : 220.
containment: 'parent'
}):
textarea
, paragraph, .
. 3.7. ,
Resizable.
,

jQuery U I1.

Leave a comment

name:

;Satisfied custom er

comment:
N esd m o re ro o m to w rits ? Ju st a tre tch y o u r s e lf
OM l

. 3.7. textarea,

1
http://jqueryui .com/demos/resizable/
100 3. ,

,
, mi nHeight, mi nWidth maxHei ght. ,
maxWidth,
containment: ,
, .
jQuery parent
,
.
, gri d,
.
,
. grid
: .
handles.
, , ,
,
. : n, , s, w, ne,
se, sw, nw al 1. , .
, { handles : V , se'}
.
-
, .



,
, ,
, .
,
, ,
. ,
. , .
,
- ,
; ,
.
,
- (Rich Internet Applications, RIA)
.
Resizable , Table of Contents
() , a Terms and Conditions (
), StarTrackr!, . . 3.8
, .
101

Terms & Conditions


1. Your Privacy
2. &
3. Ownership & Intellectual Property
U s e r G e n e ra te d M a t e r ia l

This website contains messaging systems and


0
i. liability
other user generated content toward the purpose
ii. Exclusive & Non-excluslve rights
and fulfillment of directory or indirectly contacting
HE User Generated Materia!
or stalking celebrities and/or their family and/or
people in their vaguely related social sphere. Such N
content is here forth and eternally regarded as
n r n n o r t v rf r n m n s n w o f

. 3.8.

,
.
5.
div,
, .
Table of Contents () . ,
, ,
.
chapter_03/21_horizontal_pane_splitter/index.html ()
<div id=,,s p lit t e r " >
<div class="pane" id="tocPane">
<div class="inner">

</div>
</div>
<div c la s s =,,pane" id="contentPane">
<div class=,,inner">

</div>
</div>
</div>
spl i t t e r . css.
, - di v ,
50 % .
, , ,
50:50. CSS-,
, .
chapter_03/21_horizontal_pane_splitter/splitter.css
# s p li t t e r {
height: 150px;
margin-top: 30px;
margin-bottom: 50px;
}
I s p l i t t e r .pane {
102 3. ,

width: 50$;
height: 100$:
float: le ft:

#splitter h2 {
margin-bottom: 0;
padding-bottom: 0:
}
#tocPane {
overflow: hidden;
background: #d6dde5 u r l( . ./images/handle.png) no-repeat
b r i g h t center;
}
#tocPane .inner {
width: ;
}
#contentPane {
overflow: auto;
}
#contentPane .inner {
padding: 0 5px;

jQuery-.

,
div.
resizable,
, :
, ,
, , ,
, .
,
( )
, resi ze
. , ,
:
c h a p te r_ 0 3 /2 1 _ h o r iz o n ta lp a n e sp litte r /s c rip t.j s ( )
$(#splitter > d iv :f ir s t') .resizable({
handles: ' e \
minWidth: '100'.
maxWidth: '400'.
resize: functionO {

var remainingSpace = $ (th is ).p a re n t().w id th () -


ta*$(this).outerW idth();
var divTwo = $ (th is ) .n e x t ( ) :
var divTwoWidth = remainingSpace - (divTwo.outerWidthO -
^ d iv T w o . w id t h O ) ;
divTwo.css( ' w i d t h ' , divTwoWidth + ' px'):

}):

.
, . -
( ) outerWidth
di v. outerWidth
, ( ,
true). ,
outerHeight.
, ,
.
: di v ,
. , outerWidth
,
.
, ,
outerWidth
. remai ni ngSpace,
di v
.

JAVASCRIPT
var remainingSpace * $(t h i s ) .parentC) .widthO $(t h i s ) .outerWidthO:
remainingSpace.
remainingSpace , .

(var divTwo = $(thi s ). next ():)


, ,
j Q u e r y (divTwo).
jQuery.


, .
:
JavaScript , .

,
, , :
( ),
, .
104 3. ,

, , ,
, .
ch ap te r_ 0 3 /2 2 _ ve rtical_ p an e _ sp litte r/scrip t.js ()
$ ( ' # s p li t t e r > d i v :f i r s t ' ) .resiza ble({
handles: ' s ' .
minHeight: '5 0 '.
maxHeight: '200'.
resize: fu n c tio n O {
var remainingSpace = $(this) .parent( ) .height() -
ta*$(this).outerHeight();
var divTwo = $ (th is ) .nextO ;
var divTwoHeight = remainingSpace -
fc*(divTwo.outerHeight() - divTwo.heightO);
divTwo.css( 'h e ig h t '. divTwoHeight + 'p x '):
}
}):
,
.
, ,
,
j Query-
Splitter.


.
! ,
, ,
,
.
j Query .
,
, .
,
. ,
.

4 -
, . , ,
.
: - ,
,
.
: ... , -,
! ?
!
( , )
. ,
,
, ,
. jQuery,
.
, , jQuery
,
,
JavaScript.

Web 2.0, ,
Web 2.0 -
, .
-
.
, , .
(,
Close ()), -.

()
,
: , ,
Ajax. ,
106 4. -

,
. ,
.
? ,
-
, .
, .
: ,
class lightbox,
, .
,
, .
. 4.1.

^ i *

. 4.1 . -

HTML-. ,
, class lightbox,
j Query-:
chapter_04/01 1 i ghtbox/i ndex.html ( )
< href=". . / . . /images/johnny_400. jpg" class=,,lightbox">pic</a>
, .
? -
div, ,
107

. div,
.
: 100 %
, .
. posi ti on
fixed, div , ,
, .
.
, .
,
.
chapter_04/01_1i ghtbox/1i ghtbox.css
#lightbox_overlay {
position:fixed:
top:0;
1e f t :0;
height:100^:
width:100^:
background:black u rl(loader.gif) no-repeat scroll center center:
}
#lightbox {
position:fixed:

click -.
.
overlay, .
, ,
, ,
Next () Previous ().
chapter_04/01_lightbox/script.js ()
$('a.lightbox') .click(function(e) {
// !
$ ('body) .css( 'overflow-y'. 'hidden');
$('<div id="overlay"></div>')
.css( 'to p '. S(document) .scrollTopO)
.css('opacity'. '0 ')
.animate({'opacity': '0.5'}, 'slow')
.appendTo('body'):
$(<div id="lightbox"></div>')
.hideO
.appendTo('body');

$('<img>')
.a t t r ( 's r c '. $ (th is).a ttr('h re f'))
.load(function() {
positionLightboxImage();
108 4. -

})
.c l i (fu n cti () {
removeLightboxO;
})
.appendTo(#1i ghtbox );

return fa ls e ;
}):

50 %
. - ,
. , sc
(
href ). j Query- attr,

DOM.
(, $( this) attr( 'href' )),
. (, $( <img>). attr (' src'. ' / images/
rockstar. jpg'), .
.
load.
ready, , (
) 100 %.


2,
DOM. :
( )
, JavaScript-, ,
.
:
$('<img>\ {
src: $(t h i s ) , a t t r ( ' h r e f ').
load: f u n c tio n O {
positionLig htb oxImageO;
}.
. c l i c k : fu n c tio n O {
removeLightboxO: }
}).appendTo('#1ig h tb ox );
, ,
. jQuery -
. ,
( load click).
jQuery text, html val, jQuery.
, scr.
jQuery, ,
. Ja va S a ipt-,
.
109

return false;
HTML- .
- .
positionLightbox.
chapter_04/01_lightbox/script.js ()
function positionLightboxImageO {
var top = ($(window) .heightO - $('#1 ightbox) .heightO) / 2;
var le ft = ($(window) .widthO - $('#1 ightbox').width()) / 2;
$('#1ightbox')
.css({
'top': top + $(document).scrollTop(),
'l e f t ': left
})
.fadelnO ;

,
positionLightboxImage. .
,
,
2.
.
, ,
.
, ,
.
chapter_04/01_lightbox/script.js ( )
function removeLightboxO {
$('#overlay, #1ightbox')
.fadeOut('slow', functionO {
$(this).remove();
$('body') .css('overflow-y'. 'auto'); // !
}):

, , ,
, , ,
. , , ,
.
,
!


console.log

( ,
), , , ,
110 4. -

, . , -
, . ,

.

a le r t . , ,
top, a l e r t (to p ) ;.
,
, . ,
, , , ,
.
, - ,
Firebug
Firefox ( 2)
,
. Firebug ,

console, log.
chapter_04/01_lightbox/script.js ()
c o n s o l e . lo g ( t o p . l e f t ) ;

Console () Firebug (
), .
!
,
. , console. 1-
, . 4.2:
, , ,
) Query.

IS C o n s o le HTM L CSS Script DOM Net

The calculated position is:


-53.5 440
A jQuery selection:
[ div#liohtbox 3

/html/body/div(3)

. 4.2. C o n so le () Firebug

JavaScript-,
.
DOM j Query-,
DOM-
Firebug. , -
111

! console.log
.


console.log .
, , console.warn
, a console.error
. , -
!

ColorBox: -

, ,
. - . jQuery
;
- .
,
, - , ,
-... -
.

- .
Shadowbox1, FancyBox12 Lightbox23,
, .
ColorBox4,
. -
. ,

. ColorBox HTML,
CSS
, , -
-
10 !
ColorBox -
. Col ,
. ,
,
ColorBox (
!).

1 http://www.shadowbox-js.corry
2 http://fancybox.net/
3 http://www.huddletDgettr.(^m/projecbs/lightbox2/
4 http://colorpowered.com/colorbox/
112 4. -

.
JavaScript-,

.
, CSS- ( ),
,
.
CSS-,
CSS-
HTML-.
chapter_04/02_colorbox_plugi/index.html ()
<link rel="stylesheet" href="colorbox.css" type="text/css">
< script src="jquery.colorbox-m in.js" ty pe = "te xt/ja v a s c rip tM>
fc*</script>

ColorBox ,
,
-,
, . 4.3. ,
, .
,
. ,
! .

. 4.3. ,
C o lo rB o x
113

rel="celeb" ,
. j Query-
a t t r ib u t e : a[rel="celeb"]. colorbox

.
chapter_04/02_col orboxpl ugi n/scr i p t. js ( )
S(document). ready(functionO {
$ ( a [r e l= "c e le b "]') . c o lo r b o x O ;
}):


,
ColorBox -
rel:
$ ( " . c e le b " ) . c o lo r b o x ( { r e l: ' c e l e b ' });

,
, .

( speed, ,
).
StarTrackr!, .
: ,
ColorBox, ,
.
chapter_04/02_colorbox_plugi n /scrip t.js ()
$ ( a[ re l= c e le b] ) . colorbox({
t r a n s it io n : ' f a d e ' .
speed: 500,
current: "{current} o f {total} c e le b r it y photos"
}):
ColorBox ,
: ,
cal 1back ,
. ColorBox
, ,
- .
, ColorBox GitHub1.
, , ,
. ColorBox MIT12,

.

1 http://github.com/jadmioore/colorbox/
2 http://creativecommons.org/licenses/Mn7
114 4. -

Jcrop

-, Jcrop1,
.


.
,
.

, , , ,
. , : Jcrop
,
, .
, , ,
. ,
Jcrop, . 4.4.

. 4.4. Jc ro p

, Jcrop,
,
( , ),
Jcrop.
, ,
1 http://deepllquid.com/content/Jcrop.htiTil
Jcrop 115


.
Jcrop,
.
JavaScript- Jcrop, CSS-,
GIF (
), ,
Jcrop.
CSS- ( -) JavaScript-
( ). Jcrop .gif
, CSS-.
chapter_04/03__jcrop/index.html ()
<link rel-"stylesheet" href="css/jquery.Jcrop.css" type="text/css">
<script src="jquery.Jcrop.min.js" type-"text/javascript"></script>
,
, -.
,
j Query. , ,
, ,
.
chapter_04/03_jcrop/i ndex.html ()
<div id="crop">
<img id="mofat" src=". ./. ./images/mofat_400.jpg" -"^/>
<input type="button" value=,,crop"/>
</div>

j Query . -
, ,
, .
$ ('#mofat'). JcropO ;
Jcrop ,
,
. ,
.
,
,
:
var jcrop = $('#mofat).Jcrop({
setSelect: [10.10.300.350].
minSize:[50.50].
onChange: function(coords) {
//

116 4. -

onSelect: function(coords) {
//

}):
. setSelect
.
[xl. yl. 2, 2]. mi nSize ,
.
, onChange onSel ect.
onChange ,
.
onSel ect , ,
.
,
, , 2, 2, w h. , coords ,w
.
Jcrop
, ,
. , , ,
,
, !
, ,
.
.
Jcrop jQuery, ,
j Query.
.
, Jcrop $.
Jcrop,
(
). ,
, .
chapter_04/03_jcrop/script. js ()
var jcrop = $.Jcrop('#mofat.{
setSelect: [10.10.300.350].
minSize:[50.50]
}):
$('#crop :button' ) . click(function() {
var selection = jcrop.tellSelectO :
a le rt( 'selected size: ' + selectio n s + 'x' + selection.h);
})
tell Select
; , ,
!
- 117


, .
Jcrop
,
,
, .

-
StarTrackr!

.
-.
. j Query,
, -
. ,

.
,
.
jQuery!

-

, , ,
, ,
( ).
-,
. ,
, PowerPoint.
,
, ,
,
.
,
, .

, ,
, ,
. ,
, ,
118 4. -


. , ,
.

span ( ). ,
,
,
.
.
.
chapter_04/04_rolloverfade/index.htm l ()
<span id="fader">
<img s r c = " .. / . . /images/glenda_200.jpg"
fc*al t="Gl endatroni x" />
<img class=Mto" src= ". . / . ./images/fader_200.jpg"
ta*alt="Darth Fader"/>
</span>

, ,
po s itio n display.
chapter_04/04_rol1o v e r f a d e / s t y le .css ( )
#fader {
position : r e la t iv e ;

#fader .to {
display: none:
p osition : absolute;
l e f t : 0;

hover.
, ,
:eq ( equals ()),
,
. 0 , 1 ,
.
, .
chapter_04/04_rol1over_fade/script. js ()
$(#fader' ) . hover(function() {
$(th is ) . find( img:eq(1) ) .stop(true.true) .fadelnO;
}, functionO {
$(this) .find(' img:eq( 1)') .fadeOutO ;
})
,
stop. ,
- 119

!
: clearQueue gotoEnd. clearQueue true,
.
gotoEnd , , j Query- ,
,
. gotoEnd
true. , ,

, , ,
( ,
- ,
, ).
,

.


, :eq.
:
. f i r s t :last, .eq, .las t . f i r s t ,
ch ild (>) class. jQuery
,
.

, ,
, ! ,
, ,
:hover CSS.
- ,
, JavaScript.

JavaScript
, .
-, ,

, .
, .
, -

. -, :
, ,
.
, jQuery
, JavaScript:
JavaScript ,
. : setTimeout set In terval.
120 4. -


, ,
, .
,
requestAnimationFrame, , -
. ,
, 1.

:
, ,
. :
setTimeout(<code to run>, <number of m illiseconds to wait>);
setlnterval(<code to run>, <number of m illiseconds to wait>);

, setTimeout
, ,
. s e tln te rv a l , ,
(
).
- , ,
. , ,
j Query ,
!
, - ,
,

jQuery 6.
,
- , !


, :
.
, jQuery- animate
, ,
JavaScript.
div CSS- l e f t .
.
chapter_04/05_timers/.index.html ()
<di v>
<div id="green" class="box">Go!</div>
<div id="red" class="box">Go!</div>
</div>

http://paulirish.com/2011/requestanimationfrcime-fbr-smart-animating
- 121

. , .
set Interval, ,
.
chapter_04/05_timers/script.js ()
var Sgreen = $('#green');
greenLeft = Sgreen. o ff set 0 .1 eft;
setIn terval(fun ction() {
Sgreen.css( ' l e f t ' . ++greenl_eft);
}. 200) ;
div : 200
.
. :
(, 50 )
DOM,
. - ,
, ,
, . ,
, ,
, .
set Interval
setTimeout, .
chapter_04/05_ti mers/ i ndex.html ( )
var Sred = $ (#red').
redLeft = $('# red'). o ffse t 0 .1 eft;
function moveRedO {
Sred.css( ' l e f t ' . ++redl_eft);
setTimeout(moveRed, 200);
}
moveRedO;
moveRed, setTimeout,
... moveRed! setTimeout
, moveRed . - ,
moveRed , ,
, set Interval.


( ),
. ,
JavaScript cle arln te rva l clearTimeout:
cl earInterval(<timer id>);
clearTimeout(<timer id>);

. , ?
, .
122 4. -

, ,
:
var animationTimer = setlnterval(animate, 100);

:
cl earInterval(animationTimer);
, setTi meout set I nterva 1! He ,
:
,
.

-

:
, .
,
, .
, , ,
- ,
.
j Query,

, .
, ,
.
, -
, .
, ,
. ,
.
- ,
di v. ,
show.
chapter_04/06_slideshowfade/index.html ()
<div id="photos">
<img alt="Glendatronix" class="show"
^ s r c = " . ./. ./images/glenda_200.jpg" />
<img alt="Darth Fader" src=".. / . ./images/fader_200.jpg" />
<img alt="Beau Dandy" src=".. / . ./images/beau_200.jpg" />
<img alt="Johnny Stardust" src=".. / . ./images/johnny_200.jpg" />
<img alt="Mo' Fat" src=".. / . ./images/mofat_200.jpg" />
</div>
. show
: CSS
- 123

, ,
. va current Image = 1
, cl ass .
JavaScript,
. ,
3 .
chapter_04/06_slideshow fade/script. js ( )

$(document).ready(function {
slideShowO;
}):
function slideShowO {
var current = $('#photos .show');
var next = cur rent, next 0 . length ? current .next () :
^ -c u rre n t.sibl ings(). fi r s t( );

c u rre n t.h id e O .removeClass( 'show');


n e x t .fa d e ln () . addClass( 'show');

setTimeout(slideShow, 3000);
}
, show,
, . ,
, .
- , . ,
, - .


,
. JavaScript ( )
.
.
? b ; , true, ,
. ,
,
- . ,
i f / else,
, .
,
var next * c u rre n t.n e x t( ) .length ? c u rre n t.n e x t( ) :
^ current. s ib li n g s 0 . f i r s t O ;
: -
-, (
next ), . next
( length 0,
false), - (
-).
124 4. -


.
show ,
, slideShow,
, 3 .


,
, .
, :
, , ,
.
j Query- ,
.
1. , ,
, z-i ndex.
2. ,
.
3. ,
z-i ndex ,
.
4. 2 3.
,
, , .
,
.
, ,
div, ,
HTML- .

Z-INDEX
- index CSS-,
. z -i ndex
, .

, .

, , 1 2
. , .
chapter_04/07_slideshowcrossfade/index.html ( )
<div id="photos">
<img alt="Glendatronix" src=". . / . ./images/glenda_200.jpg" />
<img alt=MDarth Fader src=". . / . ./images/fader_200.jpg" />
- 125

<img alt="Beau Dandy" src=".. / . ,/images/beau_200.jpg" />


<img alt="Johnny Stardust" src=".. / . ./images7johnny_200.jpg" />
<img alt="Mo' Fat" src=". . / . . / images/mofat_200.jpg />
</div>

.
chapter_04/07_sl i d e s h o w c r o s s fa d e / s ty le .css ( )
#photos img {
position: absolute;
}
#photos {
width: 180px;
height: 180px;
overflow: hidden:
}
, ,
. 4 (
)
, .
,
, $(document). ready.
c h a p te r_ 0 4 /0 7 _ slid e sh o w c ro ssfa d e /sc rip t. j s ()
$(document).ready(function {
rotateP ics(l):
}
rotatePics, .
,
. , ,
. ,
, ,
j Query .
chapter_04/07_slideshow cro ss fa d e / s c r ip t.j s ()
function rotatePics(currentPhoto) {
var numberOfPhotos = $('#photos img') . length;
currentPhoto = currentPhoto % numberOfPhotos;

}
JavaScript-,
, .
, currentPhoto ,
, ,
, .
126 4. -

, JavaScript %,
. , ,
, 6, 6 X 5 = 1.
,
, , ,
!

. ,
.
.
j Query- eq.
currentPhoto .
, ,
, cal 1back,
.
chapter_04/07_slideshow _cross_fade/script.j s ()
$('#photos img').eq(currentPhoto).fadeOut(function() {
// z-index
$(#photos img') .each(function(i) {
$(this).css(
'zlndex', ((numberOfPhotos - i) + currentPhoto) %
^numberOfPhotos
);
}):
$(this).show();
setTimeout(function() {rotatePics(++currentPhoto);}, 4000);
}):
.
.

.
, z-index
1. , Firebug
,
z-index ,
.
,
, .
, ,
: $(this) .showO.
setTimeout ,
4000 .
, ++currentPhoto.
, , ,
, :
- 127

fu n c tio n {
currentPhoto += 1;
ro ta te P ics (cu rre n tP h o to );
}
,
.


JavaScript, - ++ ,
1.
-* +*, .
++ ++ , .
, ( ++ -- )
, . -
, .

, ++currentPhoto.

;
, si i dellp
-
jQuery UI.



, ,
.
- (
),
.

-
jQuery, ,
.

. , -,
, .
( ) , ,
, .
, ,
, .
!

,
-, ,
.
128 4. -

InnerFade
InnerFade (http://medienfreunde.com/lab/innerfade/)
,
,
( ).
, . ,
,
. , ,
(. jQuery
? 1, , ).
, ,
: ,
class .
,
,
j Query I
, InnerFade ,
, ,
.


,
. InnerFade -.
Git1(
jq u e ry . i nnerf ade. mi n . js,
, ).
, .
chapter_04/08_i nnerfade/i ndex.html ( )
<script ty pe = "te x t/ja v a s c rip t src="jquery.innerfade.js"></script>
- ,
. InnerFade
, , , .
,
.
chapter_04/08_i nner fad e /i ndex.html ( )
<div id="news">
<h2>News</h2>
<ul>
<1 i><a href="#">Barron Von Jovi spotted ... </a></li>
<1 i><a href=#>MoTat signs up-and-coming rapper ... </a></li>
<1 i><a href=#">Glendatronix rumored-to be ... </a></li>
<1 i><a href="#>Man claims to be Darth Fader s son ... </a></li>
</ul >
</div>

1 https://github.com/wesbaker/jquery.innerFade
- 129

( ),
i nnef ade, InnerFade.
, .
,
, . -
, ,
.
chapter_04/08_innerfade/script. js ()
$('#news u l' ) .innerfade({
animationtype: 's lid e '.
speed: 750.
timeout: 3000,
type: 'random'
}):

. InnerFade
, ,
. InnerFade ,
, JavaScript
(
CSS , ).
, ,
,
j Query.

Cycle
Cycle1
, ,
( ,
). ,
( ,
50 ),
,
.
: Cycle
JavaScript-
-.
: ,
( jquery.cycle.all .min. js), ,
( jquery. cycl . 1i t e .mi n. js, 7,5 , ).

.
, ,
-. Cycle
1
http://malsup.com/jquery/cycle/
130 4. -

,
.
.
chapter_04/09_cycle_plug1n/script. js ()
$('#photos') .cycle({
fx: 'shuffle'
}):
. 4.5.

. 4.5. shuffle, C ycle

20 ,
: s h u ffle , fade, zoom, wipe, toss, curtainX, growY... . ,
,
.
, Cycle, , , ,
, .
.
chapter_04/ 10_cycl e_pl ugi n_2/scri p t. js ()
$ ( '#photos ) .cycle({
fx: ' s c r o l l Down',
speedln: 2500,
speedOut: 500,
timeout: 0,
next: '#photos'
}):
timeout ,
, ? .
next ,
-.
- 131

-,
.
, speedln speedOut
, :
,
, .
, .
, ,
, ,
,
.

-
Cycle,

.
-.

- , . ,
,
.


, ,
.
, ,
.

. , .
, ,
.
,
. .
chapterJ)4/ll_thumbnai 1_scrol 1e r/ i ndex. html ()
<div id="photos">
<div idss"photos_inner">
<img alt="Glendatronix" src=". . / . ./images/glenda_100.jpg" />
<img alt="Darth Fader" src=". . / . ./images/fader_100.jpg" />

<img alt="Beau Dandy" src=".. / . ./images/beau_100.jpg" />


</div>
</div>
,
overf 1ow: hi dden. ,
132 4. -

, 15
.
chapter_04/ll_thumbnai1 s c r o l1/ s t y l .css ( )
#photos {
overflow: hidden:
width: 600px;
}
#photos_inner {
height: ;
width: 1500px:
overflow: hidden;
position: relative;

#photos_inner img {
float: left;
width: ;
height: ;

, ,
.
chapter_04/1I t humbnai 1 scrol 1er/scri p t. js ()
$ ('#photos_inner') .toggle(functionC) {
var scrollAmount = $(this).widthO - $(this).parent().width();
$(this).anim ate({'left':'- = ' +scrol1Amount}. slow1);
}. functionO {
$(th is ) .anim ate({'left':'0 '} . 'slow ');
}):
,
. ,
, ,
. parent
(. HTML,
1). ,
,
.

.
,
. ,
, , ,
. , ,
.
. ,
.
- 133

chapter_04/12_thum bnail_scroller_im proved/script.js ()


$ ( '# p h o to s _ in n e r').c lic k (fu n c tio n () {
var scrollAmount = $ (th is ).w id th ( ) - $ ( t h is ) .p a re n t ( ) . width():

var currentPos = M a t h . a b s ( p a r s e l n t ( $ ( t h i s ) . c s s ( 'l e f t ')));
var remainingScroll = scrollAmount - currentPos: e
//
var n extScroll = M a t h .flo o r($ (t h is ).p a r e n t O .w id t h O / 2);

// ,
// ,
i f (remainingScroll < n e xtS cro ll) {
nextScroll = re m ainin gS cro ll;
}
i f (currentPos < scrollAmount) {
// '
$(th is ) .animate({' l e f t ':'- = ' + nextScroll}. 'slow');
}
el se{
//
$(this).anim ated{'left':'0 '} . 'fa s t');
}
}):
,
, , .
, ,
.
, :
scrollAmount.

, ,
, . JavaScript-
Math . abs()
, ,
. , ,
, :
, ,
. ,
Math. abs(3) 3, a Math.abs(-3) 3.
, , ,
,
! .
: ,
.
(Math. f 1oor ()
134 4. -

). ,
, nextScrol 1.
, ,
w nextScrol 1 ,
.
, .
(
), .
( ),
, .
,
? !
,
...

ScrollTo
, 3
, -, ScrollTo.
,
, (
, )!


, ,
.
ScrollTo
,
.
.
, .
,
.
.
div,
div.
div,
, ,
.
overflow: hidden ( auto). .
chapter_04/13_scrol 1in g g a lle r y /in d e x .h tm l ()
<div id="pic_container">
<div id= "pic_ scro ller">
<img alt="Glendatronix" s r c = " . / i m a g e s / g l enda_200.jpg" />
<img a lt= MDarth Fader" src= ". . / . ./images/fader_200.jpg" />
- 135

<img alt="Beau Dandy" src=". ./images/beau_200.jpg" />


</div>
</div>
div- pic container , , ,
;
3 4.
200 200 , 800
600 .
.
chapter_04/ 13_scro11i n g g a l 1e ry /s ty l e . css ( )
#pic_container {
overflow: hidden;
height: 200px;
width: 200px;
margin-bottom: 15px;
}
#pic_scroller {
height: 600px;
width: 800px;
overflow: hidden;
}
#pic_scroller img {
float: left;
}
, , .
,
Scrol 1.
chapter_04/ 13_scrol 1in g gal 1e r y / s c r ip t .j s ()
$ ( '# p ic _ c o n t a in e r ') .c lic k ( fu n c tio n ( ) {
var numberOfPics = $(t h i s ) . f i n d ( ' div > im g ') .length;
var next = Math, f lo o r (Math. randomO * numberOfPics);
$(this)
.scrollToC
'# pic_scroller>img:eq(' + next + ') '.
{duration: 1000}
):
}):
, !
ScrollTo . ,
jQuery: find
:eq. find
j Query- $, ,
, .
:eq , :eq,
, , , ,
136 4. -

. 0
.


Hath. random 0 1.
.
Math.floor(M ath. randomC) * maximum).
,
.

, ScrolFTo
: ,
!

data
, ,
,
: , ,
, !
,
. ,
.
chapter_04/14_scrol 1ing gal 1eryimproved/script.js ()
$('#pic_container') .click(function() {
var numberOfPics = $ (th is).fin d (' div > img').length;
var last = $(this).data(,l a s t ');
var next = Math.floor(Math.randomO * numberOfPics):
if (next = last) {
next = (next + 1) X numberOfPics;
}
$(this)
.d ataC last, next)
.scrollTo(
'#photos_inner>img:eq( + next +
{duration: 1000}):
}):
jQuery
data. , ,
j Query.
.
, . ,
, .
, ,
, number
$(this) .data( ' l a s t ' . next).
scro ller
$(thi s ). data (' 1a s t'). , ,
1
- 137

( ,
).
,
(
).
jQuery,
!

iPhoto- -
- iPhoto-no-
(iPhoto ,
MacOS X).

,
.
j Query- ,
,
.
,
.
-
. dive ,
, ,
.
chapter_04/15_iphoto_style_slideshow/index.html ()
<h2>Around town last night</h2>
<div id="photos">
<a href-"#" class="trigger">Image Gallery</a>
<ul id="photos_inner">
<li>
<img alt="Glendatronix" src=". . / . ./images/glenda_400.jpg" />
</li>
<li>
<img alt="Darth Fader" src=". . / . ./images/fader_400.jpg" />
</li>

</ul>
</div>
-
CSS JavaScript,
. , , ,
, .
JavaScript, , ,
,
, . ,
138 4. -

HTML-.
- CSS.
chapter_04/15_iphoto_style_slideshow /style.css ()
#photos {
border: lpx solid #BEBEBE;
height: 400px:
overflow: hidden:
position: relative;
width: 400px;
}
fphotos ul {
le ft: 0;
list-style-type: none:
margin: 0:
padding: 0:
position: absolute:
top: 0:
width: 2400px;
}
#photos li {
float: le ft;
}
#photos .trigger {
le ft: 0;
position: absolute;
top: 0:
z-index: 10;
text-indent: -9999px:
height: 400px;
width: 400px:
display: block:
}
div, .
400
. ,

, . overf 1ow: hi dden; ,

. ,
-, ,
, 2400 .
-
, .
, CSS,
-,
text-indent: -9999. , CSS,
j Query!
- 139


,
,
.
.
(

jQuery
6),
.
JavaScript (
] Query),
: var gallery = {}:. ,
({}). ,
.
, , -
, -.
.
,
. ,
- -
.
ch ap te r_ 0 4 /1 5 _ ip h otosty le _ slid e sh o w /scrip t.j s ()
gallery.trigger = $("#photos .trigger"):
gallery.content = $("#photos_inner");
gallery.scroll = false;
gallery.width = 400:
gallery.innerWidth = gallery.content.width();
gallery.timer = false;
gal lery. timer = false, :
var gallery = {
timer = false;
}
. (dot)
. ,
,
.
, : gal 1ery. tri gger
jQuery , a gal 1ery. content .
,
.
,
-, .
, gallery,
. gal lery offset ,
-; gal lery. slide
140 4. -

;
gal 1. di recti on, -,
gal 1. init. .
ch apter_04/15_iphoto_style_slideshow /script.j s ( )
gall . offset = functionO {
var le ft = gallery.content.positionO .left;
if (gallery.scroll == >') {
if (left < 0) {
le ft += gallery.width;
}
} else {
if (le ft <= 0 && le ft >= ( (gallery.innerWidth * -1) + (gallery.width * 2))) {
le ft -= gallery.width:
}
}
return le ft + "px";
}
, gallery.offset,
, 1eft ,
, di v. posi ti on offset
j Query ,
.

, , - .
, 1eft ( wi dth
400 left),
. ,
, CSS-.
, gal 1.offset ,
, .
:
gall . slide? ,
,
, .
,
. .
ch apter_04/15_iphoto_style_slideshow /script.js ( )
gallery.slide = functionO {
if (gallery.timer) {
clearTimeout(gallery.timer);
}
if (gallery.scrol1) {
$(gallery.content)
.stop(true.true)
.animate({left: gallery.offsetO}, 500);
gallery.timer = setTimeout(gallery.slide. 1000);
}
}
- 141

slide , gallery.timer.
, setTimeout , clearTimeout
. ,
, ! 11ery.sc rol1,
, . ,
,
.
, jQuery- animate left gal 1ery. content.

. stop(true.true),
.
500 ,
,
, setTimeout. setTimeout
gal 1ery. timer, , 500
, ,
( 1000, 500
).
? gallery.direction .
chapter_04/15_iphoto_style_slideshow/script. js ()
gall ery. direction = functions, which) {
var x = e.pageX - which, off set O .l eft;
gallery.scroll = (x >= gallery.width / 2) ? ">" : ;
}
gall ery. direction,
: , , whi ch,
, .
,
, -,
. .
. ,
(. -
-
) gallery.scroll: ">",
, "<" .
, ,
gall ery. i ni t.
chapter_04/15_i photostyle_slideshow/scri p t. js ()
gallery.init = function {
$(gallery.trigger)
.mouseout(function() {gallery.scroll = false:})
.mousemove(functi on(e) {gal 1ery.di recti on(e.gal 1ery.tri gger);})
.mouseover(function(e) {
gallery.direction(e,gallery.trigger);
gallery.slideO ;
}):
}
142 4. -

,
. gal 1. i ni t jQuery,
jQuery, gal 1.trigger.
.
mouseout gall . scroll false.
, , ,
, mousemove gal 1 .di recti on, ,
, gallery.scrol 1, . ,
mouseover gall . di recti on,
gal 1. si i de . gal 1.di rection ,
,
.
. $(document). ready ()
,
DOM, ,
, , .
, , ,
, , !
, , ,
, .
StarTrackr!, ,
mouseover -
callback.



callback, ,
mouseover, ,
: . ,
,
jQuery. ,
.
, jQuery
, .
: keypress
, click ,
, . . jQuery ,

.

EVENT
,
. evnt .
event, Internet Explorer
(window.event).
, ! 143

. mouseover ,
.
, , gallery,
di recti on. ,
, , .

.
chapter_04/15_i photostyle_sli deshow/scr i p t.j s ()
var = e.pageX - which, off set . left;
,
. , ,
. ,
.
()
chapter_04/15_iphoto_style_slideshow /script. j s
gallery.scroll = (x >= gallery.width / 2) ? ">" : "<";
pageXi s .
,
.

, !
! , ,
,
j Query! , ,
, .
, -
, . ,
.
StarTrackr!, , ,
, -,
. ( )
, ,
.
, ,
, j Query!
, ,
5
jQuery, ,
DOM
, CSS- ,
.
, ,
,
.
-
RIA.
- -
RIA (Rich Internet Applications
-)
. , ,
,
. ,
, , -
.

: 1
,
, ,
accordion (). ,
,
!

,
.
j Query
:
.
145

StarTrackr! ( ,
, ),

.
,
, .

/
,
.
,
, ,
. ,
, ,
.
, ,
2. ,
. , . 5.1.

Whats new?

Member extras

Prem ium Celebrities

24-hour Surveillance

About us

. 5 .1 .


, .
5- nav,
.
,
.
.
chapterJ)5/01_expandablejnenus/index.html ()
<nav role=navigation>
<ul id=menu,,>
146 5. , ,

<1i >< href="#">What's new?</a>


<ul class="active">
<li><a href="#">Weekly spedals</a></li>
<1 i><a href=,,#">Last night's pics!</a></li>
<li><a href="#">Users' comments</a></li>
</ul>
</li>
<1i><a href="#">Member extras</a>
<ul>
<li><a href="#">Premium Celebrities</a></li>
<1i><a href="#">24-hour Surveillance</a></li>

, .
chapter_05/01_expandable_menus/menus.css ()
#menu, #menu ul {
list-style-type: none:
padding: 0:
margin: 0:
}
#menu li {
cursor: pointer;
background: #94C5EB;
border-bottom: lpx solid #444;

#menu li a { text-decoration: none: }

#menu > li > a {


padding: 2px lOpx;
font-weight: bold:

#menu li li {
cursor: auto;
border: 0;
padding: 0 14px;
background-color: #fff;
}
CSS- chi Id
, ,
. ,
Internet Explorer 6,
.
( ,
) click, -
147

, ,
, .
.
,
JavaScript.
. .
chapter_05/01_expandablejnenus/script.j s ( )
$('#menu > 1i > u l')
.hideO
.click(function(event) {
event.stopPropagation0 ;
}):
child,
, .
, ,
, - .
event. stopPropagati on()
. ,
toggle,
.
chapter_05/01_expandable_menus/script.j s ( )
$('#menu > li').toggle(function() {
$(this) . find(' u l') .slideDownO;
}, functionO {
$ (th is).find(' u l') .slideUpO;
}):
, ,
.
, , stopPropagati on.



DOM.
, .

DOM,
. :
, ,

.

.
. - di v,
148 5. , ,

. di v
outer i nner .
chapter_05/02_event_propagation/index.html ()
<div id=,,outer">
Click Outer!
<div id="innerM >
Click Inner!
</div>
</div>
cl i ck di v.

, .
chapter_05/02_event_propagation/script.j s ()
$ ('div') . click(function() {
alertCHello from ' + $(this) .a ttr ( ' i d '));
}):
di v:
Hel 1 from outer.
di v. ,
Hello from inner. Hello from outer...
? di v ,
, click?
, click
, .
di v ,
. (
) di v (
di v) , .

DOM , .
;

DOM. , ,
,
,
,
. ,
:
. -
click
.
,
. ,
. ,
(Whac-A-Mole).
149

: .
, .

,
.
,
. , ,
target , ,
, .
.
JavaScript-,
false .
. j Query
W3C, ,
, .
j Query
stopPropagation, .
call back , event.
stopPropagation ,
DOM.


, -,
preventDefault. preventDefault
,
. ,
,
:
$ (' ' ) .click(function(event) {
event.preventDefault();
}):
, -.
, , , ,

, ,
, , -, 4.
JavaScript,
.
j Query-.

, .
? , ,
false ,
, preventDefault stopPropagation.
, , , .
150 5. , ,

isDefaultPrevented isPropaga-
t i onStopped
, .
, true,

, fa ls e .

/
, ,
j Query: ,
.
/
(. 5.2).

What's new?
Member extras
P re m iu m C e le b ritie s

24-h our S u rv e illa n c e

About us
. 5.2. /

, ,
( ).
, ,
. ,
, .
CSS- .
(
), ( ) .
, CSS ,
. -
,
20 .
1i , .
chapter_05/03_open_closed_indicators/menus.css ()
#menu l i {
cursor:pointer;
151

border-bottom:lpx solid #444:


background: #94C5EB u rl(arrow s.png) no-repeat r ig h t top:
}
#menu li li {
cursor:auto:
border:0;
padding:0 14px:
background-col or:#fff:
background-image: none;
}
,
CSS- ,
. ,
, .
, css,
, ul .
chapter_05/03_open_closedindicators/script. js ()
$('#menu > l i ' ) .toggle!function() {
$(this)
css('background-position'. right -20px)
.find(' u l') .slideDownO:
}. function!) {
$(this)
.css('background-position', 'right top)
.findCul 'KslideUpO:
}):



, hover
cl i ck.
, , .
,
, ( -
!),
, j Query- hover ,
.
, hover
,
.
,
,
.
152 5. , ,

, :
, , , -
.
chapter_05/04_menu_expand_on_hover/script. js ()
$('#menu > li ' ) .hover(function() {
$(thi s ) . addClass( 'w aiting'):
setTimeout(function() {
$('#menu .waiting')
.clickO
. removed ass ( 'w aiting');
}. 600 ) :
}. functionO {
$('#menu .waiting') . removeClass('waiting'):
}):
, ,
waiting ,
600 .
, , waiting.
, ,
waiting ( ,
).
, ,
. click
;
click (-),
. , ,
, .
click, .
, waiting , ,
, .
, removed ass.
,
, , .
,
, .
, ,
, ,
wai ti ng.
, (
). , jQuery,

. ,
,
4. , ,
, ,
, .
153


,
(
DHTML), ,
.
, , , CSS
JavaScript- -
, , jQuery
. Suckerfish1
.
Suckerfish -'
,
, .
:hover
.
CSS, .
, ,
CSS, .
: hover ,
, , /
.
Suckerfish
: ,
j Query.
Suckerfish ,
:hover. ,
, j Query- ;
, ,
.

- Suckerfish
Suckerfish.
,
/-
.
CSS Suckerfish
. ,
, , CSS-
:hover. ,
, .
chapter_05/05_dropdown_menu/menus.css
Container {
position: relative:
i
http://www.alistapart.a)m/artides/dfX)pdowns
154 5. , ,

}
#menu {
position: absolute;
top: 0;
right: 0;
}
#menu, #menu ill {
padding: 0:
margin: 0:
list-sty le : none;
}
#menu li {
float: le ft;
background: #FFF;
}
#menu a {
display: block;
padding: 4px;
width: lOem:
}
#menu 1i ul {
position: absolute:
width: lOem;
le ft: -999em;
}
#menu li:hover u l. #menu li ul:hover {
left:auto;
}
,
:
JavaScript! jQuery ,
, ,
. , ,
. 5.3.

. 5.3.

j Query?
, . hover
155

. : hover
, . ,
CSS ?
: hover, CSS, hover,
jQuery? , !
CSS-
hover. , (
) jQuery CSS-:
$('#nav 1i :hover u T ) .c s s ( 'le f t '. ,-999em'): // He !
:
CSS- Suckerfish, jQuery-?
CSS- ,
CSS- ,
:
chapter_05/05_dropdown_menu/script.js ()
$('#menu 1i u l' ) .css({
display: "none",
left: "auto"
}):
$('#menu l i ' ) .hover(function0 {
$(thi s )
.find(' u l')
.stop(true. true)
.slideDown('fast'):
}. functionO {
$(thi s )
.find(' u l')
.stop(true.true)
.fadeO ut('fast');
}):
CSS-,
, display: "none".
,
.
si ideDown fadeOut,
CSS- .
stop(true. true),
3, ,
,
. , , delay,
.

, , ,
JavaScript, Suckerfish
, .
156 5. , ,

Hover Intent
, mouseover,
, .
, ,
.
, .
. ,
, ,
.
,
,
. . ,
, , ,
, ,
.

Hover Intent1.
.
,
, Hover Intent ,
.
, ,
hover. ,
,
hover hover Intent.
chapter_05/06_dropdown_with_hover_intent/script.js ()
$('#menu li ' ).hoverIntent(function() {

}, functionO {

}):
, ,
. ,
Hover Intent, , ,
.
, ;
hoverlntent
.

, ,
, Hover
Intent.

i http ://cherne. net/brian/nesources/jquery.hoverlntent html


157



,
. , ,
, ,
,
.


, .
,
j Query-.
, ( -
) .
( j Query!),
, ,
.

.
StarTrackr!,
. , , . 5.4.
, ,
HTML-. , ,
, .
.
chapter_05/07_simple_accordion/index.html ()
<ul>
<li class="active">
"A" List Celebrities
<ul>
<1 i><a href=,,#>Computadors</a> &nbsp: New!</1i >
<1i><a href="#">Johnny Stardust</a></li>
<1i><a href="#">Beau Dandy</a></li>
</ul>
</li>
<li>
"B" List Celebrities
<ul>
<1i><a href="#">Sinusoidal Tendancies</a></li>
<1i><a href="#">Steve Extreme</a></li>
</ul>
</li>

</ul>
158 5. , ,

Our Celebrities
A-List Celebrities
The Jemimas New'

Computadors New!

Johny Stardust

Beau Dandy

-List Celebrities

Has Beens
Barely Famous Celebrities

. 5

HTML-
, ;
dive ,
. ,

.
CSS, ,
.
- ,
. , : ,
.
chapter_05/07_simple_accordion/script.js ()
$ ( '#celebs ul > u l ')
.c lic k (fu n c tio n (e v e n t) {
event.stopPropagati on ();
})
. f i l t e r ( ' :n o t (:f i r s t ) ')
.h id e O ;

, .
, (
/
).
j Query:
159

,
.
fil ter
. ,
, ,
j Query .
(. filter ).
filter ( :not : first),
j Query-
.
: not ,
, . $(': not ()')
, , $(' : not (.
acti ve)') , acti ve.
, f il t e r ,
add,
f il ter add,
j Query-,
.

, ;

.
jQuery. true, ,
. ,
active:

$ ( ) .filte r ( fu n c tio n ( in d e x ) {
re tu rn index 2 || $ ( th is ) .h a s C la s s ( 'a c t iv e ');
}):
,
, , ?
$(this).
, ,
, true,
.

,
( ),
.
: ,
.
, , , .
chapter_05/07_si mple accordi on/scri p t .js ()
$('#celebs ul > l i ' ) . c l i c k ( f u n c t i o n ( ) {
var s e l f C l i c k = $ ( t h i s ) . f i n d ( ' u l :f i r s t ' ) . i s ( v i s i b l e ' ): Q
160 5. , ,

if ( JselfClick) { 0
$(thi s )
.parent()
.find( > li u l:v is ib le ')
.slideToggleO;
}
$(this)
.find(' u l:f i r s t ')
.slideToggleO: e
}):
.
^ , ul,
is( v isib le'), selfCl ick (
true,
).
JavaScript- ! i f
, ,
. ! not,
, sel fCl i ck true.
Q M , ,
: , , , .

, , .
,
, ,
.
JavaScript. sel fCl ick
true,
JavaScript return.
chapter_05/08_sim ple_accordion_variant/script.js ()
$('#celebs ul > l i ' ).click(function() {
var selfClick = $ (th is).fin d (,u l: f ir s t, ) .i s ( :v isib le '):
if (selfClick) {
return;
}
$( thi s )
.parent 0
.find( > li u l: v is ib le ')
.slideToggleO:
$(thi s )
.find( 'u l:f i r s t ')
.stop(true, true)
.slideToggleO:
}):
lei


, HTML-
, j Query-,
,
.
. , ,
, .
chapter_05/09_multi_level_accordion/index.html ()
<ul>
<li class="active">"A" L i s t C e le b r it ie s
<ul>
<1i><a href="#">Computadors</a> &nbsp;New!</li>
<1i>Rising Stars
<ul>
<1i><a href="#">Johnny Stardust</a></li>
<1i><a href="#">Beau Dandy</a></li>
</ul>
</li>
<1i> F a llin g Stars
<ul>
<li><a href="#">Kellie Kelly</a></li>
<1 i><a href=,,#">Darth Fader</a></li>



$(' #accordi on > 1i ' ). cl i ck ( ...) .
,
, , .
chapter_05/09_multi_level accordi o n /sc ri p t .j s ( )
$ ( '#accordion > l i . #accordion > 1i > ul > l i ' ) .cl i ck (...);

, ,
.
,
HTML-.
1i ,
#accordion;
, , addSel f ,
1i :
$ ( '#accordion > l i ) . f i n d ( > ul > 1i ) .ad d SelfC ).click(...);

f in d >,
, .
. 5.5.
162 5. , ,

Our Celebrities
A-List Celebrities
R is in g S ta r s
T h e J e m im a s New!

J o h n y S ta r d u s t

B eau D andy

F a llin g S ta r s
-List Celebrities
Has Beens
Barely Famous Celebrities

. 5.5.

,
. ,
.
, , ,
,
(. 8).


jQuery UI
, jQuery
.
jQuery ,
, ,

. ,
mouseover
163

(, ,
, auto
height).
.
jQuery UI
Sunny . 5.6.

" A " L is t C e le b ritie s

Johnv Stardust
B e a u Dandv

Kellie Kelly

QacfoEatisr

"B" List Celebrities

Has Beens

Barely Famous Celebrities

. 5.6.
jQ u e ry UI Sunny

, ,
jQuery UI
. ,
, .
, ,
, ,
.
chapter_05/10_jquery_ui_accordion/script.js ()
$ ( ' # accordion') .accordion ({header: 'h 3 ' });

, ,
, -
h3 ,
.
,
. ,
, acti vate
, . ,
( , ),
.
chapter_05/10_jqueryuiaccordion/script. js ()
$("#accordion").accordion( 'a c tiv a te '. 2 ) ;
164 5. , ,


, ,
jQuery U I1.
j Query UI
,
.

, j Query
UI .

, ,
.
,
, . JavaScript
,
, .



,
. , , ,
, .
:
.
, JavaScript:
-.
, ,
.
div.
chapter_05/ll simple_tabs/i ndex.html ()
<div id="info">
<p id=intro">
Welcome to <strong>StarTrackr!</strong> the planet's premier ...
</p>
<p id="about">
StarTrackr! was founded in early 2009 when a young ...
</p>
<p id="disclaimer">
Disclaimer! This service is not intended for the those ...
</p>
</div>

http://jqueryui .com/demo^/accordiory
165

. -
.
, :
chapter_05/ll_simple_tabs/index.html ()
<ul id="info-nav">
<1 i><a href="#intro,,>Intro</a></l i>
<1i><a href="#about">About Us</a></li>
<1i><a href="#disclaimer">Disclaimer</a></li>
</ul>

CSS,
, .
, .
,
.
, ,
( ),
, .
:
$( '#info ' ).hide() .eq(0) .showO;
j Query ;
,
.
;
.
chapter_05/ll_simple_tabs/script.js ()
$('#info p :n o t(:first)').h id e();
, , ,
.
,
hi de/show,
.
chapter_05/ll_simple tab s/scrip t. js ()
$('#info-nav l i ' ).click(function(event) {
event.preventDefault():
$('#info p').hide();
$('#info-nav .current' ) . removed ass( "current"):
$(this) .adddass( 'current');

var clicked = $(th is ) .find(' a :f i r s t ' ) .a ttr('h re f');


$('#info ' + clicked).fadeln('fast'):
e.preventDefaultO;
}).eq(0).addClass('current'):
. -,
, ,
166 5. , ,

, href
JavaScript- +. ,
- (#) ,
a jQuery
i < , ,

. -, ,
preventDefault . ,

. , !
click ,
, eq,
current. ,
. , ,
0 ( , )
, .


jQuery UI

,
,
jQuery. ,
,
jQuery UI
Tabs, .

jQuery UI, ,
. jQuery
,
, ,
, ,

.
,
( , ),
Ajax. Ajax 6,
:
- .
, , , , ,
jQuery UI. ,
Tabs, CSS JavaScript
HTML-.
jQuery UI, . 5.7.
167

................................... }
I A b o u t S tarTrackrt D iscla im e r *

W elcom e to S ta rTra ckrl the planet's premier celebrity tracking and


monitoring service. N eed to know w here in the world the best bands,
musicians or producers are within 2.2 square meters? Y ouVe com e to the
right place. W e have a very special special on -grade celebs this week, so
hurry in!

. 5 .7 . j Q u e r y Ul

jQuery CSS- ,
. ,
Ajax, -;

DOM.
chapter_05/12_jquery_ui_tabs/index.html ()
<div id="info">
<ul id="info-nav>
<1i><a href="#intro>Intro</a></li>
<1i><a href="about.html>About StarTrackr!</a></1i>
<1i><a href="disclaimer.html">Disclaimer</a></li>
</ul >
<div>
<p id="intro">
Welcome to <strong>StarTrackr!</strong> the planet's premier ...
</p>
</div>
</div>
, .
, -
id , ( #intro).
Ajax-,
HTML- ( ). -
, ,
. ,
Ajax- jQuery UI,
HTML-.
, .
,
JavaScript,
.
JavaScript , jQuery
,
. , HTML-
, jQuery- ,
168 5. , ,

,
<body>.

Ajax, .
chapter_05/12 j q u e r y u i t a b s / s c r i p t . j s ()
$('#info).tabs();
, ,
( Write le ss. do more).


, ,
,
jQuery 1. .
chapter_05/13_jquery_ui_tab_options/script.j s ()
$ ('#i nfo') . tabs({
event: 'mouseover'.
fx: {
opacity: 'to g g le'.
duration: 'fa s t'
}.
spinner: 'Loading...',
cache: true
}):

JavaScript, : event, fx, spinner cache.
event , ,
click mouseover. ,
,
.

. fx
, animate,
.
Ajax-. spinner
HTML-, ,
. - ,
, , , , ,
(, , , spinner),
-. spinner
, GIF-
,
spinner.gif.

1
http://jqueryui.com/demos/tabs/
169

cache
, . ,
,
, .



. , ,
. .
chapter_05/14_jquery_ui_tab_control/script.js ()
$C #info').tabs().tabsC ro ta te '. 3500);
tabs ,
jQuery 3500 ( 3,5 ).
,
, .
, , .
, ,
selected:
$ ('#tabs') . tabs( 1option'. 'selected');
, , . ,
,
, -.
- About
Us ( ) .
, -, About Us
( ):
chapter_05/14_jquery_ui_tab_control/script.j s ()
$("#info a[href=about.html]").click(function(event) {
$(#info') .ta b s ('se le c t', 1);
event.preventDefault();
}):


,
, !
- ,
.

,
. ,

.
170 5. , ,





, .
,
, .
,
.
,
, ,
-
,
, , .
, , . 5.8.

Username*

___ Passw ord

log in

. 5.8.

,
j Query, .
CSS-, , ,
, -.

click ,
, , .
chapter_05/15_login panel/script. js ( )
$('#1ogin fo rm ') .h id e ( );
$('#1ogi it a ' ) .to g g le (fu n c tio n () {
$ (th is )
. a d d C la s s ( 'a c t iv e ')
. n e x t ( 'fo r m ')
.a n im a te ({ 'h e ig h t': 'show'}. {
duration: 's lo w ',
e a sin g: ' easeOutBounce'
}):
171

}. functionO {
$(thi s )
.removedass( 'a c tiv e ')
,next('form')
.slidellpO;
}):
,
, ,
CSS-
jQ uery- css.
, JavaScript
( ),
, - ,
.
, , ,
.
Ajax (
-), , , ,
. - -
, ,
.
chapter_05/15_login_panel/script.js ()
$('#1ogin form :submit') .click(function() {
$(thi s )
.parent 0
.prev('a1)
.clickO ;
}):
click ,
DOM
-. ,
- ,
,
DOM prev hide/show.



,
,
-, . .
: ,
,
, !
172 5. , ,


: , , ,
. ,
, ,
.
,
, ,
1 . ,
, ,
!
, , , ,
-,
-,
. , , ,

Next/Previous (/).

Shopping Cart ( ). ,
, - -,
,
, Checkout (
) View Cart ( ). . 5.9,
- -, ,
.

You have 5 items in your cart.

What's new?
Member extras
About Us

Welcome to StarTrackr! the planets premier celebrity tracking and


monitoring service. Need to know where in the world the best bands,
musicians or producers are within 2.2 square meters? Youve come to the
right place. We have a very special special on -grade celebs this week, so

. 5.9. ,
-

,
. ,
.
-.

1
,
,
. . .
173

chapter_05/16_s1iding_overlay/panel.css ()
.cart {
position: absolute:
width: 32px;
height: 32px:
right: 15px;
top: -lOpx;
background: transparent url(shoppingcart.png) no-repeat 0 0:
text-indent: -9999px;
}
.cart a:hover, .cart-hover {
background-position: 0 -32px;
}
#overlay {
position: absolute;
width: 100*;
height: lOOpx;
top: 0;
le ft: 0;
color: #fff;
background-color: #000;
display: none:
text-align: center;
}
#overlay a {
font-size: 130*;
font-weight: bold;
}
jQuery , ,
- jQuery.
, 100 % -,
100 . , ,
0. ,
, - .
.
hover, ,
-, , ,
. active,
, ,
. data,
data
- - 4,
,
. ,
,
active 1 . ,
174 5. , ,

,
.
chapter_05/16_sliding_overlay/script.js ()
$(<di v></di v>)
. a t t r ( 'i d '. 'overlay')
.css( 'opacity'. 0.65)
.hover(function() {
$(this).addClass( 'a c tiv e ');
}. functionO {
$(this).removeClass('active');
setTimeout(functionO {
$ ('#overlay:not( .active)') .slideUp(function() {
$('a.cart-hover') . removed ass( 'cart-hover');
}):
}. 800):
}).appendTo('body'):
CSS- opacity,
. 0 1, 1
, 0 .


,
. ,
, ,
,
.
,
, , , , .

.
chapter_05/16_sli dingoverlay/scri p t.js ()
$ ('.ca rt a ') .mouseover(functionO {
$(this).addClass('cart-hover');
$( '#overlay:not( animated)')
.addClass('active')
.html( '<hl>You have 5 items in your cart.</hl>
b*<a href="#">View Cart</a>&nbsp:<a href="#">Checkout</a>' )
.slideDownO;
}):
animated,
, (,
, :not ,
). ,

, .
,
hover ,
.
175

, ,
, j Query
,
.

, ,
- .
;
t i t l e alt,
.
,
, ,
.
JavaScript- .
,
, .
, ,
,
, .
,
, , .

HTML-,
-.


, ,
, , .
, ,
, ,
. 5.10.

Approx. Location Price


Los fac t l Q Q S _______
C h e c k o u t a ll th e C e le b s in L A t h is w e ek!
N e w Y o rk 5 3 9 .9 5

. 5.10. ,

t i t l e .
,
,
176 5. , ,

JavaScript. , ,
.
chapter_05/17_sim ple_tooltips/index.htm l ()
< href*"#" class= "location" title="Check out a l l the ... ">
New York</a>

t i t l e : (
) HTML- ,
, ,
. ,
. ,
, ,
, , ,
.


, , !
.
chapter_05/17_sim pletool tip s / t o o l t i p s .c ss ()
. t o o l t ip {
display: none:
position : absolute;
border: lpx s o l i d #333;
background-color; #ffed8a;
padding; 2px 6px;
}
,
.
, :
hover, mousemove. ,
hover,
,
:
chapter_05/17_si mpl e t o o l t i p s/sc r i p t . j s ( )
$(' . l o c a t i o n ) .hover(function(event) {
// .
}, fu n c tio n O {
// .
} ) .mousemove(function(event) {
// .
}):
,
, ,
. ,
,
.
177

. , ,
, ,
. ,
event. ,
,
.
chapter_05/17_simple_tooltips/script.js ()
II ,
var t i t l e T e x t = $ ( t h i s ) . a t t r ( ' t i t l e ' );
$ (th is )
. d a t a ( ' t i p T e x t ' . t i t le T e x t )
. r e m o v e A t t r ( ' t i t l e ' );

$('<p class="tooltip"></p>')
.te x t(title T e x t)
.appendTo('body')
. c s s C t o p ' . (event.pageY - 10) + 'p x')
. c s s C l e f t ' , (event.pageX + 20) + 'p x')
. f a d e l n ( 's l o w ');

ti tle ,
, .
:
data,
data -
- 4. ,
t i t l e ,
, , .
data, t i t l e
.

. tooltip, ,
. text
. html text,
, W3C, t i t l e HTML.
, ,
HTML-,
.

to o ltip , id
jQuery : $( '<></> ) .a ttr( i d ' . t o o lt ip '). ,
JavaScript
: $('<>' + title T e x t + ' </> ).
DOM.
, ,
: , jQuery,
JavaScript.
178 5. , ,

- ( appendTo),
(event)
, .
pageY , -
.
: - ,
.
chapter_05/17_simple_tooltips/script.js ()
11,
$ ( t h i s ) . a t t r C ' t i t l e ' . S C t h is ) . d a t a ( 't ip T e x t '));
$ ( ' . t o o ltip ').re m o v e () ;

, , :
, ,
, ti tle .
chapter_05/17_simple_tooltips/scri p t.js ()
// ,
$ ( '.to o ltip ')
. c s s C t o p ' . (event.pageY - 10) + ' p x ' )
. c s s C l e f t ' . (event.pageX + 20) + 'p x '):

,
.
. !
, , ,
.


, , ,
- . ,
(, ),

t i t l e
CSS,
j Query , . . 5.11.

Welcome to StarTrackr! the planet's premier cele


where In the^ J w-,. . . . ----- sj

,otherightl Legal Disclaimer |

. 5 .1 1 . ,

span,
,
.
,
179

,
.
, ,
, - ,
hover .
.
chapter_05/18_advanced_tooltips/1ndex.html ()
<P>
Welcome to
<strong>StarTrackr!
<span cl a s s - ' di a lo g >
<span><a href='#'>Legal Disclaimer</a></span>
</span>
</strong> the p la n e t's premier c e le b r it y tracking ...
</p>


. :
, .
, ,
, ,
.

, :
, ,
.
(. 5.12).

. 5.12.


j Query. , ,
- .
,
- ,
-,
. 6

, .
j Query,
, ,
180 5. , ,

,
- .
DIALOG,
. delay (
,
, ).
chapter_05/18_advanced_tooltips/script.j s ()
var DIALOG = {
current: n u ll,
delay: 600,
timer: n u ll,
setDialogs: fu nction 0 {
//

}
setDialogs,
-.
- ,
.
hover,
. hover.
chapter_05/18_advanced_tooltips/script.j s ()
$ ( ' . d i a l o g ' ) .parent .hover(function {
// ,
DIALOG.current = $(th i s ):
DIALOG.timer = setTimeout(function() {
//
$ ( t h i s ) . f i n d ( " . d i a l o g " ) . f a d e l n ( ' f a s t ' ):
} . DIALOG.del ay):
}. fu n c tio n O {
//
clearTimeoirt( DIALOG, t i m e r ) ;
$ ( t h i s ) . f i n d ( " . d i a l o g " ) . f a d e 0 u t ( 'f a s t ' ) :
} ) . a t t r ( " t i t l e " . ""); // t i t l e
//

, .
setTimeout,
. ,
, . del ay,
setTimeout.
, ,
, .
, ,
,
, . JavaScript-
cl earTimeout, .
181

1 FOR EACH
, , JavaScript
, ,
each:
chapter_05/18_advanced_tooltips/script.js ( )

$0".dialog").each(function(){// -
, JavaScript- jQuery-,
. each for,
jQuery, . , , ,
. .
, for? ! ,
, ,
, . ,
, each
, for
. , , ,
, each.

, , hover,
.
, , each( ),
. ,
jQuery
, .
,
.
chapter_05/18_advanced_tooltips/script.js ()
setDialogs: function {
var screenWidth = $(window) .w id t h O .
screenBottom = $(window).scrollTopO + $(window).height();

$ ( " .d ia lo g ").e a c h (fu n c tio n (){// -


ta^var container = $ ( t h is ) . p a r e n t O ;
top = co n ta in e r.h e ig h tO , //
totalH eig h t = top + $ (th is ) .outerHeightO Q
width = $ (this).outerW idth(),
o ff s e t = c o n t a in e r .o ffs e t O .
l e f t = 0;

// Q
i f ( Scontai.c s s ( ' p o s i t i o n ' ) != 'absolute' &&
^ c o n t a i n e r . c s s C p o s itio n ") != "fixe d") {
c o n ta in e r.c s s ({p o s i t i o n : ' r e l a t i v e '} ) ;
182 5. , ,

. ,
-,
-, $(th i s ) .
parent (). , $
, j Query.
.
top
. ,
(
).

,
.
, position: absolute:
posi t i on: f i xed :. ,
p o s i t i o n : absolu te :
. absol ute f i xed,
. posi t i on : rel ati v e :.


i f JavaScript
&&, a n d ( ). ,
i f
( &&).
11 ( ),
o r ( ). &&,
i f .

, ! ,
, : ,
?
, ,
, !
. ,

. , .
chapter_05/18_advanced_tooltips/script. j s ()
II ,
//
i f ( o f f s e t . l e f t + width > screenWidth) {
l e f t = 0 - width + 42:
$(thi s ) .addClass('1 e f t ):
} else {
$ ( t h i s ) . r e m o v e d a s s ( ' l e f t ' ):
}
// ,
183

//
if (offset.top + totalHeight > screenBottom) {
top = 0 - $(this).outerHeight();
S(this).addClassC'above');
} else {
$(this).removed ass( 'above');

,
( ) () () ,
. , top 1eft
, ,
-.
( ) css
top 1eft.
chapter_05/18_advanced_tooltips/script.js ()
$(this).css({
"top": top,
"left": le ft
}>:
setDialogs document-ready,
, ,
.
chapter_05/18_advanced_tooltips/script.js ()
S(document).ready(function() {
DIALOG.setDialogs ();
}):
$(window).resize(function!) {
DIALOG.setDialogs();
}):
CSS
, , .
chapter_05/18_advanced_tooltips/dialog.css ()
span.dialog.left {
background-position: 100$ 0:
}
span.dialog.left span {
padding: 15px 0 0 17px;
}
span.dialog.above {
background-position: 0 100$:
}
span.dialog.above span {
184 5. , ,

padding: 13 0 0 12;
}
span .d ialo g.ab o v e .left {
background-position: 100$ 100$:
}
span .d ialo g.ab o v e .left span {
padding: 13px 0 0 17px;
}

INTERNET EXPLORER 6
jQuery -
JavaScript-, CSS .

class . Internet Explorer 6,
class . ,
PNG -
,
Internet Explorer 6.
( YouTube Facebook)
Internet Explorer 6. ,
,
( ,
JavaScript).
1,
, Internet Explorer 6,
,
, ,
.
,
PNG .
, Internet Explorer 6,
Chrome Frame Google2. Chrome Frame Open Web
JavaScript- Chrome Internet Explorer.
Internet Explorer 6, , ,
Chrome Frame.

!
, , ,
,
, !
- -,

. span
dialog. : -

1 http://refenence.sltepoint.corrycss/con(jitic)nalcomments
2
http://code.gcx)gle.a)rrychrome/chromeframe
185

, .

,
,
.


! .
- j Query
, ,
, ,
.

, , ,
. , ,
, ,
.
, ,
.
,
, , j Query
Ajax!
, Ajax
6


, . ,
, :
- Web 2.0, ,
- Web 2.0.
Ajax!
:
, Twitter,
... , , StarTrackr!
Ajax, Facebook, Flickr Netvibes, .
, . Ajax-
, j Query
.
. (,
- HTML-) , ,
Ajax-, ,
,
. , ,
,
.


JavaScript . ,
.
:

, .
,
. ( )
187

JavaScript, ,
j Query.
jQuery Ajax
DOM,
JavaScript-. JavaScript,
, , ,

.


jQuery

JavaScript- , jQuery
, .
jQuery ,
. , jQuery, ,
JavaScript,
.
, 5.

jQuery.


HTML CSS, JavaScript .
, (//), ,
,
. , ,
, :
// '3' 'count':
var count = 3:

, /*,
*/, :
/*


*/
var count = 3;


:
, , ,
.
188 6. , Ajax


/ , 2. -
jQuery,
, , :
$ ( ' ').css({color:'green'. padding:''});
- j Query
, JavaScript,
,
. , ,
- , /
, :
var id = $ ('input#id') . va1();
var name = $('input#name').val();
var age = $('input#age).val();

var data = {
type: 'person',
id: id.
name: name,
age: age
}
,
, .
, ( .) ,
, . , ,
, data, ,
, ' person' type,
, , name,
:
if (data.type == 'person') {
alertC'Hello* ' + data.name):
}


,
, j Query .
20 , hover toggl ,
, , ,
.

5,
, ,
. -
189

data ( ,
), ,
.
, s e t T ip s : fu n c tio rU ) { . . . } ,
setTips . T T .set-T ip sO
. ,
, . ,
(
), , ,
JavaScript-
. .

.

. , ,

. , ,
( jQuery ($) (_)!).
.
TRKR StarTrackr!. ,
, , ,
.
, . ,
exclaim:
function exclaim {
a le r t ( " h o o r a y " ) :
}
exclaim ();//ypa

, , ,
. , ,
-, exclaim:
fu nction exclaim {
a le rtC 'b ooo oo"):
}
exclaim O ://y -y-y -y -y

, ,
hooray (), (----).
,
, TRKR:
var TRKR = {}:

- TRKR.exclaim = function 0 {
a le r t C 'h o o r a y " ) :
}:
190 6. , Ajax

,
:
var TRKR - {};
TRKR.namespaces - " c o o l" :
TRKR.boolean - tr u e :
TRKR.pi - 3 . 14159:
TRKR.CSS = {
" c o lo r " : "# cO ffee".
"to p ": 0
}:
TRKR.exclaim * function () {
alert("hooray");

hooray - ,

:
TRKR.exclaim : //
TRKR.namespaces: // "cool"
exclaimO; // y-y-y-y-y
,
-. ,
, TRKR -,
.
!
,
, ,
, :
var TRKR {
namespaces: "cool",
boolean: true,
pi: 3.14159.
css: {
"color": "#cOffee".
"top": 0
}.
setup: functionO {
TRKR.one = 1;

}.
exclaim: functionO {
a le rt("hooray");
}
}:

, , , ,
191

. ,
,
.


,
. , ,
, -
.
.
,
(, ),
.
, ,
callback Ajax-,
, .
this
call back, ,
:
wi ndow DOM - ,
:
var WIDGET = {};
WIDGET.delay = 1000:
WIDGET.run = functionO {
alert(this.delay); // 1000 ... !
$(p).click(function() {
alert(this.delay) // He ! !
});

, ,
. , this, del ay
( , ,
!). .
JavaScript,
:
var WIDGET = {}:
WIDGET.delay = 1000:
WIDGET.run = functionO {
alert(this.delay): // 1000 ... !
var _widget = this:
$(p).click!function() {
alert(_widget.delay) // 1000 ... !
}):
}:
192 6. , Ajax

_wi dget th i s ,
,
. JavaScript .
, t h is (
th at). , ,
(_),
. ,
.
, , ,
.
, , jQuery
.
proxy.
, ,
.
, , (,
_wi dget, ), th i s
:
var WIDGET = {
delay: 1000,
run: fu n ction {
a le r t ( t h is . d e la y ) ; // 1000 ... !
$ ( " p " ) .c lic k (
$.p roxy(fun ction() {
a le r t ( t h is . d e la y ) : // 1000 ... !
}. t h is ) ;
):
}
}:
c l i ck proxy.
,
, , t h is .
, JavaScript
. :
call back, , -, ,
t h is , , !
Ajax, , ,
jQuery ,
, .


, ,
. ,
, , -
193

Ajax,
.
: , ,
-?
.

, , html. ,
, ,
, :
$ ( '# o v e rla y ') .html("<p>You have " + c a rt.ite m s .le n g th +
items in your ca rt.< /p > ");


, ,
, JavaScript ( cart.item s
, ). , ,
: Ajax,
, , . . ,

.

HTML-
, .
, ,
JavaScript
j Query, . ,
,
HTML j Query-.
HTML-
, :
<div id = 'o v e rla y >
<p>You have <span id= ,num-items,>0</span> items in your cart.</p>
<p>Total cost is $<span id= total-cost'>0</span></p>
</div>

HTML . ,
j Query :
S ( t h is ) .fin d C ' #num-i terns' ) . t e x t (ca r t . i terns.1ength);
$(th i s ) . f i n d ( 'f t o t a l- c o s t ') .te x t(c a rt.g e tT o ta lC o s t()):

, :
HTML-, .
, .
( ),
, j Query. ,
,
194 6. , Ajax

, -,
, , ,
,
.
, -
, StarTrackrI.
jQuery.
HTML-,
j Query-.
, ,
. ,
, j Query .
d isp la y :
none :, .
chapterJ)6/01_client_side_templating/index.html ()
<table id -"ca rt">
<thead>
<tr>
<th>Name</th>
<th>Qty.</th>
<th>Total</th>
</tr>
</thead>
<tr cla ss= Mtemplate" style = "d isp lay:n on e; ">
<td><span c la s s =,,item_name">Name</span></td>
<td><span class="item_qty">Quantity</span></td>
<td><span class= ite m _ to ta l>Total</span>.00</td>
</tr>
</table>

,
. ,
, . tempi ate
jQuery- ,
, (,
, ). ,
HTML- .
chapter_06/01_clientsidetemplating/script. js ()
function tempi ate(row, cart) {
row.find(' .itemjiame') .text(cart.name);
row.find(' .item_qty' ) . tex t(cart.q ty );
row.find(.item_total' ) .tex t(c a rt.to ta l):
return row:

,
.
clone, -
195

j Query. ,
,
DOM.
chapter_ 06 /01 _ clie nt_ sid e _te m p latin g/script.js ()
var newRow - $('# cart .te m p la te ') .clon eO .rem oveC lass( te m p la te '):
var ca rtltem - {
name: 'G le n d a tro n ix '.
q t y : 1.
t o t a l : 450
}:
tempiate(newRow. cartltem)
.appendTo('#cart')
.fadelnO ;
tempi ate , !
( ,
, ), template
. ,
. ,
HTML-, .
? , !
, , ,
, , .
, , ,
, ,
.


, .
,
,
.
, , ,
, .
-, ,
Mustache1, j Query Templates12.

, jsRender3.
,
:
, .

1 http://mustache.github.oom
2 http://api.jquery.com/categorY/plugins/templates
3 https://github.com /BorisMoore/jsrender
196 6. , Ajax

(... !)
,
,
, .
,
, ,
, (
). , ,
, JavaScript
, .
, , ,
, , -

.
:
, ,
! ,
, ,
( ) ,
.
, , jQuery,
. , ,
,
.
$. browser ,
: Internet Explorer, WebKit, Opera Mozilla.
$. brow ser.version ,
, .
, :
if ($.browser.mozi 11 && $.browser.version. ="9.0") {
//
/ / F ire fo x 9.
}
, ,
, .
,
, ,
...


,
, . , Internet Explorer 8
CSS- o p acity (

f i 1te r). ,
Ajax 197

, Internet Explorer,
. Internet Explorer,
opacity!

jQuery $. support,
, .
Internet Explorer?
opacity?:
i f ( ! $ .su pport.opacity) {
// opacity : .
}
, ,
, opacity, Internet
Explorer , -
.
o p a city ,
. , $.su pport. boxModel false ,
(quirks mode) (
), $ . support. 1eadi ngWhi tespace true,
innerHTML, . . ,
, ,
1.

Ajax
- Ajax ,
-,
-.
Ajax ...
j Query!

Ajax?
Ajax 2005 Asynchronous
JavaScript and XML ( JavaScript XML).
, Ajax
, , .

, ,
-.
Ajax ,
, !
Ajax ,
1
http://api.jquery.com/jQuery.support
198 6. , Ajax

, .
, , , HTML-
, .
, ... .
Ajax
, ,
.

-.
Ajax ,
. -
, . , j Query
.
j Query,
DOM,
, ,
Ajax.
, j Query
Ajax, -,
.

HTML-
; ,
StarTrackr!, ,
,
Ajax. Ajax-
jQuery load.
load HTML-
-.
HTML-, ,
HTML-. , :
$ ('div:firs t* ).1oad('test.htm l');
,
Ajax-!
( <body>) te s t. html
di v -.
, HTML-,
.

LOAD?
: load jQuery.
A jax- load, ,
load, , ( , )
.
Ajax 199


Hijax
StarTrackr!.
, ,
.
, ,
. , Ajax,
, ,
, - ,
.
:
,
, StarTrackr!, ,
JavaScript, -
, .
hijax (
, ( hijack)
Ajax, hijax).
, , HTML-
, .
, -,
.
chapter_06/02_hijaxlinks/baronVonJovi. html ()
<body>
<hl>Baron von Jovi</hl>
<p id= "description">
I t 's a l i t t l e known fa c t th at Baron von Jovi ...
</p>
</body>

' -.
, , , ,
,
-.
,
.

LOAD
^ ^ ^ 1
, -, .
- ,
,
-. ,
,
. , JSONP-,
jQ u ery- getJSON. .
200 6. , Ajax

,
StarTrackr!.
-
.
chapter_06/02_hi j a x l i nk s/i ndex.html ()
<ul id="biographies">
<li><a href="baronVonJovi.html">Baron von Jovi</a></li>
<li><a href="computadors.htmr>The Computadors</a></li>
<li><a href="darthFader.htmlM>Darth Fader</a></li>
<li><a href=,,moFat.htmr>Mo' Fat</a></li>
</ul>
<div id=,,biography">
Click on a celeb above to find out more!
</div>
di v.
, Ajax-.
Ajax.
chapter_06/02_hi jax li n k s / s c r ip t .j s ()
$('#biographies a ') .click(function(e) {
var url = $ (th is).a ttr('h re f'):
$('fbiography').load(url);
e.preventDefaultO;
}):

, (
).
, ( href
, ), 1oad.
,
.
<hl>, -,
. ,
Ajax
. jQuery...

HTML-

load j Query
URL-. -,
. ,
-,
, , Ajax-.
Ajax 201

1oad :
,
, :
$( #biography').1 oad('computadors.html d iv :f ir s t'):
,
-, .
StarTrackr! ,
, . ,
.
chapter_06/03_l oadwi th s e l ector/scr i p t. js ( )
var url = $ (th is).a ttr('h re f') + ' #description';
He - #,
. , ,
div. ,
, ,
: 1oadi ng... ,
load.
, loading... , ,
.
chapter_06/03_l oadw ithsel ector/scr i p t. js ()
$(#biography' ) .html( 'loading...

' ) . load(url);
! .
15 ,
load, .

- -
,
, A jax-. , .
, , - ,
!


,
, 1oad. ,
- ; ,
search,
, :
$ ( 'd iv # r e s u lt s ') . lo a d ('se a rch .p h p '. 'q=jQuery&maxResults=10');
202 6. , Ajax

, 1oad, data.
( , ), j Query
GET. , ,
j Query POST.
,
cal 1back.
: ( ), ,
( , ;
), :
$ ('div#result').load(feed.php'. function(data, status, response) {
// !
}):
data, ,
cal 1back data, .
, ,
load.

: on off
Ajax
, . !
, . , ,
?
, . ...
j Query, Ajax:
$( ^ d e s c rip tio n ') .mouseover(function() {
$(thi s ) .css( 'background-color'. 'yellow');
}):
, , , .
-, , ! ?
, :
p#description, , ,
, p#descri pti on !
Ajax . ?
, mouseover
callback Ajax-,
on.
, , ,
,
, . ? ,
,

.
Ajax 203

, ,
mouseover, on, -
( #bi ography) ,
.
chapter_06/04_live event handler/script.js ()
$ ( '#biography' ) . on( 'm ouseover', fu n ctio n O {
$(t h is ) .c s s ('b a ck g ro u n d -co lo r', 'y e llo w ');
}):

C LIVE DIE?
jQ u ery 1.7 liv e die . , ,
on off, ,
, . , ,
link, ! ,
;
A jax-.
, .


#biography ca llb a ck
, . , on
$() .on( . ,
cal 1back ). ,
,
off:
$(#biography ) .o ff( 'mouseover');
P :
mouseover
, .


( ) on,
,
off: $ ( # e l' ) . o f f ( ' c l i c k 1. m y F u n c t io n ) , ,
, . ,
, ,
,
.

$.geUSON
, Ajax-,
,
Twitter -?
204 6. , Ajax

, ,
Web 2.0. , ? ,
Ajax ... .
( )
,
- ( )
. -
XML-,
.
(Application Programming
Interface, API)
. XML
, .
JSON (JavaScript Object Notation JavaScript-,
)
Ajax-. JSON
XML, JavaScript-
.
!
jQuery JSON-: S.getJSON.
URL-
cal 1back. URL- ,
JSON. JSONP,
.
"celebs" Facebook1.
chapter_06/05_getJSON/script. js ( )

$ .getJSON( ' h t t p ://graph . facebook.com/search?q=cel ebs'.


fu n c tio n (re s u lt) {
a le rt('F e tc h e d ' + re s u lt.d a ta .le n g th + ' ite m s !'):
}):
URL?
,
API12.
,
API-!

!
^^^:
, .
, ,
. , "celebs
- , "jQuery"!

1 http://facebook.oom
2 http://developers.facebook.com /docs/referenoe/api
Ajax 205

Twitter-
Facebook? Twitter-,
, .
API- Twitter1, ,
. URL-
JSON-,
.
chapter_06/06_twitter search/script. js ()
var searchTerm = "celebs";
var baseUrl = "h ttp ://se a rc h .tw itte r.co m /se a rc h .json?q=" ;
$.getJSON(baseUrl + searchTerm + "&callback= ?", function(data) {
$ .e a ch (d a ta .re su lts. fu n ctio n O {
$ ( '<di v></div>')
.h ideO
.append('<img src="' + th is.p ro file _ im a g e _ u rl + '" />')
.append( <span><a href="h t t p :/ /www.twi t t e r .com/'
+ th is.fro m _ u ser + '"> + this.from _user
ta* + '</a>&nbsp;' + t h is . t e x t + </span>')
.appendTo('#tweets')
.fa d e ln O ;
}):
, re su lts.

j Query- $. each. ,
.
di v,
, Twitter,
. Twitter-,
!

JSON
getJSON , ,
, , .
( ) .
API-, .
, .
API , URL API -
JSON-.

Ajax jQuery
1oad
jQuery, ,

1
https://dev.twitter.com/docs/api
206 6. , Ajax

$. ajax. Ajax-
jQuery, !
Ajax-, j Query,
$. ajax,
,
.
j Query ,

.
$. ajax Ajax- j Query
Ajax-.
j Query,
,
, ,
Ajax.

, !
jQuery,
JavaScript-, jQuery,
. ,
,
, , ,
. ,
, !

, $. ajax, , ,
, ,
, :
. .
GET:
$.ajax({
type: 'GET',
u r l : 'g e tD e ta ils .p h p '.
data: { id: 142 }.
success: fu n ction (data) {
// !
}:
}):
, URL-
callback success, . .
, ,
. 20 , 11back-
error
,
.
-
Ajax 207

.
,
. .

Ajax

Ajax- .
, j Query
$. ajaxSetup:
$.ajaxSetup({
type: 'POST',
u r l: 'send.php',
timeout: 3000
}):
Ajax-,
.
-
, :
$.ajax({
data: { id: 142 }
}):
POST send.php,
, 3000 .
$. ajaxSetup. , cal 1back-
error, complete success Ajax,
.


$.getScript
-
, , , :
.

, , , ,
, -.
, . ,
, j Query.
S.getScript JavaScript-
Ajax. ?
,
-,
. ,
208 6. , Ajax

, , ,
, .
Color,
3,
j Query:
$.getScri p t( http://gi thub.com/jquery/jquery-
color', functionO {
$('body').animate({'background-color': 'slow');
}):

GET POST
j Query
GET POST. S.ajax
: URL-
!
, HTTP:
$. get GET, $. post POST.
, ( URL-) :
$.get(url, data, callback, dataType);
$.post(url, data, callback. dataType);
data ,
. $. ajax, 11back
, ,
. type ,
callback, : xml, html,
scri pt, json, jsonp text, -
. :
S.getC'getlnfo.php", function(data) {
alertC'got your data:" + data);
}):
$.post("setInfo.php". {id: 2. name: "DJ Darth Fader"});
, , ! S.get
$ post , .
,
. ?


j Query $. get and $. post ,
cal 1back ;
. ,
Deferred jQuery 1.5. Deferred
, .
: -
Ajax 209

. ,
c a ll back. Ajax-
jQuery Deferred
Ajax-.
, ,
done, fa i 1 always.

( , ,
). :
$ .g e t in dex.h tm l")
.done(function(data. statu s, xhr){
//
}) .
.fa il( fu n c tio n ( d a ta , statu s. xhr){
//
})
.alw ays(function(data, statu s, xhr){
// ,
}):
j Query ,
cal 1back
success, fa i 1 compl ete $. ajax.
,
Deferred.
$ .ajax ( ,
Ajax; ).
done , Ajax- ; fa i 1
, - ; always ,
,
.
, (, success, e rro r timeout),
j Query- XMLHTTPRequest.

JQUERY- XMLHTTPREQUEST
Microsoft XMLHTTPRequest Internet Explorer
Ajax.
. jQuery
, Ajax-
callback .
.
.

Ajax- jQuery
Ajax- jQuery
. ,
- , ,
210 6. , Ajax

1oadi ng ,
, , .
j Query Ajax-: .
Ajax-.
cal 1back, ,
, .
, ,
, ,
, .
j Query :
fail ajaxError. error
, ajaxError ,
.
$. ajax, :
$.ajax({
u rl: "test.html".
}):
.fail(functionO {
alertCan error occurred!'):
}):

DOM, . ,
, di v
Ajax:
$("#msg").ajaxError(function(event. request, settings, ex) {
$(this).html("Error requesting page " + settings.url + "!");
}):
, Ajax- -
, .
, : ,
. ,
.
,
.
done () ajaxSuccess () ,
. always () ajaxComplete ()
, Ajax- ,
, .
success, error, complete always.
beforeSend () ajaxSend ()
, Ajax- . ,
ajaxStart ajaxStop , Ajax-

.
: Ajax 211


,
Ajax.

: Ajax
! , ,
. ,
JavaScript, Ajax-.

!
.
, StarTrackr!
. -
,
, .
StarTrackr! :
, .
,
.

Ajax
StarTrackr!
.
,
, .
Ajax
. .
Ajax
.
,
. XML, JSON
- ?
?
? ,
?

. ,
,
-, .
:
computadors. jpg | night_out. jpg |mr_speaker. jpg | dj_snazzy_jeff. jpg
212 6. , Ajax

- XML JSON,
, API-
,

. JavaScript
: data.splitC | '):.
, .
-
di v, . HTML-
.
chapter_06/07_ajax image gal 1e ry/in d e x: html ()
<div id="gallery"></div>
GALLERY,
. :
, URL- (
) . ,
.
chapter_06/07_ajax_image_gal1e r y / s c r ip t .j s ()
var GALLERY = {
container: "Igallery".
u rl: "getImages".
delay: 5000,
load: functionO {
//
}.
display: function(image_url) {
//
}
}:
Ajax.
GALLERY, Ajax-
cal 1back this
GALLERY.
jQuery
,
, :
var _gal 1ery = this:.

get Images ,
. ,
. ,
Internet Explorer Ajax-,
. ,
. , ,
, !
: Ajax 213


$. get, , ,
S.ajax.
callback, success.
,
:
chapter_06/07_a j a x i m agegal 1e ry /sc r i p t . j s ( )
load: functionO {
var _gallery = this:

$.ajax({
type:"get\
u rl: th is .u rl.
success: function(data) {
var images = data.s p lit( ' | ');
$. each (images, functionO {
_gal1ery.di splay(thi s ):
}):
}
}):
}

'
$.each jQuery-
, JavaScript- ,
callback .
callback ,
.

, ,
i mg .
cal 1back- success 1oad,
,
.
.
display URL-
- .
chapter_06/07_ajaxim agegal 1e r y / s c r ip t . j s ()
display: function(image_url) {
$( '<imgx/img>')
.a ttrC s rc ', '../../im ag e s/' + imagejjrl)
.hideO
.load(function() {
$( thi s ) .fadelnO;
})
,appendTo(this.container);
214 6. , Ajax

load, , GALLERY.load
j Query- 1oad.
, fadeln.
, . ,
, GALLERY, load (),
( ).
chapter_06/07_ajax image gal 1/s c rip t. js ()
$(docum ent).ready(function {
GALLERY. loadO :
}):

( Safari)
jQuery (1.7.1 ),
, ,
, ! Google Chrome,
,
; ,
.
HTTP- -,
, , 1.
, Unix1 2.


-, ,
Ajax- ! ...
,
-. , Ajax!

,
.


, ,
:
.
, ,
.

: -
, JavaScript, Image Gallery (

1 http://www.apactiefriends.org/en/xampp.html
2 http://code.google.com/p/chromium/issues/detail?id=40787&q=ajax%20local8icolspec=ID%20Stars%20Pri%2
OArea%20Feature%20Type%20Status%20Summary%20Modified0/o20CPwner0/o20Mstone0/o200S
: Ajax 215

) . ,
,
Ajax,
JavaScript.
,
,
. ,
load .

. ,
,
. (,
set Interval),
,
,
.
, ,
. , callback-
success? : ,
? cal 1back- success
,
.
complete $.ajax.
Ajax , complete
, ,
, . .
chapter_06/08_a j a x i m a g e g a l 1ery im proved/script. j s ( )
complete: functionO {
setTimeout(function() {
_gal1ery.load():
}. _gallery.delay):
}
setTimeout , ,
GALLERY. 1oad. di spl ay
- ,
-.
! ,
, . ,
. success
, .
, ,
,
.
.
216 6. , Ajax

beforeSend.
, .
chapter_06/08_ajax_image_gallery_improved/script. js ()
beforeSend: functionO {
$(_gallery.container)
.find('im g')
.fadeOutC'slow'. functionO {
SCthis) .removeO:
}):
}

, .
cal 1back fadeOut ( ,
), -.
.

. -
, HTML-
,
J avaScript.

, ,
Ajax,
G lF-! , ...


,
-;
, Ajax-
.
JavaScript- ,
- JavaScript.
,
, .
, .
GIF--
HTML- CSS-. :
JavaScript, -,
GIF-.
, !
: JavaScript,
JavaScript!
.
, ,
img.
CSS.
: Ajax 217

chapter_06/09_ajaxgal 1erywi th s p i nner/gal 1ery. css )


,spinner{
height: 100*:
background: transparent u rl( . . / . ,/css/images/spinner.gif)
^no-repeat center center;
}
befreSend ,
Ajax-. ,
,
, -.
,
.
chapter_06/09_ajax_gallery_with_spinner/script.js ( )

$ ('<di v></di v>')


.a ttr ( 'c la s s '. 'spinner')
.hideO
.appendTo(_gal1ery.container)
.fadeTo('slow'. 0.6);
, , Ajax-
, .
compl ete,
.
, ,
.
chapter_06/09_ajax_gal lery w ith sp in n er/scrip t.js ( )

$ ( '.spinner') .fadeOut('slow', function {


$(this).remove();
}):


,
,
, .
, ,
sleep, ,
. , s 1(4);,
4 .
.

()
-,
Ajax-, Ajax-
, .
, ,
Ajax-. ,
218 6. , Ajax

Ajax-, .
, .
, ,
( ,
, ,
-). ,
, .
chapter_06/10_globaleventhandlers/gal1.css ()
.progress {
background: # fff u rl(p ro g re s s .g if) no-repeat center rig h t:
}
Ajax ajaxStart ajaxStop.
, a ja x S ta rt , Ajax-
, a ajaxStop
, .
.
chapter_06/10_global eventhandlers/script.js ()
$ ( '# ajaxIn P ro gress')
.a ja x S ta rt(fu n c tio n O {
$ (th is ).a d d C la s s ('p ro g re s s );
})
.ajaxStop( fu n ctio n O {
$ (th is ) .removed ass ( 'p ro g r e s s ') :
}):



,
Ajax, - .
, ,
.


Ajax
. : ,
.
- Next ()
.
,
:
, , RSS-, ...
.
.
, . -
: Ajax 219

,
. StarTrackr!
,
. , ,
, 10
1037 .
Ajax-,
setTi meout compl ete. ,
, .
, ,
, , , .
overflow:auto
.
GALLERY: ini t ( )
, checkScroll (),
scrol 1.
q h a p te r_ 0 6 /ll_ e n d le ss_ sc ro llin g /sc rip t.js ()
in it: function() {
var ^gallery = this:
$(this.container).scroll(functionO {
_gal 1ery. checkScrol 10;
}):
this.JoadO ;
}.
GALLERY,
.
3, scroll
.
c h a p te r_ 0 6 /ll_ e n d le s s s c ro l1in g / s c r ip t .j s ()
checkScroll: functionO {
var gallery_div = $(this.container);
if (gallery_div[0].scrollHeight - gal 1ery_div.height0 -
ta*gallery_div.scroHTop() <= 0) {
this.loadO ;
}
}
checkScrol 10 ,
. ,
- ,
,
( , j Query
,
).
,
.
220 6. , Ajax

j Query JavaScript, scroll Height


JavaScript-,
. , height,
,
, -.
,
DOM j Query; [0].

scrol 1Height ,
. 0,

.
,
-? - ?
, ! ,
, !
,

GALLERY running.
, ,
running true. , , Ajax-
, ,
return. fa ls e , ,
true.
, ( ),
running fa ls e .
chapter_06/ll_endless s c r o l1i n g / s c r ip t .j s ()
var GALLERY = {
running: fa ls e .

load: fu n ctio n O {
// He , !
i f (th is.ru n n in g ) {
return;
}
th is.ru n n in g = true;

var _ g a lle ry = th is ;
$.ajax({

complete: fu n ctio n O {
ga lle ry .ru n n in g = fa lse ;

}):
'}
: Ajax 221


, GALLERY,
var gal 1 = this:.
,
: ajax context,

:
var GALLERY =.{
u r l : "getlm ages",
load: fu n ctio n O {
$.ajax({
ty p e :"g e t",
u rl: t h is . u r l,
context: t h is ,
success: fu n ction(data) {
// " th is " GALLERY'
a le r t ( loaded ' + t h i s . u r l ):
}
}):
}
}:
.
, j Query
. (, $. each,
) -
JavaScript,
. context
, ,
, j Query
DOM:
$("<div>") .a t tr ("id", "result") .appendTo("body");
$.ajax({
type: "get",
u rl: "G etR esults.htm l",
context: $ ("# re su lt"),
success: fun ction (data) {
// " th is " # result
th is .h tm l(data):
}
}):


Ajax
. .
. ,
222 6. , Ajax

. ,
, .
,
.
! ,
. , ,
- . ,
,
.
,
, , Ajax- ...
. ^
GIF-.
: -? ?
,
-? JavaScript (
, , ),
,
.
jQuery ,
.
Ajax , ,
.
,
$. ajaxSetup timeout.
20 :
$.ajaxSetup({
timeout: 20000
}):
,
( ) ,
:
$ .a ja x ({
timeout: 4000,

}):
,
? j Query , .
e rro r , - , ,
.
, ,
XMLHTTPRequest ,
; timeout, e rro r (
HTTP- 404) p arse re rror (
XML JSON).
: Ajax 223


, .
setTimeout
1 (
, ,
).

chapter_06/12_ajax_error_handling/script. j$ ()
var GALLERY - {

delay: 1000,

load: functionO {

var _gallery = this:


$.ajax({
type:"get",
u rl: th is.u rl,

error: function(xhr, status) {


setTimeout (functionO {
_gallery.load():
}. _gallery.delay);
}
}
}):
, 1oad,
error, 1oad... ,
. ? , !
10. , , ,
11- , - :
!
:
, attempts.
( ),
.

chapter J)6/12_ajax_error_handling/script. js ()
var GALLERY = {

delay: 1000,
attempts: 3,

reset: functionO {
this.delay = 1000:
this.attempts = 3:
}.

}
224 6. , Ajax

reset
- .

.
chapter_06/12_ajax error handling/script. js ()
error: fu n c tio n (x h r, status) {
i f (_gallery.attem pts-- == 0) {
// , .
_ g a lle ry .re s e t():
return:
}
setTimeout(function() {
_ g a l l e r y . lo a d ( ) :
}, _ g a lle ry .d e la y *= 2);


-- ++ JavaScript-,
1. +*,-
.

, ,
attempts. ,
0, .
setTimeout:
1oad. ,
1 ,
2 , ,
4 . ,
:
,
, , .

!
,
, !
.
, , ,
, ,
.


, . ,
,
ajaxError -,
- ,
,
.
: Ajax 225


,
Ajax StarTrackr! ,
, .
,
.
, , , , .
,
, -
. , ,
, .
XML
: ,
, .
,
-, ,
, . .
, ,
, XML
, .
JSON
, -
, XML. XML ,
JSON,
. JSON- ( ,
, JavaScript-, ), j Query
L- .
:
<?xml version"].." encoding="UTF-8"?>
<celebs>
<celeb id="42r>
<name>Johnny Stardust</name>
<image>johnny_200.jpg</image>
</celeb>
<celeb id="422">
<name>Kellie Kelly</name>
<image>kel1ie_200.jpg</image>
</celeb>
</celebs>


, .
, XML-,
, XML-, ,
. dataType: ' Ajax-
contentType.
226 6. , Ajax

, ,
.
$. each.
. XML-,
. , j Query
XML- , DOMI
, j Query
DOM , . ,
, fi nd() , a next prev
-.
chapter J)6/13_consum ing_xm l/script.j s ()
success: function(data) {
$(data)
.fin d ('celeb s')
.childrenO
.each(function() {
var node = $(this);
var id = node.a t t r ( ' id '):
var name = node.find('name').text();
var image = node.find('image'J.textO;
_gallery.display({'id': id. 'image': image, 'name': name}):
}):

cel eb i d,
URL- ,
di spl ay ( JSON-
JavaScript-!).
display ,
data, .
data , ,
, i d,
. i mg j Query-
data.
, ,
,
: alt,
.
chapter_06/13_consuming_xml/script.j s ()
display: function(dataltem) {
$('<img /> )
.attr({
src: '../../im a g e s/' + dataItern.image,
alt: data Itern.name
})
.hideO
: Ajax 227

.d a ta ('id '. dataltem.id)


,load(function() {
$(thi s ) .fadelnC):
})
,click(function() {
CELEB.1oad($(thi s ) .data( id ')):
})
.appendToC '#');

DOM
: ,
id click.
i d,
: .
GALLERY,
.
CELEB,
.
chapter_06/13_consuming x m l/ sc rip t. js ()
var CELEB = {
u rl: 'celebs.json',

load: function(image_id) {
var _celeb = this:
$('#details in p u t').a ttr('d isa b le d '. 'disabled'):
$.getJSON(
th is .u rl.

function(data) {
$ ('#details in p u t') ,removeAttr('disabled'):
_celeb.display(data);
}):
}.
display: function(data) {
$('#id').val(data.id);
$('frame') .val(data.name);
$('# tag s') .val(data.tags.join(" ")):

}
, JSON
JSON, .
i d, , .
$ .getJSON,
beforeSend complete,
, ,
228 6. , Ajax

, .
, ,
a ttr di sabl ed.
, di spl ay
. Ajax-! ,
JSON-
, .
celebs, json
.


, , ,
, ,
,
!
, j Query:
, .
(,
) , /
.
, Ajax- jQuery
: , ,
serialize.
serialize input, name.
, serial ize, ,
.
chapter_06/14_sending_form_data/index.html ()
< form >

<input type="text" ="" />

<input type="text" name="tags" />

<input type="hidden" name="id" />

<input type="button" value="update" />

</form>
, serial ize
jQuery- :
var form_data = SC'form") .serialize();
,
name , (&):
name=Kellie+Kelly&tags=b-grade+has-been+rich&id=8
: Ajax 229

,
serializeArray.
, ( ),
/ .
:
chapter_06/14_sending form data/script. js ()
update: functionO {
var form_data = $('form') .serialize();

$.post(this.set_url, form_data, functionO {


$ ('#status') . te x t( ' Update successful! ):
}):

, $. post ! ,
, , - ,
.
S.ajax. ,
Update Successful!,
.
chapter_06/14_sending_form_data/script. js ()
$.ajax({
type: "POST",
u rl: th is .u rl.
data: form_data,
error: functionO {
$ (# statu s').te x t( Update failed. Try again.').
ta*slideDown('slow');
}.
success: functionO {
$ ('#status').text('U pdate successful!');
}.
complete: functionO {
setTimeoutC functionO {
$('I s ta tu s ') .slideUpC'slow');
}. 3000);
}
}):
, ,
setTimeout, complete
,
. , ,
update, Submit ().
chapter_06/14_sendi ng_form_data/script. js ()
$ ('#update').click(function() {
CELEB.updateO:
}):
230 6. , Ajax


, ,
.
, Console
() Firebug (
console.log 4). Ajax-,
-, ,
,
. 6.1.

C o n so le - HTML CSS Script DOM N et

T G E T http:// 127.0.0. 1:8000/jqury -bo o k-co de /cha p ter_ 06/08_ajax_gallery_w ith_spinner/getlm ages
H ead ers R esponse

| jo h n n y _ 2 0 0 . j p g j k e l l i e _ 2 0 0 . j p g \m o la t _ 2 0 0 . j p g | beau__20Q . j p g | fa d e r^ _ 2 G 0 . j p g jg le n d a _ 2 0 0 . jp g

G E T http:// 127.0.0. 1:8000/ jq u e ry-b o o k ro d e/ ch a p te r 06y08_ajax g a lle ry with sp in n e r/ g e ilm a q e s ?! OK 24m*

. 6.1. A ja x- Firebug

Ajax
? !
, . ,
: ,

-.
. , !
Ajax ( ) ,

. , , ,
Ajax. j Query
. ,
API- JSON
, ,
!
,
7

,
. - . ,
, ,
-,
, ,
. HTML- ,
-,
.
JavaScript HTML-
,
,
. jQuery

.
, !
,
. , Ajax,
, , ,
, , ,
1999 , . ,
, ,
, .

, - , !
, jQuery - .

HTML- . .
-. JavaScript
-.
232 7. ,

, JavaScript - , j Query
!
, :
DOM, j Query
. DOM-
, j Query
.
, .
, , j Query
HTML5. HTML5
,
JavaScript. ,
HTML5; ,
j Query
, HTML5 -
.
, ,
.


, ,
.
, .
-, ,
?


^ ^ jQ u ery ,
,
, .
, JavaScript,
jQ u ery-, ,
. , , ,
,
. O pen W eb Application Security Project
1.

jQuery , .
,
! ,
, HTML , HTML5
,
.

1 http://owasp.org
233

j Query
, getEl ementsByCl assName
, .
querySel ectorAl 1 ,
. ? ,
, querySel ec to rA l 1 (qSA)
, ,
, HTML5,
, . qSA
, , , j Query
:
$ ('input[type-text]') . css( 'background-col o r', '1emonchi ffon')
j Query
CSS, ,
.
: input :te x t .
- ,
, . , ,
, . 7.1.

'
T est O p s/

type j 21,297
SC " [type' password ] " ) ; 0.84%
p a ss w o rd
20% slower

fitter 2,388
S C password"); 0.64%
p a ss w o rd
91% slower

11,689
in p u t fitter
S( " i nput: pas swo rd ); 0.64%
p a ss w o rd
56% slower

fitter m ethod 13,516


SCin p u t " ) . f it t e r C " :passw ord"); 0.61%
p a ss w o rd
49% slower

26,538
in p u t typ e
SC "inp ut[type password ] " ) ; 1.11%
p a ss w o rd
fastest

. 7.1 .

, : password ,
, ,
, 13 589 .
i nput[type=' password' ], 13 000
. 26 000
, .
234 7. ,

input[type='password' ] :password ,
.
[type= radio' ], [type= image' ]
[type='submit']. , , ,
.
, ,
. :enabled :disabled
di sabl ed, :checked : sel ected
, ,
, ,
.

w rCHECKED SELECTED
,
,
. ,
i f ( $ ( t h i s ) . i s ( c h e c k e d ' )).

;,
, .
val ,
.
, .
chapter_07 /0 l_si mpl e__val i dat i on/scri p t. js ()
$ ('#myform') .bind('submit'. function(event) {
$([type=text]) .each(function() {
if(!$(this).val().length) {
event.preventDefault();
$(th is ) .css('border', '2px solid red');
}
}):
}):

, , ,
.
val ,
.
, ,
.
chapter_07/02_radio_buttons/script.js ()
$ ( '[type=i nput] ' ).change(function(){
alert($(this).val());
}):
$ ( '[name=sex]' ) .b in d ('click ', function(){
alert($(thi s ) .val()):
}):
235

change
. ,

, .
. change
,
, . .
change
,
, . change

, .
, .
,
.
blur, , .
.
chapter_07/03_simple_inline_validation/script.js ()
$ ( ' : input*) .b lu r(fu n c tio n () {
i f ( $ ( t h i s ) . v a l 0 .length == 0) {
$ (th is )
.addClass( ' e r r o r ' )
.after('<span class="error">This f i e l d must ... </span>');

}):
$ ( ' : in p u t ' ) . fo c u s (fu n c tio n () {
$ (th is )
.removedass( e r r o r ' )
.next( 's p a n ')
. removed;
}):
, ,
.
.

, ,
.

, m !
, ,
: ! ,
, ,
.
, , ,
,
, , !
236 7. ,

...
, HTML5 JavaScript
.
HTML5 requi red
:
<input value="Jemima" placeholder="Best new talent" required>
. -, ,
, -, ,
API-
. , ,
!
. 7.2 ,
.
, , - ,
. ,
,

.

T h is is a r e q u ir e d fie ld

^CZirZZZ)
Ifjl Please fill out this field.

...... .....J
Please fill out this field

. 7.2.

, j Query
, .
237

submit
submit,
. , ,
click Submit (),
, ,
Enter. -
event .preventDefault , ,
, .
, ,
. - ,
-.
chapter_07/04_submit_event/script.js ()
$("form").submit(function(event) {
var error = false;
$(this).find("[type-text]").each(function() {
if ($(this).val().length {
alert("Textboxes must have a value! ");
SCthis).focus 0 ;
error = true;
return false; // "each"
}
}):
if (error) {
event. preventDef aill t ():
}
}):
, ,
, ,
.
,
jQuery ,
.
, ,
, ,
.

, , , Validation.


Validation

: , , ,
,
. Validation
238 7. ,

,
.
,
( !),
.
.
,
, .
ch apter_07/05_validation plu gin/in dex.htm l ( )
<div id="signup">
<h2>Sign up</h2>
<form action="">
<div>
<1 abel for="nameM>Name:</label>
<input name="name" id="name" type="text'7>
</div>
<div>
<1abel for="emair>Email :</label>
<input name="email" id="email" type="text"/>
</div>
<div>
<1abel for="website">Web site URL:</label>
<input name="website" id="website" type="text" />
</div>
<div>
<1abel for="password">Password:</label>
<input name="password" id="password" type="password" />
</div>
<div>
<1abel for="passconf">Confirm Password:</label>
<input name="passconf" id="passconf" type="password" />
</div>
<input type="submit" value="Submit!" />
</form>
</div>
Validation,
validate ,
. rules,
.
chapter_07/05_val i d a t i o n p lu g i /s c r i p t . j s ( )
$('#signup form'). validated
rules: {
name: {
required: true
}.
email: {
required: true.
239

email: true
}
website: {
u r l: true

password: {
minlength: 6.
required: true
b
passconf: {
equal To: "#password"
}
}.
success: function(label) {
label.text('OK!' ) . addClass( 'v a lid ');
}
}):'
,
, , ,
. ,
. requi red, email, url, minlength
nequalTo.
required ,
, email url
: @, URL-
h ttp :// . . rules
, name , minlength (
) (, ,
maxi ength). , equal -
Tpj Query, ,
.
Validation 1abel
, .
error,
.
Validation ,
. , ,
,
, , .
cal 1back- success
label, ,
, .
success ,
, . , , . 7.3.
,
, localization
Validation .
240 7. ,

Nam e:
Mr Speaker #

Em ail:
this is not an email Please enter a v a lid em a il a d d ress.

W eb site URL:
http://sitepoint.com

Passw ord
0

C o n firm Passw ord:


Please enter the sam e v a lu e again.

{ Submit! J

. 7.3. V alid a tio n

,
Validation.
, ,
.
, .



140 . Twitter? . ?

... ,
, Twitter.
,

, .


, .
maxi ength textarea,
. span,
.
chapter_07/06jnax_length_indicator/script.js ()
$ ( .maxiength')
.a f t e r ( "<span></span>")
.nextO
.hideO
.end()
.keypress(function(event) {
//
}):
241

span , textarea -
. span,
next.
span,
, end. end
jQuery , ,
. hide,
next. , end,
, next.
, keypress.
, .
,
, ,
.
chapter_07/06_m axjength_indicator/script. j s ()
var current = $(this) .val .length;
if (current >= 130) {
if (event.which != 0 && event.which ! 8) {
event.preventDefault();

: JavaScript- length ,
.
,
preventDefault .
keypress which,
ASCII- . ,
Delete () ( ASCII
0) Backspace () ( ASCII 8)
. ,
, ,
, .
chapter_07/06_max_length in d ic a t o r / s c r ip t .j s ()
$(th is) .nextO.showO .tex t(130 - current);

span, . ,
, ,
, ,
. , , span,
, 140- .
, -
, ,
, ,

.
242 7. ,


, ,
-, ,
. ,
, .
, .
.
, -
, .
,
.
, ,
,
, ,
. . 7.4,
, , ,
.
, , .

. 7.

, data,
. - pi acehol der,
: -
, , ,
CSS .
, , pi acehol der
, , data.
data ,
, ,
.
chapter_07/07_form_hints/script.js ()
$ ( ' i n p u t . c l e a r ' ) .e ach(function() {
$ (th is)
.data( ' d e f a u l t ' . $ ( t h is ) . v a l ( ) )
.a d d C la s s ('in a c t iv e ')
.focus(function 0 {
$ ( t h is ) . r e m o v e d a s s ( 'in a c t iv e ');
i f ($(t h i s ) . v a l () === $ ( t h i s ) . d a t a ( ' d e f a u lt ' ) ||
* * $ f t h i s ) . v a l ( ) === ' ' ) {
243

$(thi s ) .val( '') ;

})
.blur(function() {
if ($(th is) .val() == '') {
$(thi s ) .addClass( 'in ac tiv e') .val($(th is).d ata ('d e fau lt')):
}
}):
}):
,
. focus blur;
,
. focus ,
. , ,
.
, , ,
, .
- ,
.
.
, j Query , HTML5
,
.


, ,
. ,
, StarTrackr!: ,
,
.
, .
,
Check all ( ),
.
j Query- ,
.
.
HTML-
.
chapter_07/08_check_al1/i ndex.html ()
<div class="stats">
<span class="title">Reason for Celebrity</span>
<input namereason"
type=Mcheckbox" value="net" />Famous on the Internet<br/>
<input name="reason"
244 7. ,

type="checkbox" value="crim" ^Committed a crime<br />


<input name="reason"
type="checkbox" value="model" />Dates a supermodel<br />
<input name="reason"
type="checkbox" value="tv" />Hosts a TV show<br />
<input name="reason"
type="checkbox" value="japan" />Big in Japan<br />
<hr />
<input class= "check-all"
name="reason" type="checkbox" /><span>Check all</span>
</div>


check - 11. :
, .
,
, .
, ,
:checkbox[name=reason].
,
checked, ,
. ,
, checked
,
, .
chapter_07/08_check_al 1/s c rip t. js ()
$ ( ' . c h e c k - a l l :checkbox ) .change(function() {
var group = ' :checkbox[name=' + $ ( t h is ) . a t t r ( 'n a m e ') +
$ (g ro u p ).a ttr('c h e c k e d '. $ ( t h is ) . a t t r ( 'c h e c k e d '));
}):


- ,
DOM
. , - , ,
, ,
context jQuery, , jQuery.
context 8.


( )
, -
Ajax .
, .

.
245

.
:
, , -,
, .
, ,
( ).
,
, , -
.
,
, ,
. ,
textarea,
.
.
, .
, ,
input ( editable), ,
, textarea ( editable-area).
, i d.


.
chapter_07/09_i nl i n e e d i t i n g/i ndex. html ( )
<h3 id="celeb-143-name" class="editable">Glendatronix</h3>
<p id - celeb-143-intro" class="editable-area">
When Glendatronix floated onto the scene with her incredible debut ...
</p>
, .
hover, ,
, (
).
click,
, ,
, .
chapter_07/09_i nl i n e e d i t i n g /sc ri p t . j s ( )
$(".editable, .editable-area')
.hover(function() {
$(this).toggleClass('over-inline');
})
.c lick (fu n c tio n (e v e n t) {
//
}).b lu r(fu n c tio n (e v e n t) {
/ /
}):
246 7. ,

. edi tabl -, .
,
, $editable (
). a c t iv e - i n l i n e
hasClass. a c t iv e - in l ine ,
. ,
.
chapter_07/09_i nl i needi t ing/script. js ()
//
var Seditable = $ (th is );
i f (S edita b le .h a s C la s s ( a c t i v e - i n l i n e )) {
return;
}
, .
html ,
$.trim,
. , , HTML-
,
, .
,
repl .
.
input ,
textarea
. , ,
!
active, :
,
. empty.
remove, , empty
, .
chapter_07/09_i nl i needi t i ng/ scri p t. j s ( )
var contents = $.trim($editable.html().replace(/\/p>/g,'7p>\n\n"));
Seditable
.addClass('active-iniine')
.empty();

J S * EMPTY REMOVE
, jQuery, ,
remove empty,
, , ,
. , , ,
. ,
.
247

, textarea.
edi table , ,
( ,
editable-area).
,
, .
chapter_07/09_i nl i needi t i ng/scri p t. js ( )
// ,
var editElement = $editable.hasClass('editable') ?
fc*'<input type="text" />' : '<textarea></textarea>'

//
S(editElement)
.val(contents)
.appendTo($editable)
.focus 0
.blur(function(event) {
$editable.trigger( b lu r');
}>:
trigger.
(
Seditable.blurO,
). tri gger ,
, .
tri gger :
, ,
. . i nput
,
.
input.
(
).
.
tri gger bi nd. bi nd
. ?
click, hover, ready
. . , ,
bind.
bi nd , ,
, callback, .

, . ,
, editable
.editable-area: cl ick, hover bl ur. ,
bind:
248 7. ,

$ ( '.editable, .editable-area') .bind({


hover: function(e) {
// hover
}.
click: function(e) {
// click
}.
blur: function(e) {
// blur

}):
: ,
.
$. post,
Saving... (...). POST ,
. Ajax-,
,
, save. ,
, ,
, .
c h ap te r_ 0 7 /0 9 _ in lin e _ e d itin g /sc rip t.js ()
.blur(function(event) {
//
var Seditable = $ (th is);

var edited = Seditable.findC :first-chi 1d'). val ():


Seditable
.c h ild re n O
.replaceWith('<em c la s s = "a ja x ,,>Saving ... </em>');

//
$.post(' save'.
{id: S editable.attrC id'), value: edited}.
function(data) {
Seditable
.removeClass('active-inline')
c h ild re n O
. rep laceW ith (ed ited );
i f (S e d ita b le .h a s C la s s ('e d ita b le -a r e a ')) {
ra p tu re (Se d itab le );
>
}
);
}):
j Query,
. replaceWithO ,
, , . :
249

,
, , ,
!
rapture,
$editable.
i f ,
texta. ,
,
j Query- contents.
chapter_07/09_inl ine editing/script. js ()
var rapture = function (which) {
$(which).contents() .filter(function() {
return this.nodeType === 3;
})
.wrap(<p></p>')
.end()
.f i 1te r ( br')
.removeO
.end()
.end()
.childrenO .filter(function() {
$(this) .html($.trim($(this) .htmlO .re p la c e (/(\t|\n )/g ."")));
return !$(th is ) .textO .length
}). removeO;
}
, j Query, , ,
, contents. chi 1dren
, .
, children
, contents ,
. ,
, texta :
. ?
,
contents. nodeType, 3, ,
,
, .
end. end contents,
br f ilte r
remove. remove,
DOM, ,
end, .
end, ,
$(which).
chi 1dren ,
, $( which). ,
250 7. ,

.
f 11ter
.
trim,
repl . ,
HTML. , .
:
Lorem ipsum dolor s it amet. consectetur adipisicing e lit, sed do
eiusmod tempor incididunt ut labore et
dolore magna aliqua.<br /><br /> .
Ut enim ad minim veniam. quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
<br /> <br />
Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur.
:
<p>Lorem ipsum dolor s it amet, consectetur adipisicing e lit, sed do
eiusmod tempor incididunt ut labore et dolore*magna aliqua.</p>

<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco


laboris nisi ut aliquip ex ea commodo consequat.</p>

<p>Duis aute irure dolor in reprehenderit in voluptate velit esse


cillum dolore eu fugiat nulla pariatur.</p>
, ,
, .
,
, ,
- ,
!

Autocomplete

, .
, ,
-
Last known whereabouts (
), ,
, .
; . 7.5.
jQuery UI 1.8 .
Autocomplete,
jQuery;
, , -
251

, .
j Query 1.7, ,
,
. .

Last known whereabouts:


R 1055)

. 7 .5 . Last kn o w n w h e re a b o u ts ( )

Autocomplete.
, 1,
, -.
, CSS-.
Autocomplete CSS-,
0 , .

.
Autocomplete
.
1ocat i on .
chapter_07/10_autocomplete/index.html ()
<label for="location">Last known whereabouts:</label>
<input type="text" id="location"/>

, Autocomplete.
,
. , ,
HTML- -.
chapter_07/10_autocomplete/script. js ()
var c i t i e s = [ ' P a r i s ' , 'New York', 'M ila n ', 'Stockholm'... ];
$ ( '# lo c a t io n ') .autocom plete(cities.{
a u t o F i l l: true,
s e l e c t F ir s t : true,
width: '240px'
}):
JavaScript-, Autocomplete
URL-,
Ajax. Autocomplete

1 http://docs.jquery.com/Plugins/AutDcomplete
252 7. ,

, .
,
!
,
,
. a u t o F ill
( ,
), a matchContai ns
,
, . ,
.
Autocomplete result,
- . ,
,
( ). , ,
:
$( '#1 o c a tio n ')
.a utocom plete(cities)
.resu lt(fu n c tio n (ev en t. sele ctio n ) {
a le rt(s e le c tio n );
}):
, .
, !
, jQuery UI,
(. 7.6).

Last known whereabouts:


](AddT)
Milan
Stockholm

Melbourne
Montreal
Mexico
Madrid

. 7.6. Last k n o w n w h e re a b o u ts ( )
jQ u e ry UI

,
jQuery UI, Autocomplete.
253

1.8, . ,
! HTML CSS;
.
.
chapter_07/10a_uiautocomplete/script. js ()
var cities = ['P a ris', 'New York', 'Milan', 'Stockholm' ... ];
$('#location') .autocomplete({
source: cities
}):
,
, .
jQuery . ,
-,
, 1.
, ,
. , ,
.




.
, - ,
. ,

. ,
.
,
. ,
. 7.7.

|
j Submit Rating I

. 7.7.


. ,
.
,
, .
1 http://blog.jqueryui.com/2010/08/extensible-autx)completE
254 7. ,

chapter_ 07 /ll_ star_ratin gs/ind e x.h tm l ()


<div class="stars">
<label for*"rating-l"><input id=Mrating-1" name*"rating"
^type-"radio" value-'T7>0.5 Stars</label>
<label for="rating-2"><input id="rating-2" name="rating"
^type*" radio" value="2"/>l Star</label>
<label for="rating-3"><input id*"rating-3" name*"rating"
ta^type*" radio" value="3"/>1.5 Stars</label>
<label for="rating-4"><input id*"rating-4" name="rating"
^type*" radio" value="4"/>2 Stars</label>
<1abel for="rating-5"><input id*"rating-5" name="rating"
fc*type="radio" value*"5"/>2.5 Stars</label>
<1abel for="rating-6"><input id="rating-6" name*"rating"
fc*type-"radio" value*"6"/>3 Stars</label>
<1abel for="rating-7"><input id="rating-7" name="rating"
ta*type="radio" value*"7"/>3.5 Stars</label>
<1abel for="rating-8"><input id="rating-8" name="rating"
l^type*" radio" value="8"/>4 Stars</label>
</div>

.
HTML- , CSS,

: , ,
.
HTML-.
j Query ,
.
. ,
JavaScript, , .
, CSS-,
.
( . 7.8),
HTTP-
.

. 7.8. - CSS
255

CSS - CSS ,
.
background-
position.
ch ap te r_ 0 7 /ll_ sta r_ ra t1 n gs/sta rs.c ss ()
.stars div {
background: transparent url(sprite_rate.png) 0 0 no-repeat:
display: inline-block:
height: 23px;
width: 12px;
text-indent: -999em:
overflow: hidden:
}
.stars a.rating-right {
background-position: 0 -23px;
padding-right: 6px;
}
.stars a.rating-over {
background-position: 0 -46px;
}
.stars a.rating-over.rating-right {
background-position: 0 -69px;
}
.stars a.rating {
background-position: 0 -92px: }

.stars a.rating.rating-right {
background-position: 0 -115px:
}
,
, . ?
- ! ,
, . ,
.

( )!
,
,
. : ,
, , . HTML-
,
. , ,
. createStars
256 7. ,

.
( addHandl ers),
.
starRati ng.
c h a p te r_ 0 7 /ll_ sta r _ r a tin g s /s c rip t.js ()
var starRating = {
create: function(selector) {
$(selector).each(function() {
//
}):
}
addHandlers: function(item) {
$(item),click(function(e) {
// ,
})
.hover(function {
// ,
//
},function {
// ,
//
}):

}
create ,
, ,
. .
, .

ch ap te r_ 0 7 /ll_ star_ rat1 n gs/scr1 p t.j s ()


$(selector).each(function {
var $1 is t = $('<divx/div>');
/ / ,
$(this)
.fi nd( ' i nput:radi )
,each(function(i) {
var rating = $(this).parent().text():
var Sitem $('<a href="#"></a>')
. a t t r ( 't i t l e ', rating)
.a d d C la ssd X 2 1 ? 'r a t in g - r ig h t ' : ")
.text(ratin g );

starRating.addHandlers($item);
$1ist.append(Sitem);

if (S (this).is(':checked')) {
Si tem.prevAl1 ().andSelf( ) .addClass(' rating'):
}
}):
257

( di v):
, .
: radio,

.


addClass
(. -
- -
4), . ,
- () , .
, ra tin g-right.
.

, addHandl ers,
, .
. ,
, (
:checked). , rating ,
, .
rating ,
.
, ,
jQuery: prevAl 1 andSel f. prevAl 1
-, (
prev, -,
).
-, ,
. andSel f,
. ,
, .


, prevAl 1, jQuery
nextAll, - - ,
. jQuery 1.4
: prevUntil nextUntil.
, - -
( , , ),
, .
, , $ h2: f i r s t ') . nextUntil (' h2 ); ,
h2 - h2
-.
prevUntil nextU ntil,
. ,
next-Unti 1( ' h2'. ' d i v '), div,
2.
258 7. ,

,
.
.
c h a p te r_ 0 7 /ll_ sta r_ ra tin g s/sc ri p t .j s ( )
11
$(this).append(Slist).find('label') .hideO :
,
. .
. ,
CSS-, ,
.
, CSS- .
,
.
c h a p te r_ 0 7 /ll_ sta r _ r a tin g s /s c rip t.js ()
$(itern).click(function(e) {
//
})
.hover(function {
$(th i s ) .prevAl1C). andSel f().a d d d ass(' rating-over');
}.function() {
$(thi s ) .si bli ngs( ) .andSelf( ) .removed ass( ' rati ng-over');
}):
hover :
, ,
rating-over, prevAl 1 andSelf ,
. ,
rating-over. , hover.
click.
c h a p te r_ 0 7 /ll_ sta r _ r a tin g s /s c rip t. j s ()
// click
var $star = $(this);
var SallLinks = $(this).parent();

//
S a llL in k s
.parentO
. f in d C input :ra d io [ v a lu e - + S s ta r .t e x t O + ] )
. a t t ( checked*, tru e );

//
Sal 1Li nks. chi 1dren(). removed ass (' rati ng'):
Sstar.prevAl1 ().andSelf( ) .addClass( ' rating);

// click
e.preventDefaultO;
259

cl ick
.
radio attrib u te , ,
.
, C S S - .
ra tin g , .
, , ,
.
,
.


,
: .
, jQ u e r y jQ u e r y
,
,
H T M L -. ,
,
,
. , -,
!


H T M L
,
. ,
,
. jQ u e r y U I
. ,
,
, jQ u e r y U I
.
? . :
J a v a S c rip t C S S - jQ u e r y U I ,
H T M L , .
.

chapter_07/12_buttons/index.ht1 ()
< fie ld s e t id -"r a d io ">
<input type~"radio" id - " r a d io l" nam e-Yadio" / x la b e l
fc * -fo r Y a d io lH>Find a c e le b rity < /la b e l>
260 7. ,

<input type="radio" id="radio2" name="radio" checked="checked"


^ / x i a b e l for= Mradio2">Report a ce leb rity< /la b el>
<input type="radio" id="radio3" name="radioM /><1abel
^for="radio3">Becom e a ce leb rity < /la b el>
< /fieldset>

, , ,
. .
chapter_07 / 12_buttons/ scri p t. j s ( )
$( '# ra d io ') .bu tton setO ;

?
. 7.9 , .

An d en ... ?

O F in d a celebrity R epo rt a celebrity Become a celebrity

An d en ... ?

F in d a c e le b rity Report a c e le b rity Become a c e le b rity

. 7.9. jQ u e ry Ul

, .
,
- ARIA (Accessible Rich Internet Applications),
.

CelebSpotter (
), ,
. , ,
.
, ,
, .
,
, ,
(datepicker).

JavaScript, .
261

. ,
,
, .
, ,
- . ,
jQuery UI
,
,
.
. 7.10.

Su Mo TU W Th Fr Sa Su Mo Tu We Th Fr Sa

' if 2j

6 j 7 8 9]! 10 111 1 2 ] | 4J s)\ 6

[ lij 14 15 16 17 18 19 SO 11 12 13, 14 15 n

2 0 jj 21. 22 23 24 25 26 17 1a \i 20 21 21' 23

27 28 29 30 31

j Today Done

. 7.10. ,
j Q u e r y UI

,
.
chapter 07/13_date_pi cker/i ndex.html ()
<input type="text" id="date" />
, jQuery-
:
$("#date") .datepi cker();
, ,
.
- ,
. ,
, jQuery,
? (
, jQuery ,
JavaScript- HTML5.)
,
jQuery UI, .
! ,
262 7. ,

,
, ,
(
, Ctrl
), .
, 50
, !
, . 7.10,
.

chapter_07/13_date_pidcer/script.js ()
$ ( # d a te ') .datepicker({
showOn: ' both'.
buttonText: 'Choose a d a te ',
buttonImage: 'c a le n d a r.png'.
buttonImageOnl : true.
numberOfMonths: 2.
maxDate: 'O d'.
minDate: '- lm '.
showButtonPanel: true
}):
showOn , .
' fo c u s ' ( ),
' b utton' ( ,
, ) ' b oth' (
). , button Image. ,
buttonlmageOnly true ,
, .
numberOfMonths 2,
, .
: , [ 3 .3 ]
3 x 3 !
maxDate minDate ,
. Ja v a S c rip t- date
.
,
. maxDate 0, .
mi nDate ,- lm -lw. ,
.
, :
, m , w , a d .

H T M L 5 , .
- H T M L 5 (
, )
. , ,
j Q u e r y J a v a S c rip t .
263


,
- ,
, .
, ,
. , ,
.
, .


jQuery
,
.
$. datepi cker. setDefaults ,
.
-, .
, ,
, :
S.datepi cker.setDefaults({
numberOfMonths: 2
}):
,
. S. datepi cker.
i so8601Week , ,
1 53. S.datepi cker. parseDate
. (, mm-dd-yy),
JavaScript- date. , $. datepi cker.
formatDate, . date
, .

()
^ , -
. ,
,
, ,
- .

jQuery UI (si ider)!
,
: , .
jQuery ,
.
. 7.11.
264 7. ,

Drag the slider to filter by price:

203A Johny Stardust (bio) Front-man Los Angeles $79

14 IB Beau Dandy (pic.bio) Singer New York $39

6636 Ctendatronix (bto.press) Keytarist London $55

. 7.1 1. ,
jQ u e ry UI

.
chapter_07/14_sliders/index.html ()
<div id="price-range">
<form action=M">
<fieldset>
<1 abel for=,,min">Minimum Price:</l abel>
<select id="min" name="min">
<option value=,,0">0</option>
<option value="10">10</option>
' <option value=n20n>20</option>

<option value="80">80</option>
<option value="90,,>90</option>
</select>
<br/>
<1abel for="max">Maximum Price:</label>
<select id="max" name-"maxn>
<option value="10,,>10</option>
<option value="20">20</option>
<option value="30">30</option>

<option value="100,,>100</option>
</select>
<fieldset>
</form>
</div>
. -
,
. si i der
di v.
ch ap te r_ 0 7 /1 4 _ slid e rs/sc rip t.js ()
var max = $('#max').val();
var min = $('#min').val();

var rangeSlider = $ ('<div></div>*)


.slider({
min: 0.
265

max: 100,
step: 10.
values: [min, max],
range: tru e,
animate: tru e,
s lid e : f u n c t i o n s . u i ) {
$ (th is)
. parent()
, f i n d ( ' lin in ')
,v a l( u i,v a lu e s [ 0 ] ) ;
$ (th is)
.parent0
,fin d ( 'I m a x ')
,v a l( u i,v a lu e s [ l] ) :
showCelebsO;
}
})
. b efo re( <h3>Drag the s lid e r to f i l t e r by price:< /h3> ');

$( '# p rice -ra n g e ') .a fte r(ra n g e S lid e r) .h id e O ;

! . : min
max ,
step , , values
.
, ,
.
, ,
, .
range animate ,
, : range ,

. mi
( )
max (
). animate jQ u e r y
, -
, , .
, s lid e ,
, .
u i,
;
value
. showCelebs ,
,
.
, change,
slid e . , ,
266 7. ,

( s lid e
, ).
,
jQ u e r y , ,
, o r ie n ta tio n :
v e rtic a l
before a fte r
-,
.
, ,
.

showCelebs.

chapter_07/14_sliders/script.js ()
function showCelebsO {
min = $ ( # m in ').v a l():
max = $ ('# m a x').v a l():
$ ('.d a ta t r ') .e a c h ( fu n c t io n ( ) {
var p ric e = p a r s e ln t ( $ ( t h is ) .f in d ( 't d : la s t ) .t e x t ( ) .
h * s u b s t r in g ( l) ) ;
i f (p ric e >= min && p ric e <= max) {
$ ( th is ) .fa d e ln ( ) :
} e ls e {
$ (th is).fa d e O u t();
}
}):
}
, .
, ,
,

.
JavaScript, , .
subst r i ng (1), , (
). parseInt
.
showCel ebs document - ready,

.
, ,
,
.
, . , ,
,
!
267


(D ra g and D ro p )
.
( , ,
) ,
. ,
. , ,
,
, .
-.
, ,
4 .
- , !
- Delete (
) , .
,
,
, ,
.
. 7.12
. .
, img.
,
.
, cursor: move .

4 , ,
.

here to delete

. 7.12.

, .

chapter_07/15_drag_drop/index. ht*l ()
<div class="trashH>
<img src=Htrash.png" alt="trash"/>
<span id=4rash-title">Drag images here to delete</span>
</div>
<div id=Mphoto-grid">
<img src=".. / . ./images/fader_100.jpg" />
268 7. ,

<img src= ". . / . ./images/beau_100.jpg" />


<img s rc = " .. / . . /images/glenda_100.jpg" />
<img s rc = " .. / . ./images/mofat_100.jpg" />
</div>

Q
d iv - .trash.
, JavaScript.
, !
, ,
HTML- ( ,
).
, ,
,
).

-
. ,
j Query-
j Query UI.
: draggabl droppabl ,
.

!
jQuery UI
, , CSS-
: , draggable droppable,
. cl ass,
, .

.
chapter_07/15_drag_drop/script.js ()
$(docum ent).ready(function {
$ ( '#photo-grid > im g ') .draggable({
re ve rt: 'in v a lid '
});
$ ( ' . t r a s h ') .droppable({
a ctiv e C la ss: 'h ig h lig h t '.
hoverClass: 'h ig h lig h t - a c c e p t '.
drop: function(event, u i) {
puffRem ove($(ui.draggable));
}
});
});
fu n ction puffRemove(which) {
//
}
269

. ,
,
, , ,
, .
,
jQuery UI.

draggable
draggable
, . , $ ('').
draggable(). <> - .
! ,
, .
:
$ ('') . draggabl({axis: ' ', containment: 'parent'});
axi s X ,
, containment
. parent, document'
window' (
DOM) ,
[xl. yl. 2, 2]. grid,
,
(, grid: [20.20]).
:
$('#draglt*).draggabl({ handle:
' :f i r s t '. opacity: 0.5,
helper: 'clone'
}):
di v- draglt,
<>. handle,
,
. hel per,
, .
clone.
, ,
. opacity
helper.
, revert.
invalid ( ),
,
, ,
.
, : start, stop drag.
,
270 7. ,

,
. drop,
,
.

droppable
draggable , droppable1.
-
. ,
.
acti veClass hoverClass. activeClass
,
. hoverCl ass ,

.
accept,
,
. ,
, .
, , ,
, . start,
stop drag over, out drop.
drop, ,
.
draggabl droppable .
,
, .
, jQuery UI 2.0 ,
. API-
,
, .
, ,
!


, ,
,
. , ,
,
, ,
,
, . .

,
1930- .
. . .
271

j Q u e ry - ani mate
. ,
, ,
. P N G - ,
,
, ,
. ,
, .
animate,
,
.

chapter_07/15_drag_drop/script.js ()
II
v a r.S th is = $(which);
image_width = 128;
sca le _ fa cto r = Sthis.outerW id thO / image_width.
var frame_count = 5;
Strash. Spuff:

- : image width
, f rame count
(,
image width * frame count). , ,
, , -
, ,
, , .
,
.
, .

chapterJ)7/15_drag_drop/script.js ()

Strash = $('<div c la s s = " p u ff''x / d iv > ')
.css({
height: S th is .o u te rH e ig h tO .
le f t : S t h is .o f fs e t O .le f t .
top: S t h is .o f f s e t O .t o p .
width: S th is.o u te rW id th O .
p o sitio n : 'a b s o lu t e '.
overflow: 'hidden'
})
.appendTo('body');

,
. overf 1ow hi dden,
.

chapter_07/15_drag_drop/scri pt.js ()
Spuff = S('<img class= "puff" src=epuff.png7 > ')
.css({
272 7. ,

width: image_width * sea le _ facto r.


height: (frame_count * image_width) * sea le _ facto r
})
.data( ' cou nt'. frame_count)
.appendTo(Strash);


,
,
. , ,
.
jQuery document-ready: $( '<img src="epuff.png"/> )
, ,
.

count data.
, .
, ,
.
chapter_07/15_drag_drop/script. js ()
II
$this.anim ate({
opacity:
}. ' f a s t ' ) .removeO:

animate
f adeOut, .
,
. ?
f adeOut , animate
.
animate.
,
. JavaScript;
,
.
chapter_07/15_drag_drop/scri p t . js ()
//
(fu n ction animateO {

var count = $ p u ff.d a ta ( 'c o u n t');

i f (count) {
var top = frame_count - count;
var height = $ p u ff.h e ig h t() / frame_count;
$ p u ff,css({
"top": - (top * h eigh t).
273

'position': 'absolute'
}):
Strash.css({
'height': height
^
Spuff.dataCcount". count - 1);
setTimeout(animate, 75); 0
} else {
Spuff.parentO.removeO;

. ,
.
(function myFunction() {}) (),
,
. JavaScript-,
.
,
( ,
setTimeout).
, , count.
,
(
i f (count), JavaScript 0 false).
,
.
, setTi meout,
callback. , 75 ,
.
,

DOM.
. ,
, !

sortable
jQuery UI
,
jQuery , sortable.
sortable ( ),
, , ,
. ,
. sortable
274 7. ,

,
.
,
. Move up
the list ( ) Move down the list (
), ,
sortabl
.
- S ta rT ra ckr! ,
.
, (-1 is t ) ,
(b -1i st).
: ,
.
.
, Accept ( ),
.
s o rta b l .
, div.
.

chapter_07/16_sortables/index.ht*l ()
<ul id=* a -lis t" class="connected">
<1 i x a href="#">G1 endatroni x < / a x / 1 i>
< l i x a href="#">Baron von J o v i < / a x / n >

</ul>

<ul id = " b -lis t" class="connected">


< l i x a href="#">Mr Speaker</ax/ii>

</ul>

,
:

$ ( " # a -lis t, #b-1is t " ) .s o r t a b l ():

, ,
, ,
,
.

chapter_07/16_sortab1es/script.js ()
S ( " # a - lis t ; # b -lis t" ) .s o rt a b le ( {
connectWi t h : ' . connected .
placeholder: 'u i- s t a t e - h ig h lig h t .
receive: function(event, u i) { ado pt(this) }.
remove: function(event, u i) { orphan(this) }
} ) .di sa b le S e le cti on();
275


. ,
. ,
Kthis cal 1back ( )
.

DISABLESELECTION
8 di sableSelection.
, enablsSelection -
, jQqery
III. di sableSelection ,
. ,
,
, - .
: UI 2. !

, .
chapter_07/16_sortables/script.js ()
function adopt(which) {
i f ($(which).hcfsClass('empty*)) {
$(whi ch). removed ass ( empty' ) . fi nd(*. empty'). remove():
}
}
function orphan(which) {
if (S(which).childrenO.length 0) {
$(which)
.append($('<1 i class="empty''>empty</li>))
.addClass( empty');
}
}
empty ()

. recei ve ,
.
adopt empty, .

remove, orphan.
,
. , <1i> empty.


Twitter
,
StarChi ,
276 7. ,

(,
). , ,
. ,
, ,

. : ( ),
, ,
.

, . ,
,
, .

.
,

. ,
!

jQuery UI, ,
Progressbar .
,
, ,
, , di v.
chapter_07/17_progress_bar/index.html ()
<form action=" ">
<fieldset>
<1egend>Sta rChi </1egend>
<textarea id="chirper" rows="10" cols="50"></textarea>
<div id=,,console">
<div id="bar"></div>
<div id="countM >0</div>
</div>
<button type="submit">Chirp!</button>
</fieldset>
</form>
j Query UI,
.
chapter_07/17_progress_bar/script. j s ()
$('#bar') .progressbar();
. ! ,
, . , ,
0 %, :
$(#bar) .progressbar({value: 50})
277

StarCh i ,
,
.
, .
chapter_07/16_progress_bar/script.js ()
$('#chirper')
.valC ')
.keyup(function(e) {
var characters = 140;
var chirp = $('#chirper') .val0 ;
var count = chirp.length;

if (count <= characters) {


$(#bar' ) ,progressbar('value'. (count / characters) * 100);
$ ('#count') . te x t(count);
} else {
$( '#chirper'). val (chirp, substrings .characters)) ;

}):
jQuery 0 100.
, ,
.
, 100.
value.
, , JavaScript-
substri ng .
,
, ,
.


,
, :
Thanks for submitting the form
JavaScript-, ,
.



, ,
. :
,
, .
278 7. ,

, ,
( E n d U s e r
Licen se A greem ent ( E U L A ) ) ,
S ta rT ra ck r!. ,
.
.
, H T M L
di v. , ,

. , ,
- .

chapter_07/18_siplenodal_dial/index.htnl ()
'<!-- -->
<div id="overlay">
<div id= "blanket,,x / d iv >
</div>
<div id="eula" class="dialog">
<h4>End User License Agreementsh4>

<div class="buttons">
<a href="#" class="ok">Agree</a>
<a href="#" class=s"canceV,>Disagree</a>
</div>
</div>

,
.
. H T M L -, ,
, C S S ,
. -
. .

chapter07/18_sinple nodal_dialog/dialog.css ()
#overlay {
bottom: 0;
display.none:
l e f t : 0:
m argin-right: auto:
m a rg in -le ft: auto:
p o sitio n : fix e d :
rig h t: 0:
top: 0:
width: 1002;
z-index: 100:
}
#blanket {
279

background-c o lo r :b la c k ;
d isp la y : block;
o pa city: 0.8;
p o sitio n : absolute:
top: 0:
width: 100%:
}
.d ia lo g {
background: white;
b order-radius; 10px;
d isp la y : none;
margin: lOOpx auto:
p o s itio n : re la tiv e ;
width: 500px:
padding: 40px;
}
.
openDi al , L -
, overlay .

clone, j Q u e ry - ,
. ,
,
.

chapter_07/18_siple_odal_dialog/script. js ()
function openDialog(selector) {
$(selector)
.cloneO
.appendToCfoverlay')
.showO
.pa rentO
.fadeln(f a s t ');
}
, ,
,
, .

chapter_07/18_sipl emodaldi al /script. js ()


$ ("# eulaO p en").click(function() {
openDia1( "#eula");
}):

. overl ay,
280 7. ,

, ,
.
chapter_07/18_simpl e modal_di al og/script. js ()
function closeDialog(selector) {
$(selector)
.parents("#overlay")
.fadeOut( 'f a s t ', functionO {
$(thi s )
.removeO;
}):

closeDialog
.
-. HTML
,
document-ready,
, .
chapter_07/18_sim plejnoda1_dialog/script.js ()
$('#eula')
.findC.ok. .cancel')
.on('click', functionO {
closeDialog(this):
})
,end()
.findO .ok')
.on('click', functionO {
// !
})
.endO
. fi nd(' .cancel')
.onOclick'. functionO {
// !
}):
, 1i ve.
clone
DOM, . 1i ve
,
!
, ,
. 9 ,
. ,
.

, ,
. , , Dialog,
j Query UI.
281

Dialog
jQuery UI
, Dialog,
jQuery UI,
. , ,
,
.
, jQuery UI Lightness,
. 7.13.

. 7 .1 3 . ,
jQ u e ry UI

,
HTML-,
.
, , , .
chapter 07/19_jquery_ui_dialog/index.html ()
<div id="dialog" title = M
Are you sure?">
<p>You've assigned the current celebrity a rating of 0 ...</p>
<p>Perhaps you are just judging them on the terrible last
^movie ...</p>
</div>
CSS jQuery UI Lightness,
StarTrackr!.
, ,
ThemeRoller (
9). HTML-,
t i t l e ,
282 7, ,

. , HTML-
: ? .
chapter_07/l9_jquery_u1_dialog/script.js ()
$('#dialog).dialog({
autoOpen: false,
height: 280,
modal: true,
resizable: false,
buttons: {
Continue: functionO {
S (this).dialog(.close'):
/ /

'Change Rating': functionO {
$(this).dia1og('close'):
/ /
}
}

, ! , ,
, dial .

buttons . ,
buttons.
, , ,
.
, .
, ,
, .
, ,
,
.


,
.
, .
, ,
.

,
.
.

( -
).
283

, autoOpen fa ls e . , -
,
.
ra ti ng-,
, 'open* dialog .
.

chapter_07/18_jq u e ryu id i al /script. js ()


$ ( '# ra tin g -0 ) .c lic k ( fu n c tio n ( ) {
$( *#dialog') .d ia lo g ( 'o p e n ');
}):
, !
,
.
, . ,
, $ (th is) .d ialo g ( 'c l o s e '). ,
c l ose open.
, .
?
modal true,
,
fa ls e ,
- . resi zabl
fa l se ( true draggable).
re si zabl draggabl
j Q u e ry ,
.
H T M L ,
, j Q uery,
t i t l e , .
,
bgi frame ( b ackground ifram e). true,
bgi frame
Internet E x p lo re r 6,
.
, open, clo se
focus, ,
, .
be fo reclo se,
, ,
!
,
. ,
,
.
284 7. ,

,
j Query . ,
,
. ,
,
j Query (
,
). ,
, .

Growl-
, StarTrackr!

.
: Twitter-,
RSS-, , ,
StarTrackr! .

, ,
?
Growl-
(Growl ,
MacOS X).
: - ,
, -
. .
, ,
, ,
, , .
,
, .
, . 7.14.

. 7 .1 4 . G ro w l-
285

CSS.
,
. HTML, , ,
.
chapter_07/20_grow l_style_notifications/index. html ()
<div id="growl"></div>

.
- - .
CSS-,
.
chapter_07/20_growl_style n o t if ic a t io n s / s t y le . css ()
#growl {
position: absolute:
bottom: 0:
right: 5px;
width: 320px;
z-index: 10:
}
, ,
. ,
,
.
()
chapter_07/20_growl_style n o t if ic a t io n s / s c r ip t . j s
function addNotice(notice) {
$('<div class=M noticen></div>')
.append( '<div class="skin,,x /d iv > ')
.append('<a href="#" class="closeM >close</a>')
.append($('<div cl ass="content"x/di v>') .html ((notice))
.hideO
.appendTo('#growl')
.fadeln(lOOO):
}
, , -
di v (
),
.
, ,
, , HTML, ,
j Query- . ,
, HTML j Query-,
. -
286 7. ,

, -,
p o s iti on: r e la t i ve.

chapter_07/20_growl style_not1ficat1ons/sty1e.css ()
.n o tice {
p o s itio n : r e la t iv e :
m in-height: 30px;
}
.sk in {
p o s itio n : absolute:
background-color: #000000:
bottom: 0;
le f t : 0:
o p a city : 0.6;
rig h t: 0:
top: 0:
z-index: -1;
-m oz-border-radius: 5px: -w ebkit-border-radius: 5px:
}
.c lo s e {
background: transparent u rl(.b u tto n -c lo s e .p n g ') 0 0 no-repeat;
te x t-in d e n t: -9999px:
p o s itio n : absolute:
top: 2px;
rig h t: 2px;
width: 26px;
height: 26px;
}

. document - ready
addNotice ,
.

chapter_07/20_growl style notifications/script.js ()


addNotice("<p>Welcome to StarTrackr!</p>");
setTim eout(function() {
addNotice("<p>Stay awhile!</pxp>Stay F0REVER!</p>");
}. 1000);
H T M L .
,
A ja x -
addNotice ,
. , ,
,
, ! .
287

chapter_07/20_growl_sty1e_notifications/script.js ()
$('# grow l')
. f i n d ( ' . c lo s e ')
, o n ( 'c lic k '. fu n c tio n O {
/ /
}):

cl i ck
, on,
.c lo se . , ,
.
.

chapter_07/20_gro*l style_notifi cati ons/scri pt.js ()


/ /
S ( t h is )
.c lo s e s t .n o t ic e ')
.animate({
border: 'none',
height: 0.
marginBottom: 0.
marginTop: ' -6 px'.
opacity: 0,
paddingBottom: 0.
paddingTop: 0,
queue: fa lse
}. 1000, fu n c tio n O {
$ (th is).rem ove ():
}):
, ,
cl osest
. ,
,
D O M . c lo se st j Q u e r y -
D O M .
,
, .


, , .
, ,
. ,
- .

, ,
288 7. ,

j Query ,
.
, 8-
: .
, -
, ,
, .
( )
, ,
,
! , ,
,
,
. .
j Query,
. , ,
,
, .
, ,
Add to wishlist ( ).
- , Adding (),
, ,
. ,
Added () .
chapter_07/21_l_up_notifications/index.htm l ()
< class="wishlist" href="#">Add to wishlist</a>
, , adding,
,
.
chapter_0 7/21 _l_up_notifications/style.css ()
.adding {
position:relati ve:
left:-35px;
top:-4px;
display:none:
}
,
.
(, wi shl i st),
, .

cal 1back,
. ( prev)
Added ().
289

c h ap te r_ 0 7 /2 1 _ l_ u p _ n otification s/scrip t.j s ()


$('<span>Adding</span>')
.addClass( 'adding')
.insertA fter(' .w ish list');

$ ( '.w ish list')


.click(function(e) {
doOneUp(this, functionO {
$(th i s ) . prev( ) . t e x t ( Added') ;
:
e.preventOefaultO:
})
:
span .
. ,
top opacity span,
, .
chapter_07/21_l_up_noti fi cations/script. js ()
function doOneUp(which, callback) {
$(which)
.nextO
.showO
.animate({
top:"-=50px",
opacity:"toggle"

1000,
functionO {
$(this)
.css({top: ""})
.hidef' slow'. callback)
.removeO:
}):
}

, callback?
doOneUp,
callback jQuery- hide.
hide , , .
, Add to wishlist (
) Added ().

, ,
, ,
( CSS). ,
, ,
290 7. ,

, .
, , !
, 9.


, ,

: HTML, CSS, JavaScript njQuery. , ,
,
. , .
-,
.
,
8
StarTrackr!
, ,

Twitter .
,
StarTrackr!,
, ,
SPA-.
,
, StarTrackr!, ,
. ,

,
.
,
. ,

,
. ,
( -
!).
- (Rich Internet
Applications (RIA)) . ,
-
.
jQuery, !

,
.
,
292 8. ,


, , . .
,
, , ... !
StarTrackr! :
, , , ,
, ,
.

selectable
jQuery UI
, ,
. ,
, ,
, ,
.
StarTrackr! -
, .
.
,
( ) ,
.
sel ectabl
jQuery UI .
( ),
: , ,
, ,
, . ,
. ! ,
, . 8.1.
, selectable ,
Ctrl ( ),
, .



,
, .
,
, ,
.

. ,
. -
293

Recently Added Tags

bad old crazy broke


singer r...
j
zzzzzzzz: irrrip :
broke smelly electronic
j
|

plastic brcjke sexy random


surgery

A p pro ve Reject i ic ie a rj |

. 8.1.

, ,
, .
chapter_08/01 jq u e ry u is e le c ta b le /in d e x .h tm l ()
<ul id="tags">
<1i>bad singer< /li>
< li> old< /li>
<1i> p la s tic surgery< /li>
<li>broke</li>

</ul>
<button id="approve">Approve</button>
<button i d="re j e c t">Rej ect</button>
<button id="clear">Clear</button>

,
CSS, , .
#tags {
lis t - s t y le - t y p e : none:
margin: 0:
padding: 0:
}
#tags l i {
border: lp x s o lid #ccc;
f lo a t: le f t ;
width: 60px;
height: 60px;
fo n t-size :!..le m ;
margin:3px;
294 8. ,

padding:0.4;
text-align:center;
}
,
jQuery UI -. ,
.
chapter_08/01_ j q u e r y u i s e le c t a b l/s c r i p t . j s ()
$("#tags") .selectableO ;
, . ... , -
? -, , . sel ectabl
class , ,
.
Firebug , , ,
. .
chapter_08/01_jquery_ui_selectable/style.css ()
#tags .ui-selecting {
background: #FEFF9F;

#tags .ui-selected {
background-col or:#eEeF8F:
}
ui-selecting ,
, ui - sel ected ,
. ,
.
, ,
-. ,
Ctrl.
, .
.
, , ,
, . ,
-1i ster, -1i ster.
,
j Query UI.
1, , start, stop,
selecting, unselecting, selected unselected.
sel ect i ng , ,
. stop,
, .

1 http://docs.jquery.conrVUI/Selectable
295

chapter_08/01_jquery_ui_selectable/script.js ()
$(#tag s') ,selectable({
stop: functionO {
// !
}
}):
. ,
, ,
,
.
chapter_08/01_jquery_ui _selectabl/scr1pt.js ( )
var names = $.map($(' .iii-selected, th is ') , function (element, i) {
return $(element) .te x tO :
}):
$(' 1i '. this)
.filter(functionO {
return($.inArray($(this).textO, names) != -1); {
,addClass('ui-selected');
j Query-
, , !
: $(' .u i-se le c te d ', this).
j Query, .
, j Query
$(expression. context) , context ,
j Query .
-,
, ,
.

$ . $.inArray
j Query-, , $.
$. i , .
j Query
JavaScript- .
names,
S.map.
$ . ,
.
, .
jQuery-
,
. -: !
296 8. ,

,
:
var names = $ ( '.ui-selected, t h i s ') .map(function(i. element){
return $(element) .textO ;
}):

- 1 MAP, FILTER
f i l t e r ;
,
.
:
, . , filter (
) JavaScript1.

, ,
,
. fi 1ter
$: inArray,
( JavaScript-
, j Query-). , ,
S.inArrayCvalue. array), .
, -1. ,
fi 1ter true fal se, ,
$.inArray (, -1), true
false . fi 1ter

. , ,
filte r, .


, ,
? Sel ectabl ,
j Query UI, , .
, ,
ui -selected.
chapter_08/01_jqueryuisel ectable/scri p t. js ()
$('#approve').click(function() {
$ (S ta g s ')
.find(' .ui-selected')
.addClass('approve')
.removed ass( 'ui-selected re je c t');
}):
$('# re je c t') .click(function() {

1 https://developer.mozilla.Org/en/JavaScrii#Reference/GlobaLObjects/Array
297

$ ('# tag s')


,find(' . ui-selected')
.addClass('reject')
. removed ass (' ui -sel ected approve');
}):
$('#clear').click(function() {
$ ('# tag s')
.findC li )
. removed ass ( 'ui-selected approve reje ct');
$('#approved') . val ( " ) ;
}):
approve reject,
, ui - selected,
, ,
.
, , ,
? ,
, .
#approve
,
, .
chapter_08/0l_jquery_u1_selectable/script.js ()
$('#approve').click(function() {
var approvedlterns =
$ ('# tag s')
.findC .ui-selected')
.addClass( 'approve')
.removedass( 'ui-selected r e je c t')
.each(functio n() {
approvedltems +- $ (th is ) .in d e x () + ''I";
:
$ ( ^ approved') . val(approvedltem s);
}):
cl i ck, #cl ear,
.
chapter_08/01_jquery ui s e le c ta b le / s c r ip t. js ()
SClapproved^.valC );
index ,
.
. .
jQuery UI- Selectable ,
, ,
, .
298 8. ,


, ,
, .
, .
, ,
. , ,
,

.
,
.
chapter_08/02_sorting_lists/index. html ()
<ul class="sortable">
<1i><a href="#">Beau Dandy</a></li>
<1 i><a href=,,#">Gl endatroni x</a></l i >
<1i><a href=#">BMX Spandex Corporation</a></li>
<1i><a href="#">Maxwell Zilog</a></li>
<1i><a href="#">Computadors</a></li>
</ul>
j Query- -
. :
, -,
. ,
j Query-, ,
JavaScript. j Query-
, -
j Query- JavaScript- sort.
,
. SORTER SORTER. sort (list)
, a SORTER. sort (lis t. ' desc')
. ,
,
, .
ch a p te r_ 0 8 / 0 2 _ so rtin g _ lists/ scrip t. js ()
var SORTER = {};
SORTER.sort = function(which, dir) {
SORTER.dir = (dir == "desc") ? -1 : 1:
$(which).each(function() {
//
var sorted = $(this).find("> li").sort(function(a. b) {
return $(a).textO.toLowerCaseO > $(b).text().toLowerCase() ?
^SORTER.dir : -SORTER.dir:
}):
299

$(thi s ) .append(sorted):
}):

,
. , desc
di , , , SORTER.di . ,
,
. ,
,
. sort
JavaScript-, $0,
j Query- text .
, .

SORT
sort JavaScript-. ,
, , ,
, ,
, , , . sort
, , .
1, sort
. -1, JavaScript- sort
. , ,
sort , .

,
.
SORTER.di -1 1
. sort :
, -SORTER, di .
-1, -(-1), , 1,
, ,
.
,
. , append ,
, .
HTML- SORTER.sort
click.
chapter_08/02_sorting_lists/script.js ()
$(#ascending') .click(function() {
SORTER.sort( ' .sortab le'):
}):
$ ('#descendi ng') . cli ck(functi on() {
SORTER.sort( ' .so rtab le', 'd esc');
}):
300 8. ,



. , , ,
.
sel ect, , mul t i pi e="mul t i pi e"
( ,
).


StarTrackr! -
, .
sel ect:
, , .
: ,
,
.
, ,
. 8.2.

A ll C e le b r itie s A - L is t e r s

Beau Dandy 1 'Johnny Stardust


Mo' Fat iCIendatronix
Mr Speaker H Beit> Dandy I
Kelly H i
Darth Fader j Thome Angeles
C&C Music Pty Ltd
Computadors 1
Baron von Jovi j
Invert S ele ctio n Invert S ele ctio n

Swap: C D C D
Swap All: ( >> ) ( )
Search:

. 8.2.

HTML-, , s e le ct
.
chapter_08/03_select_lists/index.html ()
<select id="candidates" m u ltiple= "m u ltiple " size="8">
<option value='T42">Beau Dandy</option>

</select>
<select id = " a - lis te rs " m u ltiple= "m u ltiple " size="8">
<option value="232">Johnny Stardust</option>

</select>
301

<div id="controls">
<input type=Mbutton" id="swapLeft" value="&gt;" />
<input type=Mbutton" id="swapRight" value="&lt; />

</div>
,
. SWAPLIST,
.
sel ect.
chapter_08/03_select_lists/script.js ()
var SWAPLIST = {};
SWAPLIST.swap = function(from, to) {
$(from)
.find( :selected)
.appendTo(to);
}
swap, ,
: .
, , .
find :selected.
, sel ected.
appendTo. !
, ,
, swap
.
chapter_08/03_select lis ts /s c r ip t.js ()
$('#swapLeft') . click(functi on() {
SWAPLIST.swap( ^candidates . 'f a - lis te r s ');
}):
$('fswapRight') .click(function() {
SWAPLIST.swap( 'f a - li s t e r s '. 'fcandidates'):
}):

! SWAPLIST.
? .
()
c h a p te r_ 0 8 /0 3 _ se le c tJ is ts /s c rip t.j s
SWAPLIST.swapAll = function(from.to) {
$(from)
.childrenO
.appendTo(to);

(
) .
.
302 8. ,


: ,
, ,
.
,
, . SWAPLIST,
.
chapter_08/03_selectli sts/scri p t.js ()
SWAPLIST.invert = f u n c t io n d is t ) {
$( 1i s t )
.c h ild re n O
.p r o p ( 's e le c t e d '. fu n c tio n d , selected) {
return !selected:
}):
}
, ,
selected prop. prop
a t t r ( ), ,
, . ,
tru e /fa l se, prop,
( )
j Query1.
prop !$ (th i s ) . prop( 's e le c t e d ' )
. JavaScript- NOT (!) ( )
, , true, fa lse ,
fa lse , true.

PROP
prop ,
a ttr,
. a ttr (key. value) ,
, prop a ttr
.
: .
. invert ,
,
.
text, html, val, addClass, wrap... !


,
, :
,
.
1 http://blog.jquery.com /2011/05/12/jquery-l-6-l-released
303

chapter_08/03_select_li s ts / s c ri p t . j s (r )
SWAPLIST.search = function(list, search) {
$ (list)
.childrenO
.prop('selected'. false)
.filter(function() {
if (Isearch) {
return false;
}
return $(th is )
,text()
,toLowerCase()
.indexOf(search.toLowerCaseO) > - 1
})
.prop( 'selec ted ', true):
}
? ,
( fal se sel ected).
f i 1ter ,
.
f ilte r
jQuery- .
true, . false,
...
.
,
, .
text, .
( ) ,
. JavaScript- indexOf
, "hel 1". i ndexOf ( 'l l ') ;
2 ( , , 0).
, indexOf -1,
.
, j Query- f i 1ter,
, .
prop , .
, ,
click,
, .
keyup i nput,
, .
chapter_08/03_select 1i s ts / s c ri p t . js ()
SClsearch^.keyupCfunctionO {
SWAPLIST.search("#a-listers. #candidates". S(this).valO );
}):
304 8. ,

, .
, , ,
, ,
; , -
- , .
. ,
! ,
?
.
:
, , .

(
), !


:
. j Query
: , HTML-
, , ,
. ,
, . 8.3. ,
,
CSS!

~A -lis t Celebrities
+ln a successful band
" In an indie band
n com outadors
G ..! Apes
Bosom
+ ln film or television
"F a m o u s because they're rich
+ Famous parents
+ D ot-C om m illionaires
^ B-list Celebrities
+C -lis t Celebrities
*Up and Com ers ____________

. 8 .3 .

span,
( ).
/,
. , .
305

. chapter_08/04_expandable_tree/index.html ()
<ul id="celebTree">
<1i><span>A-list Celebrities</span>
<ul>
<li><span>In a successful band</span>
<ul>
<li>Johnny Stardust</li>
<1i >G1endatroni x</li>
</ul>
</li>

<li><span>Famous because they're rich</span>


<ul>
<1 ixspan>Dot-Com mi 11 ionai res</span>
<ul>
<li>Joel Mynor</li>

, ,

. HTML- ,
.
-,
CSS. ,
,
. handle ,
-. ,
opened, cl osed.
, , CSS-,
.
chapter_08/04_expandable tree /scrip t. js ()
.handle {
background: transparent url(tree-handle.png) no-repeat le ft top;
display:block;
flo a t:le ft;
width:lOpx;
height:10px;
cursor:pointer;
}
.closed { background-position: le ft top; }
.opened { background-position: le ft -lOpx; }
, , -
:
. /
ul.
, ,
306 8. ,

click
.
chapter_08/04_expandabl e tre e /s c ri p t. js ()
$('fcelebTree u l')
.hideO
.prev('span')
.beforeC'<span></span>')
.prevO
.addClass( 'handle closed')
,click(function() {
// /
}):
. ,
, jQuery !
, .
span
. span
.
,
prev. handle closed (
- hide),
cl i ck, .
,
.
, .
chapter_08/04_expandable_tree/script.js ()
// /
$(this)
.toggleClass( 'closed opened')
.nextAll( 'u l')
.toggleO;
,
cl osed opened toggl 1ass.
toggl 1 ass, , , ,
, , .

TOGGLECLASS
toggleCl ass ,
: , ,
. , .
:

i f ( 1) {
$ (th is ) .a d d C la s s ( opened');
} e ls e {
307

$ ( t h i$ ) .rem ovedass('opened*);
}
toggleClass(class, switch), i f
:

$(th i s ) . to g g le C la s s ( opened'. x ** 1);

, ,
next 11. jQuery -,
, span ( ),
-
... u l . !
, .


j Query. ,
. ,

c lic k .
, ,
.
: on off Ajax
6 on.
, , .
,
, . HTML-,
, .
chapter_08/05_event_delegati on/i ndex.html ()
<span><strong>Selecti on:</strong></span>
<span id=,,c u rre n t,,>--Choose a celebrity--< /span>
<ul id=,,p ic k e r,,>
< li class="category">
<span class= "title"> A-List< /span>
<ul>
<li>Beau Dandy</li>
< li> G lendatronix< /li>
</ul>
< /li>
< li class= Mcategory">
<span class= "title"> B-List< /span>
<ul>
<li>Mo' Fat< /li>
<1i>DJ Darth Fader</li>
</ul>
< /li>
</ul>
308 8. ,

,
category > cel ebri ty
(. 8.4).
?

Selection: A-List > Glendatronix

A -L ist
Beau Dandy

B-List
Mo Fat
DJ Darth Fader

. 8.4.

click
$( '#picker l i ') .click (...),
.
,
, cl i ck -.

, ,
, . target
DOM,
j Query, j Query-:
$('#picker1).click(function(e) {
$(^ c u rre n t').tex t($ (e.targ et).tex t());
}):
.: ,
! ,
:
(
/
5). , ,
, .
, ,
, (
e.stopPropagation "return false").
, . ,
, ,
, ,
.

, ,
. , ,
? .
309

chapter_08/05_event_delegation/script.js ()
$(#p1cker' ) .click(function(e) {
$ ( '.selected') .removed ass( 'selected');
$(e .ta rget) .addClass( ' selected');
var celebrity = $(e.target).textO ;
var category = $(e.target)
.closest(' .category')
.find( . t i t l e ')
.te x tO ;
$('#current') .text(category + " > " + celebrity);
}):
cl osest
category. , closest
... ,
. parent (). parent (),
parentC), HTML-.

HTML-
, ,
, .

-,
- .
CSS, . , CSS
,
,
.
StarTrackr! , . ,
:
,
, . 2
, ,
, .
, , ,
j Query.


:
, .
, ,
,
. , ,
310 8. ,

,
, .

,
, !
, ,
. ,
. 8.5.

Id Name Occupation Approx. Location Price

007F Kellie Kelly Singer Omaha S11.95

8 5 Darth Fader OJ London $19,95

. 8 .5 .

-,
position: fixed thead
. position: fi xed
, -. , ,
, ( ),
j Query.
, .
, 2, ,
, .
chapter_08/06_fixed_table_headers/index.html ()
<table id=,,celebs,,>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Occupati on</th>
<th>Approx. Location</th>
<th>Price
</tr>
</thead>
<tbody>

</tbody>
</table>
thead .
,
. :
thead ,
thead.
311

p o s it io n : absol u te ; ,

TABLE, ,
fixHeader,
. ,
-.
data, .
chapter_08/06_f ixedtable headers/script. js ()
var TABLE = {};

TABLE.fixHeader = fu n ctio n (ta b le ) {


$ (ta b le ).e a c h (fu n c tio n () {
var Stable = $(t h i s );
var Sthead = S t a b le .fin d ( 't h e a d ');
var Sths = S t h e a d .fin d ( 't h ');
S ta b le .data( ' to p '. Sthead.o f f s e t ( ) . to p ) ;
S ta b le .d a t a ( 'le f t '. Sthead.o f f s e t ().1 e f t );
S ta b le .d a ta ( bottom '. S ta b le .d a ta ( 't o p ') + S ta b le .h e ig h tO -
^ Sthead.heightO );

,
. , ,
. , ,
each tabl (Stabl ), thead (Sthead)
th, (Sths).
Sthead, (
!).

||||| EACH

, .
, ,
each.
each: table
, .

faux ul
.
chapter_08/06_fixed_table_headers/script.js ()
var S lis t = $('<ul class="faux-head"></ul>');
$ th s .e a c h (fu n c tio n (i) {
_th = $ (th is );
S list.a p p e n d (S ( <1i ></1i> ")
.a d d C la s s (_ th .a ttr(" c la s s " ))
.htm l(_ th .h tm l())
.w idth (_th .w idth ())
.c lic k ( fu n c tio n ( ) {
312 8. ,

_th.click()
})
) .hideO .css({left: Stable.data( 'l e f t ') .top: Stable.data( 'to p ')}):
}):
$('body') .append(Slist);
th Sths. each
, ,
-. , HTML-
, click.
, !
,
thead, -.


: ,
, -?
-
, , ,
.
, DOM,
-.
( !),
. ,
: ,
,
.

- thead,
scrol 1 .
chapter_08/06_fixed_table_headers/script. j s ()
$(window).scrol function {
clearTimeout(timer);
timer * setTimeout(function() {
if (Stable.data('top') < S(document).scrollTop() &&
^S(document).scrolITopO < Stable.data(bottom')) {
Slist
.showO
.stopO
.animate({
top: S(document).scrollTop().
opacity: 1
}):
} else {
$list.fadeOut(function() {
$(this).css({top: $table.data( 'to p ')}):
}):
}
} . 100 ) :
}):
313

scrol 1
100 . ,
, , ,
, . ,
thead ,
. , -
. ,
thead , ,
, ,
( ,
).
! TABLE.fixHeader("#celebs")
. thead ,
.



.
, ,
,
,
! ,
, , .
. 8.6.

Id Name Occupation Approx. Location Price


203 Johny Stardust (bio) Front-man Los Anoeles $39.95

6636 Glendatronix Keytar 1st London $39.95

1418 Beau Dandy (pic) Singer NffioJGHk $39.95

2031 Mo Fat Producer New York $19.95

007F Kellie Kelly Singer Omaha $11.95

805 Darth Fader DJ London $19.95

203 Johny Stardust (bio) Front-man Los Angeles $39.95

6636 Glendatronix Keytarist London $39.95

141 Beau Dandy (pic) Singer New York $39.95

2031 Mo Fat Producer New York $19.95

id Name Occupation Approx. Location Price


007F Kellie Kelly Singer Omaha $11.95

8 5 Darth Fader DJ London $19.95

. 8.6.


- .
314 8. ,

? , ,
? , ...
jQuery, .
chapter_08/07_repeati ngtabl eheader/scri p t. js ( )
$('#celebs')
.find(' t r :f i r s t ')
.cloneO
.insertAfter('#celebs tr:nth-child(10n)');
:
cl one. :
nth-child ,
. , ,
,
. ,
, . , :
nth-chi ld(2), .
:nth-chi Id ,
.
even odd,
. :
, !
. , ,
:nth-chi ld(10n), .
,
. , ,
, :nth-chi ld(10n+3). , ,
, :nth-chi 1d( 10-7).
, :
,
,
. ,
, ,
.
,
-.
chapter_08/07_repeat i ngtable header/script. js ()
var TABLE = {};

TABLE.repeatHeader = function(table. every) {


$(table).each(function() {
var $this = $(this);
var rowsLen = $ th is.fin d ('tr:n o t(:f i r s t ) ' ) . length:

$ (th is ) .f in d ( 'tr :f ir s t')


.cloneO
315

.insertA fter($this.find('tr:nth-child(' + every + 'n )')):

if ((rowsLen) %every === 0) {


$ th is .fin d ( 'tr ila s t') .remove!);
}
}):
}
, ,
, ,
. ,
, (
-).
$(thi s) .
,
.
: ( )
.
f 1nd,
, ,
, .

,
: ,


,
,
. ,
,
,
,
-! , , ,
?
, , ,
, , , , .
, ! ,
Windows-.
, ...
! , .
. .
, ,
.
.
316 8. ,

,
,
, , , ,
.
.

,
-, ,
.
,

.
.
, . ,
: 10 000
, . ,
,
; ,
, .
j Query-, . 8.7.

Celebs
0

id Name Occupation A p p r o x . L o c a tio n Price
203A Johny Stardust (bio) Front-man Los Anoeles $39.95

6636 Clendatronix Keytarist London $39.95

141B Beau Dandy (pic) Singer New York $39.95

. 8 .7 .

, ,
Next () Previous (), ,
.
HTML , j Query ,
.
chapterJ)8/08_pagination/index.html ()
<div class="table-wrapper">
<div class= ,,wrapper-paging,,>
<ul>
<1i><a class="paging-back">&11;</></1i >
<1 i><a class= ,,paging-this"><strong>0</strong> o f <span>x
fc*</span></a></li>
<1 i x a cl ass^'pagi ng-next ">&gt
:</></1i >
</ul>
317

</div>
<div class="wrapper-panel">
<table id=''celebs">

</table>
</div>
</div>


jQuery.
, ,
.
.

,
CSS,
jQuery -.
, ^^
.
.
chapter_08/08_pagination/index.html ()
var TABLE ={ } ;
TABLE.paginate fu n ctio n (ta b le . pageLength) {
// 1. .

// 2. .

// 3. .

pagination = fu n ction (d ire c tio n ) { // 4. ,


var reveal = fu n ction (current) { // 5. .

}:
}
}:
, , ,
. ,
, ,
.
chapter_08/08_pagi nation/script.js ()
11 1. .
var Stable * $ ( ta b le ) ;
var Srows = S t a b le .fin d ( tbody > t r ' ) ;
var numPages = M ath .ceil(S row s.len gth / pageLength) - 1;
var cu rren t = 0;

.
,
318 8. ,

, DOM
- di v, .
,
.
chapter_08/08_pag1nation/scr1pt.js ()
II 2. ,
var $nav - $table
.p a ren ts( ' . tab le-w ra p per')
, f i n d ( ' .wrapper-paging u l ' );
var $back - $ n a v . f i n d ( 'l i: f ir s t - c h i ld a' ) :
var $next - $ n a v . f i n d ( 'l i:la s t - c h i Id a' ) ;

,
, ( ,
). Previous (
) Next (). ,
pagi nati on, .
chapter_08/08_pagination/script.js ()
$nav.find(' .paging-this strong') ,text(current + 1);
$nav.find('a.paging-this span') .text(numPages + 1):
$back
.addClass('paging-disabled')
,click(function() {
pagination '< ');
}):
$next.click(function() {
pagination '> ');
}):

, .
,
.
j Query? : 11 () : gt (),
, , 10- 20-,
. , slice,

, .
chapter 08/08_pagi nat i on/scri p t.j s /)
// 3. .
Srows
.hideO
.slice(0. pageLength)
.showO;
319

:
-. , ,
, . -
, (
).
chapter_08/08_pagination/script.js ()
. ,
i f (direction "<") { //
if (current > 1) {
(current -- 1):
}
else if (current == 1) {
(current -- 1):
Sback.addClass(pagi ng-di sabled"):
}
} else { //
if (current < numPages - 1) {
current += 1:
}
else if (current == numPages - 1) {
current += 1:
$next.addClass("pagi ng-di sabled):
}
}
reveal(current);
current, .
reveal.
chapter_08/08_pagination/script. js ()
11 5. ,
var reveal = function (current) {
Sback.removed ass("pagi ng-di sabled");
Snext.removed ass("paging-di sabled");

Srows
.hideO
.slice(current * pageLength, current * pageLength + pageLength)
.show();

$nav.find("a.paging-this b").text(current + 1);


}
reveal disabled,
. slice
, .
320 8. ,

@
, , , , ,
: .
(.
jQuery
6),
. ?
,
,
.



, , ?
, ,
Edit () ,
, . 8.8.

Celebs
A p p ro x .
Id Name O c c u p a tio n P rice
L o ca tio n

Johny Stardust
203A Front-man Los Anodes $39.95 dD
)
f-nn-r,-' -
-
,,,-ri
I s G en d atron tx Keytarist < a h ref * h ttp :// | $39. *
141B Beau Dandy (pic) Singer New York $39.95 ( )

. 8.8.

, ,

.
,
. , .
chapter_08/09_editable_table_cel1s/index.html ()
<form actio n = "n u ll" method="post">
<table id= "celebs>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Occupati on</th>
<th>Approx. location</th>
<th>Price</th>
</tr>
321

</thead>
<tbody>
<tr>
<td>203A</td>
<td>Johnny Stardust</td>
<td>Front-man</td>
<td>Los Angeles</td>
<td>$39.95</td>
</tr>

, ? ,
, ,

!
:
HTML- ,
, , jQuery
.
,
.
chapter_08/09_editable table cel 1s/script. js ()
TABLE.formwork = function(table) {
var Stables = S(table):

Stables.each(function () {
var _table = S (this):
_table
.findCthead tr )
.append($('<th class*="edit">&nbsp:</th>'));
_table
,find('tbody t r ' )
.append(S('<td class=,,edit"><input type=button"
ta*value="Edit'7></td>'))
}):
Stables.find(' .edit :button') .o n ('click '. function(e) {
TABLE.editable(this):
e.preventDefaultO;
}):
}
TABLE. formwork , ,
thead tbody edi t
. thead ,
, , tbody, ,
.
. ,
: . ,
322 8. ,

, , , .
.
chapter_08/09_ed1table_table_cells/scr1pt.js ()
TABLE.editable - function(button) {
var $button = $(button);
var $row - Ibutton.parents( 'tbody t r ') ;
var Scells - $row.children(' td ' ) ,not(' .e d it');

if ($row.data('flag')) { //
//
//

$row .data('flag'. false):


$button.text('Edit'):
}
else { //
//
//

$row .data( 'f l a g '. t r u e ) ;


S b u tto n .te xt( 'S a v e ');
}

click TABLE.formwork ,
,
, .
Sbutton parents, Srow chi 1dren
( edit not) .
i f data, ,
, ,
. , ,
.

. , ,
.
chapter_08/09_editable_table_cel1s / s c r i p t .j s ()
Seel Is.each(function 0 {
var _cell = $(this);
_cell .html (_cell .find( 'in p u t') .val 0 ) ;
}):
val input cell
html, cell.
(
!), ,
.
323

,
.
chapter_08/09_editable_table_ce11s/sc rip t.js ()
$cells.each(function 0 {
var _ce11 = $(this);
_cell .data( 'tex t' ._cell .htmlO)
. html ( '') ;

var $input - $('<input type="text" />')


.val(_cel1.d a ta ('te x t'))
,width(_cell.width() - 16):

_ c e ll.append($input);
}):
,
. ,
i nput, . ,
, data,
.
input. , ,
, , ,
DOM.
i nput ,
.
, ,
. ?

,
.
:

,
. , ,
, DataTables1.
DataTables -
, HTML-
, , ,
, , ThemeRoller, Ajax- . .
, ,
, ,
,
. , ,
!

1
http://www.datatables.net/index
324 8. ,

,
, ,
j Query. ( ) ,
,
.



, ,
( )
.
,
,
.
: ,
, , .
,
, Shift,
.


, , .
,
DOM,
. next previous,
.
, j Query .
,
, . ,
, #celebs.
.
: #celebs tr,
: #celebs t r td :nth-chi 1d( 1). , ,
: #celebs tr td :nth-chi 1d(1) :checkbox.
! ,
$(' t r : odd *).
(
i d checker) thead .
th, td, .
click ,
,
, checked
,
.
325

chapter_08/10_sel e c t c o l umn_checkboxes/scri p t . j s ( )
var chkSelector = 't r td:nth-child(l) :checkbox';

$('#checker').click(function() {
$('#celebs ' + chkSelector)
.prop('checked', $(this).prop('checked'));
}):
(chkSel ector),
.


Sh ift
,
.
Shift
,
. ,
-.
Shift
. , Shift?
, , jQuery, !
Shift,
. shi ftKey, click;
- !
Ctrl Key, al tKey metaKey.
, ,
? DOM,

i ndex. .
,
,
.
, data.
, .
chapter_08/10_select column_checkboxes/script. j s ()
$('#celebs ' + chkSelector).click(function(e) {
var Stable = $(th is).p aren ts('tab le');
var lastRow = Stable.data(' lastRow');
var thisRow = $(this).parents('tr').index():

if (lastRow !== undefined && e.shiftKey) {


var numChecked = 0;
var start = lastRow < thisRow ? lastRow : thisRow;
var end = lastRow > thisRow ? lastRow : thisRow;
Stable
find(chkSelector)
326 8. ,

.s lic e (s ta rt. end)


.('checked', true);
}
Stable.data('lastRow'. thisRow);
}):
lastRow (
, table ),
Shift.
. ,
, ,
. j Query- si ice
. ,
.

!

!
StarTrackr!


. , j Query
HTML- ,
, , ,
, - RIA (Rich Internet
Applications), .
,
j Query
, . , , ,
?

.
,
, !
, .
:
!

, .
, ,
j Query!
,
9

jQuery, ,
, .
DOM
. jQuery ,

.


, ,
\! ?
, ,
, ,
( ) ,
?
, .
,
. ,

JavaScript-. ,
jQuery-.
,
jQuery.

shuffle -
1 . ,

, ,
- ,
!
328 9. ,


jQ uery ,
,
. , ,
jQuery-.
, jQuery-
,
.

,
. ,
, -
, ,
, ,
. ,
,
,
.
, ,
j Query-,
j Query. JavaScript prototype

. prototype
j Query
.
(, !)
jQuery. JavaScript-
,
-, $ jQuery-:
(functi($) {
//
})(jQuery);
,
JavaScript- jquery.
pi uginname. js -,
. ,
!
,
$.
, ,
. HighlightOnce,
j Query $. fn.
329

chapter_09/01_plugins/jquery.highlightonce.js ()
(function(S) {
/ /
$. fn. hi ghl ightOnce = functionO {
/ /
}
})(jQuery);
, $. fn JavaScript- jQuery. prototype
.
jQuery,
, ,
jQuery.
j Query,
, .
-
, , ; ,
$(' '). highl ightOnce(),
paragraph .
, , j Query- .
.
chapter_09/01_plugi ns/jquery.hi ghli ghtonce.js ()
//
return this.each(functi on() {
// -
}):
,
. ,
, .


HighlightOnce ,
. , ,
, ! ,
,
, .
$(this)
j Query JavaScript.
, ,
,
. ,
,
. , ,
( ,
330 9. ,

Effects j Query
j Query- Color).
chapter_ 09 /01 _ plu gins/jq uery.h ighlighton ce.js ()
11 -
$(this)
,data('original-color'. $(this),css('background-color'))
.css('background-color', '#fff47f')
.one('mouseenter'. functionO {
$(this).animate({
'background-color': $ (th is).data('original-color')
}. 'f a s t') :
}):
j Query, one,
. one bi nd,
, ,
. ,
,
(). one on!
, data
, mouseover
DOM.
, .
, .
ch apter_ 09 /01 _ plu gins/scrip t.j s ()
SCp')
.hide()
.highlightOnceO
.slideDownO;
:
,
,
hide si ideDown. ,
11 (6
),
, ,
, .


j Query
, ,
,
, , .
,
,
.
331

,
,
, .

, ,
, .
:
. ,
. HighlightOnce,
.
,
. .
c h ap te r_ 0 9 /0 2 _ p lu gin o p tio n s/jq u e ry .h igh ligh ton ce .js ()
S.fn.highlightOnce = function(color) {

$(th is ) .css('background-color'. color || *#fff47f')

}:
,

( JavaScript- 11).
.
chapter_09/02_pluginoptions/script. js ()
$ ( 'p ')
.hide()
.highlightOnce('green')
.slideDownO;
,
, .
,
, ,
.
.
, ,
. animate, css
jQuery UI. /
: ,
.
.
chapter_09/03_plugin options w ithdef aults/jquery.highlightonce.js ()
S.fn.highlightOnce.defaults = {
color : '#fff47f',
duration : 'fa st'
};
332 9. ,

,
j Query- $. extend.
,
, .
, , ,
:
, ,
- ,
. ! .
chapter_09/03_pl ugi n_opt i o n s w i t h_def aul t s/jq u e ry . hi ghl i ghtonce. j s ( )
$.fn.highlightOnce = function(options) {
options = $.extend({}, $.fn.highlightOnce.defaults, options):

return this.each( ... );


}:
opti ons ,
.
.
chapter_09/03_pl ugi n o p t i ons_wi t h d e f aul ts /jq u e r y . hi ghl i ghtonce . j s ()
$(thi s )
.data('original-color'. $(th is ) .css( 'background-color'))
.css('background-color', options.color)
.one( 'mouseenter', functionO {
$(thi s ) .animate({
'background-color': $(th is ) .data('original-color')
}. options.duration);
}):
,
.
,
duration ' f a s t' 2000 .
chapter_09/03_plugin_options_w ith_defaults/script.js ()
$ ('')
.hideO
.highlight0nce({duration: 2000})
.slideDownO;

callback
,
cal 1back . ,
, , ,
, call back
. callback
,
333

,
. ,
,
. , , HighlightOnce
, ,
, , .
setup (
mouseover) complete (
animate).
chapter_09/04_pl ugi n c a l 1backs/ jquery. hi ghl i ghtonce. j s ( )
$.fn.highlightOnce.defaults = {
color: '#fff47f'.
duration: 'f a s t',
setup: n u ll.
complete: null
}:
cal 1back - ,
null.
, ,
. 11back
j Query- cal 1back,
j Query.
.
chapter_09/04_plugi n c a l 1backs/jquery.hi g h li ghtonce.j s ( )
$(this)
.data('original-color'. $(this).css('background-color'))
.css('background-color', options.col or)
.one( 'mouseenter'. functionO {
$ (th is).animate(
{'background-color': $(this).data('original-color)},
options.duration,
options.complete
):
}):
// callback- setup
if ($.isFunction(options.setup)) {
opti ons.setup.11(thi s ):
}

callback. callback- complete :
, animate,
animate callback,
. setup :
, .
334 9. ,

j Query JavaScript. ,
c a llb a c k , jQuery- S .isF u n c tio n ,
true, ca llb a ck , fa ls e
. ( ,
, ,
, n u ll) ,
cal 1back!


S.isFunction, jQuery : $.isArray (
, ), S.isPlainO bject (
JavaScript-) $. i sEmptyObject ( , ).
JavaScript-
.

c a llb a c k , .
JavaScript-,
o p tio n s .s e tu p O . ,
, d efault,
( ).
ca llb a ck ,
DOM . JavaScript-
c a ll. , c a ll, t h is ,
. th is ,
DOM.
, $(t h i s )
compl ete,
.
chapter_09/04_plugincal1backs/script.js ()
$(' p' )
.h id e O
.highlightO nce({
co lo r: #FFA86F'.
complete: fu n ctio n O {
$(t h i s ) .slid e U p O :
}
})
.slideD ow n O ;

jQuery- callback
, jQuery- cal 1back

. , hide
c a llb a c k ( )
speed, c a llb a c k .
/, , . ?
335

, JavaScript-. ,
, , ,
callback, .
j Query,
Ajax- 1< params , ,
, cal 1back:
load: function( u rl. params, callback ){
// ,
if (jQuery.isFunction( params )){
// , callback,
callback = params;
params = n u ll;
}
}
, params ,
. , ,
, callback params.

j Query.
HighlightOnce,
call back.
chapter_09/05 jquery style cal 1backs/jquery. highl ightonce. js (')
S.fn.highlightOnce = function(options, callback) {
if (S.isFunction(options)) {
callback - options:
options = n u ll;
}
options = $.extend($.fn.highlightOnce.defaults.options);

return this.each(function() {
// -
$(this)
.data( 'original-color'. $(this).css('background-color'))
.css('background-color'. options.col or)
.one('mouseenter', function0 {
S(this).css( 'background-color', " ) ;
S.isFunction(callback) && callbackO;
}):
}):
}:


,
, ,
jQuery. .
336 9. ,

, ,
,
,
.

jQuery
jQuery-,
,
,
,
jQuery . ,
jQuery ,
jQuery, ,
.
, jQuery,
jQuery .

jQuery
, ,
, ,
. , , ,
jQuery.
jQuery, , extend
, .
!
jQuery. fn. extend $.fn. extend ,
jQuery,
,
jQuery-. jQuery. extend(),
jQuery. ,
, .
, extend,
, ,
(
).
, ,
extend. 8,
:
var SORTER = {}:
SORTER.sort = function(which) {
//
}
jQuery.
SORTER jQuery, extend.
337

chapter_09/06_extending_jquery/script.j s ()
$.fn.extend({
sorter: functionO {
return this.each(function() {
var sorted = $ (th is ).c h ild re n ('1i ' ) ,sort(function(a,b) {
//
return $(a).text().toLowerCase() >
^ $(b).text().toLow erCase() ? 1 : -1:
}):
$(this).append(sorted);
}):

}):
sorter
,
.
.
chapter_09/06_extending_jquery/script.j s ()
$('#ascending') .click(function() {
$ ('u l.so rtab le')
.hide()
.sorterO
.slideDownO;
}):
SORTER
, extend
. jQuery-,
,
. , ,
.
.

$
j Query ,
: ,
. , ,
, . ,
, , !
: $.ajax, S.itiap,
$.slice, S.trimH .
$. ,
,
j Query. , $ map
, j Query-.
Twitter-
Ajax, 6, ,
338 9. ,


, , 56
. ,
j Query,
. ,
,
$. 1apsed(time) .
,
. ,
, j Query ,
, $
.
chapter_09/07_$_prefixed_functions/script.j s()
(function(S) {
$.lapsed = function(time) {
var then = new Date(Date.parse(time));
now = new DateO;
minutes = Math.round((now-then) / 60000);
lapsed, seconds;

//

})(jQuery);
jQuery.
jQuery, ,
- .
,
i f/el se. ,
, ,
,
.
chapter_09/07_$_prefixed_functions/script.j s ()
//
if (minutes === 0) {
seconds = Math.round((now - then) / 1000);
if (seconds < 10) {
lapsed = "less than 10 seconds ago";
}
else if (seconds < 20) {
lapsed = "less than 20 seconds ago";
}
else {
lapsed - "half a minute ago":
}
}
else if (minutes === 1) {
339

seconds = Math.round((now - then) / 1000);


if (seconds 30) {
lapsed = "half a minute ago:
} else if (seconds < 60) {
lapsed = "about a minute ago";
} else {
lapsed = "1 minute ago":
}
} else {
lapsed = "more than a minute ago";
}
return lapsed
j Query-,
elapsed , .

.
chapter_09/07_$_prefixed_functions/script.js ()
.append( '<span class-,,time,,>' + $.lapsed(this.created_at)
'</span>')


-
$.fn. myPlugin $. extend ({ myPlugin : ... }) ,
extend ,
. j Query (
), .
j Query, ,
!
$. t i
.
, true
.
chapter_09/08_overwri ti ng exi sti ng_functi on/script. js ()
(function(S) {
var _trim = S.trim;
$.extend({
trim:function(text, clear) {
if (clear) {
return text.replace(/\s+/g,'') ;
}
return _trim .call(this, text);
}
}):
})(jQuery);
, ,
$ j Query (.
340 9. ,

). trim
, . ,
trim. trim
. ,
,
j Query- trim.
,
, ,
$. ajax
.
, .
,
.
, ? ,
.
, ,
HTML5 . HTML5
. ... . HTML5
j Query- animate CS53-,
. animate,
, .
CSS3-peuieHHH jQuery, , ,
, , 1. ,
. ,
, , , ,
! , ,
.
chapter_09/09_extending jquery a n im ate /sc rip t. j s ()
$.fn.extend({
defaultAnimate: $.fn.animate,
animate: function(props, options) {
//

if (jQuery.support.transitions) {
// CSS3
}
else {
// jQuery
}
}
}):
animate
defaultAnimate.
, , ,
, .

http://addyosmani .corn/blog/css3transitions-jquery
341


animate.
,
553- j Query-.
chapter_09/09_extending_jquery_animate/script.js ()
animate: function(props, options) {
var prefixes = [ 'Moz'. ' Webkit' . ' 0 ' ] , / / , 'Khtml' , 'Ms'
length = prefixes.length,
effects = {
duration: 2000.
easing: "ease-in-out",
complete: null
}.
effect, i ;
jQuery.extend(effects, options);
effect = ['a ll effects.duration / 1000, 's
^ effects.easin g ] ,join("");

if (!jQuery.support.transitions) {
i f (jQuery.support.transitions !== false) {
jQuery.support.transitions = false;

for (i = 0; i < length: i += 1) {


if ((prefixes[i] + "Transition") in this[0]
h * .sty le) {
jQuery.support.transitions =
^ p r e f ix e s [ i] . "-transition] .jo in C ");

}
return $(this).each(function() {
if (jQuery.support.transitions) {
$(th is ) .css(jQuery.support.transitions. effect)
css (props):
if ($.isFunction(effects.complete)) {
setTimeout(function() {
effects. completeO:
}. effects.duration);

}
else {
options.easing = "linear";
$(this).defaultAnimateCprops. options);
}
}):
}
-, ,
jQuery .
342 9. ,

, .
, .
props opti ons :
animate,
.
,
defaul tAnimate, .
.
, pref i xes
, , length
, a e ffe c ts ,
. effect,
, , i
, . p re fix e s
.
, 583-.
, , e ffe c ts
d e fa u lts . ,
, ,
e ffe c t e ffe c ts.
chapter_09/09_extending_jquery_animate/script.js ()
i f ( ! jQ u e ry .su p p o rt.tra n sitio n s) {
fo r (i = 0; i < length: i += 1) {
i f ( ( p r e fix e s [ i] + "T ra n sitio n ") in t h is [ 0 ] .s ty le ) {
jQ u e ry .su p p o rt.tra n sitio n s = p r e fix e s [ i] ,
^ " - t r a n s it io n " ] .jo in ("");

}
, , , i f
jQuery support , , , JavaScript
.
, ,
animate,
583- ( ,
!). i f ,
jQ u ery.su pp o rt.tra n sition s false.
, .

?
: ? JavaScript
, true false.
, JavaScript ,
, . 0, "" ( ),
null undefined. 1, "0" "false" (
). .
343

, ,
, , .
,
.
fal se
jQuery.support.transitions , ,
. , for
prefixes "Transition"
style , .
true ,
553-. , Chrome true
WebKi tTransi ti on . CSSS-
Internet Explorer , Ms
. ,
, , .
Internet Explorer 10 ,
.
return,
each ,
animate. ( , , ?)
chapter_09/09_extending_jquery_anim ate/script.js ()
if (jQuery.support.transitions) {
$(this).css(jQuery.support.transitions, effect).css(props);
if ($.isFunction(effects.complete)) {
setTimeout(function() {
effects.completeO;
}. effects.duration);

, CSS3, jQuery.
support transitions :
"-WebKit-transition"
, , Chrome.
: (. )
CSS. ,
CSS3!
jQuery. support .transitions
css , effect.
:
"all 2s ease-in-out"
, , ,
callback. ,
call back.
,
344 9. ,

. jQuery- , CSSS-
.
. jQuery. support. transi ti ons
- ?
jQuery-, :
, , defaul tAnimate.
chapter_09/09_extending_jquery_animate/script.j s ()
else {
options.easing = "linear":
$(this).defaultAnimate(props, options);
}
, options .easing? CSS3 -
,
, jQuery.
, camel-
, .
,

. , , ,
,
. , ?
? , ,
,
.
chapterJ)9/09_extending jquery a n im ate /sc rip t. j s ()
$('#star_0 div' ) .animate({ width: "580px" }, {
complete: function 0 {
$("#star_0") .addClass("barred")
.fi nd("span" ).html( "Made it"):
}
}
):
$('#star_l div) .animate({ width: "580px" }, {
duration: 2000,
easing: 'lin e a r ',
complete: function () {
$("#star_l") .addClass("barred")
.find("span").html("Arrived"):
}
}
);
$('#star_2 div' ).animate({ width: "580px" }. {
duration: 7000.
easing: ' ease-in-out .
complete: function () {
$("#star_2") .addCl ass("barred)
345

.find("span) .html("Star statu s");

}
);
cal 1back
.
, ,
, .
, ease-in-out.
, ,
. 9.1, , . 9.2.

2 , , , .
, . 9.3,
-, .

. 9 .3 .
346 9. ,

j Query-
- ,
CSS3, . ,
, StarTrackr!
j Query 1.
!


, 4 , 2 , 6
, 4 14 ,
.
, : j Query-
, -.
, -
, ,
, -?

-
- " " -
, , . ,
" " - ,
, .

,
() ,

.
-,
,
- .
-,
Ajax. Ajax-,
, .
chapter_09/10_custom_selectors/script.js ()
$ . e x t e n d ( $ . e x p r [ '{
abovethefold: fu n ctio n al) {
return $(el) .offset0 .top < $(window) .scrollTopO +
(window).hei ght();
}
}):
$. extend,
. -

1
j Query,
. . .
347

$. [: ], .
/, , ,
. true false.
true, (el) .
.
chapter_09/10_custom _selectors/script. js ()
$ ('p:abovethefold').css(co lo r'. red);
:abovethefol d -,
, , ,
.

j Query, , ,
, .

j Query .
, ,
W3C, -
, .
,
,
. , .


, bind trigger ,
, click, mouseover, toggl ...
. ()
, bind trigger
.
bind trigger? , ,
. ,
!
. ,
, , ,
, , ,
, .
do-toggl .
di scl aimer 2.
chapter_09/ll_custom_events/index.html ()
< id="disclaimer">
Disclaimer! This service is not intended ...
</p>
<input type="button" id="toggleButton" value="toggle" />
348 9. ,

di scl ai
, .
chapter_09/ll_custom _events/script.j s ()
$(^disclaim er) .bind('do-toggle', function {
$(thi s ).toggle('slow');
}):
do-toggle
disclaimer. do-toggle
disclaimer
.
do-toggle? trigger.
chapter_09/ll_custom _events/script.js ()
$ ('#toggleButton *).click(function() {
$(#disclaimer') .trigger('do-toggle');
})
di scl aimer ,
.
,
toggl ,
:
.
,
di scl aimer toggl
,
do-toggle , .
, . bind/trigger
.
,
.
: ,
-,
-
.
-

3 .
, .
,
.
, , ,
, .
.
,
: , ,
.
349

,
.
change .
chapter_09/12_custom_events_with_params/index.html ()
<select id="chooser">
<option>Beau Dandy</option>
<option>Johnny Stardust</option>
<option>Glendatronix</opti on>
</select>
. reveal
.
,
, . effect
ease, si i deToggl .
.
chapter_09/l2_custom_events_w1th_params/scr1pt.js ()
$ ('#bio h3') .b1nd('reveal', function(e. effect, duration) {
if (effect == 'ease') {
$(this).next().siideToggle(duration);
} else {
$(thi s ).next( ) .toggl e ():
}
})
,click(function() {
// 1 :
$(thi s ) .trigger('reveal);
}):
,
- trigger.
bi nd effect,
.
chapter_09/12_custom_events_with_params/script.js ()
$(#chooser')
.change(function() {
// 2:
$('# h3:contains(' + S(this).vaK) + ') ')
.trigger('reveal'. 'ease');
}):

,
reveal. ' ease',
.

,
.
350 9. ,

bind
trigger .
chapter_09/l2_custom_events_w1th_params/scr1pt.js ()
$('#bio h3:contains(' + $(this).vaK) + ') ')
,trigger('reveal', [ 'e a s e ',2000]);

()

j Query
:
JavaScript-.
:

, ,
.
, ,
,
. ,
.
j Query
: ()
. ,

, ,
.
.
:
bind, ,
unbi nd! unbi nd :
,
. :
$( ' J.unbindO ;
,
-. ,
. ,
mouseover,
unbind:
$(' ) .unbind('mouseover');
, - ,
unbi nd , .
,
.
click bind.
unbind.
351

chapter_09/l3_event_unb1nd1ng/scr1pt.j s ()
var doToggle - functionO { $(this) .toggleO: };
var doSlide - functionO { $(this) .slideToggleO: }:

$( 'p ')
.click(doToggle)
.click(doSlide):

$ ('p' ) . unbindC'click'. doToggle);


unbi nd
doSlide, doToggle.

?
()
c lic k mouseover, : unclick
unmouseover? . jQuery ,
,
API- .

, ,
.
,
. jQuery

.
, ,
,
.
, ( .)
,
. ,
,
, ,
,
( ).
chapter_09/14_event_namespacing/script.j s ()
$('p ') .bind('mouseover.colorize', functionO {
$(this) .css( background-color . 'lemonchiffon')
})
.bind( 'mouseout.colorize', functionO {
$ (th is).css(background-color'. " );
})
.click(function() {
SCthis)
.trigger('mouseout.colorize')
.unbind( .colorize');
}):
352 9. ,

mouseover
mouseout -.
,
.
: ,
.
c lic k , ,
. , mouseout
.
mouseout. , mouseout,
, ,
. mouseout
.
,
, ,
unbind. ' c o lo r iz e '
.

.
,
DOM. ,
( ).
, unbi nd.


:
,
.

iPhone:
, j Query ,
, :
, !
,
.
, -
, : , ,
PSP,
. .
DOM, -
,
.
, , ,
, .
iPhone.
353

iPhone . mousedown mouseup,


. ,
iPhone,
. j Query
(
, , !), bind
,
.
$ (d o cu m e n t).b in d ('to u ch sta rt'. function(event) {
var o rig in a l = eve n t.o rig in alE v en t;

var x = original.changedTouches[0].pageX;
var = original.changedTouches[0].pageY;

$ ( '# block ) .css({top: y. le f t : x});


} ):

, ,
,
( Firebug
) .
touchstart, ,
.
to u ch start )Query,
o r ig in a l Event j Query- ,
c a llb a ck , o r ig in a l Event
JavaScript - j Query-.
.

block .

MOUSEDOWN MOUSEUP
iPhone,
, mousedown mouseup.
$(document) event .preventDefault.
,
, ,
.

special
,
, special jQ uery
, .
, DOM
, , !
special ,
jQuery,
354 9. ,

.
, ,
( beforeUnIoad). s p e c ia l
jQuery.
c lic k ,
, load .
, ,
.
,
, ,
. ,
, .
s p e c ia l JavaScript-
$. e v e n t.sp e c ia l.
, .
setup , , add
, remove ,
, teardown
( , ,
).
mul t i hover.
ch apter_09/15_special_event/script.js ()
jQ u e ry.e v e n t.sp e cia l.m u ltih o v e r = {
setup: fu n ction (data. namespaces) {
//
}.
add: fu n ction (h an d ler, data, namespaces) {
//
}.
remove: function(namespaces) {
//
}
teardown: function(namespaces) {
//
}.
handler: function(event) {
//
}
}

, ,
. ,
,
bi nd, -.
ch apter_09/15_special_event/script.js ()
$ (' ') . bind( "mul t i hover'. {times: 4}. fu n c tio n O {
$ (th is ).c s s ('b a c k g ro u n d -c o lo r', 'le m o n c h iffo n '):
}):
355

m ulti hover -,
,
, .
,
trig g e r. ,
.
sp e cia l add remove,
mul t i hover
. setup,
,
data.
3.
( jQuery.event .sp e cial .handler) mouseover,
,
.
chapter_09/15_special_event/script. js ( )
setup: fun ction (data, namespaces) {
$ (th is )
.d a t a ( 't im e s '. data && data.tim es || 3)
.bin d('m ou seover'. jQ u e ry .e v e n t.sp e cia l.m u ltih o v e r.h a n d le r);
}.
teardown: function(namespaces) {
$ (th is )
.rem oveData('tim es')
.unbind('mouseover'. jQ u e ry .e v e n t.sp e cia l.m u ltih o v e r.h a n d le r);

data bind special. ,


, ,
!

teardown ,
. data, ,
mouseover unbi nd. .
,
, mouseover,
m ulti hover.

chapter_09/15_special_event/script.js ( )
handler: function(event) {
//
var times = $ ( t h is ) .d a t a ( 't im e s ') || 0:
tim e s - - :
$ ( t h is ) . d a t a ( 't im e s '. tim es):

i f (times <= 0) {
356 9. ,

event.type = ' m ulti hover';


jQ uery.eve nt.handle.appl (th i s .a rguments);

$(th i s ) .u n b in d ('m u ltih o ve r');


}
}

.

.
mul t i hover 1 times data.
0 ( ,
), type
m ulti hover, handle.

, , .
sp ecial
.
, m ulti hover,
, ,
c lic k , $. eve nt.sp ecial . c lic k
. speci al
, , ,
, jQ uery- .


jQuery
,
jQuery,
, .
, , , ,
.


, $ jQuery,
, , . jQuery
,
, .
,
. ,
, $. ,
, JavaScript- Prototype, js $()
JavaScript- getEl ementBy Id,
, .
jQuery 357

, jQ uery
noC o nflict:
jQ u e ry .n o C o n flict( );

, jQ uery $,
- jQuery:
jQ u e ry .n o C o n flic t():
// - jQuery
jQ ueryC'div ) .h id e O ;
// - $ 0
$ c o n te n t" ) .s ty le .d is p la y = 'none';
, $
, jQuery, , ,
. :
jQ uery.noConfli c t ():
jQ u ery(fun ction($) {
$(function()- {
// $
// jQuery
}):
}):
// $
//

jQ uery
jQuery $, , jQuery,
. :
n o C o n flic t jQuery $.
t r k r jQuery:
var t r k r = jQ u e ry .n o C o n flictO :
// - jQuery
t r k r ("d iv " ) .h id e O :
// - $ 0
$("c o n te n t" ) .s ty le .d is p la y = 'none';

noConfl ic t :
var t r k r = {};
t r k r .$ = jQ u e ry .n o C o n flic t(tru e );

,
.




, , :
, , ,
358 9. ,

, - ,
.
, .
queue!
, , ,
.
chapter_09/16_queue_dequeue_animations/script.js ()
$ ( f# button l ) . c lic k ( fu n c t io n () {
$(th i s ) .animate({
height: 200,
width: 200
}. 's lo w ') . t e x t C r o l l i n ' ");
} ):

,
200 200 ,
. animate, fx
, , .
te x t f , , queue
.
chapter_09/16_queue_dequeue_animations/script. js ()
$ ( '# button2') .c lic k ( fu n c tio n ( ) {
$(th i s ) .animate({
height: 200.
width: 200
}. 'slo w ').q u e u e (fu n ctio n () {
$ ( t h is ) . t e x t ( 'r o lle d ! ');
}) . t e x t C r o l l i n ' ");
} ):

animate te x t ,
queue ,
. ... ,
, !
animate , queue fx
.
chapter_09/16_queue_dequeue_animations/script. js ()
$ ( *#button3 ) . c lic k ( f u n c t io n ( ) {
$ ( t h is ) . animated{
height: 200.
width: 200
}. slow ').q u e u e(fu n ction () {
$ ( t h is ) . t e x t ( 'r o lle d ! ');
}) . t e x t C r o llin '" ) .animate({ // animate
//
height: 100,
width: 100
}. 's lo w '):
} ):
jQuery 359

queue , .
on o ff, animate stop, queue
dequeue.
dequeue : jQuery
cal 1back- queue.
chapter_09/16_queue_dequeue_animations/script.js ( )
$ ('# b u tto n 4 ') . c lic k ( fu n c t io n {
$ (th is).an im ate({
height: 200.
width: 200
}. 'slo w ').q u e u e (fu n ctio n 0 {
$ (th i s ) .t e x t ( ' r o lle d ! ' )dequeue():
}) . t e x t C r o llin '" ) .animate({ // animate
height: 100,
width: 100
}. slo w '):
} ):

, , rollin' (
), 200 200 ,
rolled ( ),
100 100 . , ,
queue, , .

JavaScript-
jQuery-
jQ uery
DOM . , jQ uery
DOM, JavaScript-
. , ,
jQuery.
(
s lid e llp JavaScript-?),
.
s lid e llp JavaScript- ,
height - .
,
DOM:
$(myobj):

jQ uery-,
, . data
,
.
. ,
JavaS cript-. ,
. ,
360 9. ,

,
, ,
:
//
var locationD ata = {
name : "Bourgeois Burger C a fe ".
celebCount : 3,
la t : la titu d e ,
Ion : longitude,
}
//
var lo c a to r = M ap.getLocato r(latitude, longitude):

: 1ocator 1ocati onData,


, . lo c a to r
jQuery, data
1ocati onData. jQ uery data,
:
// , , Ja v a S crip t-
$ (lo c a t o r ) .d a ta ('p in _ d a ta '. lo c a tio n D a ta );

,
c lic k locator,
locationData:
// , - ...
var currentData = S (c lic k e d L o c a tio n ).data( p in _ d a ta '):

// , !
a le rtC Y o u selected the lo c a tio n : " + currentData.name):
} ):

, ,
,
, ,
. ,
, . data
, .


API- jQuery UI.

jQ uery UI ... !
, (
). , ,
! ,
-
361


. ,
,
.
,
jQuery UI:
,
- ThemeRoller1.
, jQuery UI.
,
,
, ,
, , .

,
jQuery UI

.
Lightness, Sunny,
, , .
, ,
, ThemeRoller.
ThemeRoller, Gallery ()
. ,
. Download theme
( ),
jQuery UI. ,
. ,
, .
, ,
, .
,
css .
-,
CSS-. ,
.


, , ,
. ThemeRoller
, , .

1 http://jqueryui.cx)m/themert)ller
362 9. ,


(. 9.4).

Section 1

Section 2 Datopicker
r Section 3
December 2009
Nam enim rlsus, moiestie et, porta ac, eliquam ac, $ Mo Tu We Th Fr Sa
rtsus. Qulsque tobortis. Phaseilus peilentesque purus 1 2 3 4 5
in massa. Aenean In pede. Phaseilus ac libero ac
tellus peilentesque semper. Sed ac felts. Sed
7 8 9 10 U 12

commodo, magna quis lacinia ornare, quam ante j'.i* 14 15 16 17 16 19


allquam nisi, eu iacults leo purus venenatis dui. 20 21 22 23 24 25 26

List item one j; 27 28 2$ 30 31


* List item two
___ * List item three
Progress bar

First Second Third


Highlight/Error
Lorem tpsum dolor sit amet, consectetur adipisicing elit, sed do
etusmod tempor inodidunt ut iabore et dolore magna aiiqua, Lit
enim ad minim veniam, quis nostrud exercitation ullamco Hey! Sample ui-state-htghl?ght
laboris nisi ut aliquip ex ea commodo consequat. style.

Dialog k Alert: Sample upstate-error style.


tP Open Dialog

. 9.4. - T h e m e R o lle r jQ u e ry Ul

, , Download
theme ( ).
jQuery UI ,
, , ,
Custom Theme (
). custom-theme ( CSS-
custom-theme). ,
, Advanced Theme
Settings ( )
Theme Folder Name ( ).

INTERNET EXPLORER 6
, ThemeRoller,
, .
jQuery UI
Internet Explorer , ,
jQuery, CSS3 PNG-,
Internet Explorer 6.
,
PNG. , CSS,
!
363


ThemeRoller ,
, , ,
,
CSS-,
DOM.
, jQuery
UI, .
. 9.5 CSS-
, 3,
jQ uery U I- . , (
, 1 ThemeRoller),
-, -
(
jQuery , Lightness, Dot Luv Eggplant).

Gtendetrontx Ciendatrontx

Mr Speaker M r Speaker
Johnny Stardust
Johnny Stardust
After smashing into the limelight * After smashing into the


after a cortroversial run as "local * After smasnfng Imo the Itmeiighi a controversial
weather forecaster with something umelight after a controversial run as local weathei forecaster
to say", Johny Stardust has gone run as local weather wttb som ething to say\ johny
from stren jth .to-stron gth . His Stardust sas gone from
forecast w tlh eomethmy to
current spot as front-man of super-group itrength-to-strength. His current spot as
P a h o o p t makes his exact location a valuable
say. Johny Stardust '-a* pone from front- man o f super-group Pahoopt makes
commodity. strength-to-strength His current spot as his exact location a va uabla com m odity,
A SOLD OUT!
front-marvof super-group Pahoopt makes a so ld oun
his exact location a valuable commodity
Am elia
a S 0 lD OUT!

Amelia

. 9.5. , T h e m e R oller

, ,
, - ,
ThemeRoller. ,
-,
. HTM L-
, , :
<div id= "bion>
<h3>Beau Dandy</h3>
<div>
<img class= ,,p ic" s rc =,,glendatronix.png" />
<span>Glendatronix is the queen o f ....</span>
</div>
<h3>Mr Speaker</h3>
<div>
<img cla ss= "pic" src="mrspeaker.png" />
364 9. ,

<span>After smashing into the limelight ... </span>


</div>

</div>
di v- #bi ,
ui -widget. ,
, ui -helper-reset.
chapter_09/17_themable_components/index. html ()
<div id="bio" class="ui-widget ui-helper-reset">
.

, .
chapter_09/17_themable_components/index. html ()
<h3 class="ui-widget-header ui-corner-aH">Johnny Stardust</h3>
<div class="ui-widget-content">
<img src="johnny-100.png" width="100" height="100 "/>
<span>After smashing into the limelight ... </.span>
</div>
ui -widget-header , a ui -corner-al 1
(, ,
). ui-corner-all
, ui - corner-tl
ui -corner-bottom ,
.
SOLD OUT! (!) ,
,
.
chapter_09/17_themable_components/index.html ()
<div class="ui-state-error">
<span class="ui-icon ui-icon-alert"></span>SOLD OUT!
</div>
ui -state-error , a ui -icon-alert
span.
,
jQ uery UI , ,
,
- ThemeRoller.
, , ,
.
z-index ( Internet Explorer 6)
. 1 -

1 http://jqueiyui.corTydocs/Theming/API
365

,
.

, ,
ThemeRoller, , ,
j Query . ,
,
, ,
ThemeRoller, j Query.
,
!


j Query,
j Query ,
j Query Mobile1, j Query
. j Query Mobile ,
j Query j Query UI,
, ,
j Query Mobile.
,
j Query Mobile, ,
. Alt+Tab
refresh
Ctrl+S, rel oad.
j Query Mobile - - ,
j Query, , ,
j Query . ,
j Query, ,
j Query. ,
,
, tap swi , C S S ,
- , j Query
, .
j Query
Mobile , , -
jQ uery UI, !
< link rel=sty1esheet href="h ttp ://co d e .jquery.com /m obile/1.0/
^ jq u e r y . nrobile-1.0. min. css ">

< scrip t src="h t t p ://code.jq u e ry .com/mobi1e /1 .0/


^ j q u e r y . mobi 1e - 1.0. mi n . js " x / s c r i pt>

i http://jquerymobile.com
366 9. ,

! j Query- CDN
, ,
.
jQuery- CDN
7 24
, .
.
j Query Mobile1, j Query Mobile
,
, ,
. :
j Query Mobile
. , ,

.

,
, jQuery Mobile,
. ,
:

,
Ajax;

Ajax-;
, HTML-,
;
,
.

jQuery Mobile , .
,
jQ uery Mobile , ? ,
,
.
, jQ uery Mobile
, jQuery UI,
, ,
. jQuery Mobile HTML5
CSS3, ,
.
- , , ,
. jQuery Mobile
,
jQuery jQuery UI,

1 http://jquerymobile.com/gbs
367

, ,
. .
, j Query
jQ uery UI, ,
.
,
.
j Query Mobile Pop Trumps: The Jemimas
,
-,
, (. .6-9.8).

. 9 .6 . - P op Trum ps

HOME

. 9.7. Pop Trumps


368 9. ,

Pop Trumps

Congratulations!
The game w as a win

S o far you've played one game,


and w on all of them.

CONTINUE HOME

. 9.8. ,

,
j Query Mobile .
chapter_09/18_getting_mobile/index,html ()
< link re l= stylesh eet href="h ttp ://co d e .jquery.com /m obile/1.0/
jq u e ry . mobi 1e - 1.0. mi n . css ">

<scri-pt src=h t t p ://co de. jq u e ry .com/mobi 1e /1 . 0/


ta* jq u e ry .mobi1e -1 .0 .mi n .j s "></s c r i pt>

j Query Mobile, ,
, .
j Query,

document. ready.
head
.
head , meta.
chapter_09/18_gettingjnobi1 /index.html ()
<meta name=viewport content=,,widthdevice-width. i n i t i a l -s e a le = l,
^ u se r-sca la b le = 0 ">

j Query Mobile HTML5, 5-,


- .
, ,
, 1:1. ,
.
content user-seal able=0
. ,
369

,
.
HTML5. ,
HTML5,
( , , , jQ uery Mobile
HTML5).
chapter_09/18_ g ettin g jn o b ile /in d e x.h tm l ()
<section data-role="page" id=,,home">

</section>
<section data-role="page" id=albums,,>
<header data-role= header">

</header>
<div data-role= ncontent">

</div>
<footer data-role= "footer">

</footer>
</section>
<section data-role="page" id^'album'^

</section>
<section data-role="page" id = "resu lts'^

</section>

s e c tio n
data-ro le , .
di v s e c ti on ,
, d a ta -ro le j Query Mobile ,
section .
id,
. ,
i d , j Query Mobile
.
se cti on
header, di v footer. - data-
ro le , j Query Mobile .
HTML
d a ta -ro le . .
chapter_09/18_getting mobi 1e/index. html ()
<a href='^albums" data-role= ,,button">START</a>

se c ti on c i d home , ,
j Query Mobile,
. data - ro l button, a j Query Mobile
370 9. ,

. - ,
se cti on i d 1bums
.
section i d albums ,
data HTMLS-. header
, , , data-theme.
,
data - rol 1i s tv i ew, d a ta -tra n si t i on
i , .
chapter 09/18_ getting_m obi1 /index.html ()
<header data-role="header" data-theme="b">
<hl>Pop Trumps</hl>
</header>

<div data-role*"content">
<p>Select an album by The Jemimas to play</p>

<ul d a ta -ro le = "listv ie w " data-inset= "true" data-theme="b">


<li><a href=#album" d a ta - tra n s itio n = " flip >
fc^The Jemimas: Debut</a></li>
<1 i><a href="#album" d a ta -tra n s itio n = ,,f l i p M>
fc^This is The Jemimas</a></li>
<1 i><a href="#album" d a ta -tra n s itio n = "flip ">
^ Awkward Third</a></li>
<li><a href="#album" d a ta -tra n s itio n = " f1ip M>
ta*Best o f The Jemimas</a></li>
</ul>
</div>

,
data - rol 1i s tv i ew, ,
, album,
, .
s lid e , slideup, siidedown, pop fade. jQTouch1, , ,
,
. f 1i ,
.
data - rol
DOM.
chapter_09/18_ g e ttin g jn o b ile /in d e x.h tm l ()
<div data-role= "contentM>
<div d ata-ro le = "field co n tain ">
<1 abel for= ,,f lip - a " class= ,,u i-hidden-accessible">
^ S e le c t s iid e r :< /lab el>
<select nam e^'slider" id = " flip -a " data-role= s lid e r "
ta*data-theme="c>

1 http://www.jqtouch.com
371

<option value="no">&#9756; Number ls</option>


<option value="yes">6</option>
</select>

</div>
</div>

<footer d a ta -ro le -"fo o te r" data-theme-"c">


<div data-role= "controlgroup" d ata-type-"h orizon tal">

</div>
</footer>

data - rol e f i el dconta i n,


. , d a ta - ro le
f i el dset .
d a ta - ro le s lid e r f i el dconta in,
co n trol group ( c hgroup HTML5),
.
DOM,
data-rol s i ider, j Query Mobile j Query U I
s e le c t
,
(. 9.9).

. 9 .9 . jQ u e ry M o b ile -
372 9. ,

control group ,
CSS ( -
DOM ). control.group

. data-type="horizontal" div,
control group, ,
, .
data data-direction="reverse",
. , ,
,
data-di recti on . ,
.

; ,
.
chapter_09/18_gettingjnobi 1e/index. html ( )
<a href="#album" data-role=,,button" data-di rection="reverse"
^id="continue">CONTINUE</a>
j Query Mobile, ,
, -
, mobileinit. jQuery Mobile-
,
- , ,
, m obileinit
,
. , ,
. ,
DOM.
, , $(document). ready () ,
document, 1oaded.
,
jQuery, ,
jQ uery Mobile, :
<script src="h ttp : / /code.jquery.com/jquery-1.7.1.m in .js"x /sc rip t>
<script src=". ./p a th /to /y o u r/sc rip ts.js"x /sc rip t>
<script src="h ttp :/ /code.jquery.com/mobile/1.0/
jquery. mobi 1e -1.0. mi n. j s " x /s c r i pt>
, HTML,
mobileinit . ,
, .
, 7,
.
chapter_09/18_gettingjnobi1e / s c r ip t s . js ( )
function doOneUp(which, callback) {
$(which) .nextO .showO .animate({
373

top: "-=50",
opacity: "toggle"
}. 1000.
fu n c tio n () {
$ ( t h is ) .c s s C 't o p " . " " ) .h id e C 'slo w ". ca llb a ck );
} ):
}

, ,
,
, .
, , , , ,
remove() cal 1back. ,
.
Trumps.
chapter_09/18_gettingjnobi1e / s c r ip t . j s ()
fu n ction Trumps () {

//

t h i s . i n i t = fu n ction {
//
}
}

var TRUMPS = new TrumpsO;

$(docum ent).ready(function (event) {


TRUM PS.initO ;
} ):

-,
new rumps , in i t.
i ni t rumps,
, DOM.
, !
rumps t h is , datastore,
,
.
chapter_09/18_getti ngjnobi1e/ scri p t . j s ()
th is .d a ta s to re = {
games: {
win: 0.
draw: 0.
lo ss: 0.
to t a l: 0.
la s t: n u ll .
}-
t a lly : {
374 9. ,

wins: ,
losses:
}
}:

j Query Mobile
, , j Query
Mobile ,
.
API- HTML5 1ocal StorageC ), ,
. ,
. ] Query- data ,
- ,
, datastore. ,
.
chapter_09/18_gettingmobi 1 /s c rip t. js ()
this.gam eover = fu n ction {
var wins = TRUM PS.datastore.tally.w ins,
losses = TR U M P S .datastore.tally.losses,
re s u lt = (wins > losses) ? "win" : (wins === losses) ?
fc*"draw" "lo s s ";

TRUMPS.datastore.games[result] += 1;
TRUMPS.datastore.games["total"] += 1;
TRUMPS.datastore.games["last"] = re s u lt;

$.mobi1e .showPageLoadi ngMsg();

setT i meout(funct i on(){


$.mobi1e .changePage("#results");
TRUMPS. re s u lt O ;
}. 999);
}:

,
, JavaScript ,
. JavaScript-
, ,
.
. ,
, .
.
, datastore.
,
. resul t
, , ,
. -
375

tal , , games,
.
jQ uery Mobile, ,
, $ .mobi 1.
chapter_09/18_getti ngjnobi1e / s c r ip t . js ()
$ .mobi1e . showPageLoadi ngMsg();


.
Ajax,
, .
,
, ,
. jQuery Mobile
Trumps.
chapter_09/18_getti ngjnobi 1e / scri p t . js ()
$ .mobi1e .changePage("#results");

, jQuery Mobile
.
? changePage.
,
jQuery Mobile1.
,
.
3 ,
, ,
.
chapter_09/18_getting mobi1e / s c r ip t s .js ()
this.prom pt = fu n ction 0 {
setTim eout(function() {
$ ("#home" ) . f i nd(" a" ) . fadeIn("s 1ow");
}. 3000);
}:

th i s . reset.
chapter_09/18_getti ngjnobi1e/ scri p t . js ()
t h is . r e s e t = fu n ction 0 {
var switches = [ " # f lip - a " . " # flip - b " ] .
length = sw itch es.len gth ,
cu rren t, i;

fo r (i = 0; i < length; i += 1) {
, curren t = $ (sw itch e s[i]);

i http://jquerymobile.coni/demos
376 9. ,

cu rre n t[ 0 ] .selectedIndex = 0;
c u rre n t.s 1i d e r( " re fre sh " ) . next()
. f i nd( " . u i - s 1i d e r-1 abel - a" ) . t e x t ( random());

fu n ction random 0 {
return Math.floor(Math.random() * 11)

,
, .

. - ,
jQuery, jQuery UI:
cu rren t, s lid e r ( " r e f resh"). next .f in d C . u i- s lid e r - la b e l- a " ) .
^ te x t(ra n d o m O );

jQ uery Mobile-? :
, jQ uery Mobile si i der,
7, .
, ?
, ,
t h is , re s u lt. jQuery
Mobile , . gameover,
datastore,
,
, ,
. ,
. 8
12 . -
: 12 . ,
.
chapter_09/18_getting mobi 1e / s c r ip t . j s ( )
t h is . r e s u lt = fu n ction () {
var re s u lt = TRUMPS.datastore.games.last.
s a lu ta tio n = (re s u lt !== "lo s s ") ? "C ongratu lations!" :
^ " S o r r y about t h a t!" ,
to ta l = TRUMPS.datastore.gam es.total.
wins = TRUMPS.datastore.games.win.
draws = TRUMPS.datastore.games.draw,
losses = TRUMPS.datastore.games.loss,
played = (to ta l === 1) ? "one game" : to ta l + " games",
record:

i f (wins === t o t a l) { record = " a ll" : }


e lse i f (losses === t o t a l) { record = "none": }
e lse i f (wins > (draws + lo sse s)) { record = "most": }
377

else i f (losses > (draws + wins)) { record = "some"; }


else { record = "a few"; }

$(# re su lts" ).fi nd("h2") .te x t(sa lu ta tio n );


$("#res ui t s " ) .fi nd("h3" ) .fi nd("span" ).te x t(resu 11):
$("#resu1ts") .fi nd("p") .findCb") .text(played);
$("#results") .fi nd("p") .findC'span") .text(record):

$.mobi1e .hi dePageLoadingMsg();

.
, jQuery Mobile result.
chapter_09/18_getti ngjnobi1e / scri p t . j s ()
$.mobi1 .hi dePageLoadi ngMsg();
, , ,
showPageLoadingMsg,
gameover. ,
,
,
, thi s .gameover t h i s . result ,
.
chapter_09/18_getti ngjnobi1e / scri p t s . j s ()
this.scored = function (which) {
var result = ($(w hich).find(".ui-btn-text").text() === "WIN")
tafr-? "wins : "losses";

th is.d a ta sto re .ta lly [re su lt] += 1;


i f (th is.d a ta sto re .ta lly [re su lt] > 2) {
this.gameover();
}
}:

thi s . scored ,
album .
ta llie s datastore. -
jQ uery Mobile,
th is. set. ,
jQ uery Mobile, ,
.
chapter_09/18_getti ngjnobi1e / scri p t . js ()
th is .s e t = function 0 {
$(document) . bind( "mobi1ei n i t ". functi on(){
S.mobile.touchOverflowEnabled = true;
} ):

$("#home") .bi nd("swi pe". functi on(event){


378 9. ,

document.location = "#albums";
}):.

$("#albums").bindC'vclick", function(event){
$("#home" ) .f i nd( " .u i-btn-te x t" ).te x t("NEW GAME");
} ).f
i nd("ul" ) .fi nd("a" ).each(function(i ){
var albums = [ "0_debut", "l_thisis". "2_awkward".
^ " 3 _ b e s to f" ] ;

$(this) .bindC'tap", functi on (event){


$(#album").css("background-image".
^["url(graphics/album s/". albums[i], ".p n g )"].jo in (""));
}):
}):

, ,
. jQuery,
j Query Mobile , ,
. th is .s e t.
th is .s e t
mobi lei nit, . $. mobi 1 .
touchOverflowEnabled true. jQuery
Mobile CSS- overflow: auto ,
, ,
. ,
.

jQuery Mobile:
$("#homeM).bind("swipe". function(event){ ...
$("#albums").bindC'vclick". function(event){ ...
$(this).bindC 'tap". functi on (event){ ...
tap swipe - ,
, : -
. , -
, jQuery
,

, ,
. ,
tap, ,
. , !
swipe ,
a tap . , ,
, , vcl i ck, , v
vi rtu a l, , , , . jQ uery Mobile
,
, , ,
379


, vmouse .
vmouseover, vmousedown, vmousemove, vmouseup vmousecancel vcl ick,
,
, START NEWGAME. ,
, ,
.
, .
chapter_09/18_gettingjnobile/script. js ()
$(#a1bum" ).bi nd("pagebeforehi de", functi on(){
TRUMPS. resetO ;
}):

$( .score"),c1ick(function(event) {
doOneUp(this):
TRUMPS.scored(this);

event.preventDefault();
} ).a fte r ( "<span class=' oneup' >+l</span>");

$("#gameover"),bind("tap". this.gameover);// ,

$("#resu 11s"). fi nd(" a"). bi nd (''tap , functi on () {


// datastore
TRUMPS.datastore.tally.wins = 0;
TRUMPS.datastore.tally.losses = 0;
})
}:

thi s . set,
. , tap
resul ts th is,
datastore. ta 11, tap OVER, th is, gameover.
, , ?
tap.
click
jQuery. doOnetlp t h is . scored
, after span,
+1.
j Query Mobile.
chapter_09/18_gettingjnobile/script. js ()
SCfalbum") .bindCpagebeforehide". functionO { ...
, , ,
, , ,
. OnPageUnload
.
t h i s . reset, , , .
380 9. ,


. ,
j Query Mobile, ,
, , ,
. , ...

StarTrackr!:
-,
!
.
. , , ,
,
, Ajax. ,
j Query.
,
. , , ...
, , , .
$( "#n i nj "). hi de () .
; ,

-.


j Query ,
. ,
.
,
j Query
, .
!

j Query 1.
j Query
, .

$.ajax
Ajax- jQ uery $. ajax.
,
.
, , jQuery, .

tru e fa l se
.
,
.

async
async true,
( ,
!),
fa ls e . , , ,
.

1 http://api.jquery.corn/
382 .

cache
Ajax-:
, ,
.
cache fa l se. S c rip t JS0NP
.

crossDomain
j Query fa l se
, tru e .
,
.

global
,
Ajax- .

, fa ls e global.

ifModified
i fModi f i ed (
success) ,
.
, ,
.

isLocal
,
, f i 1 : III
u rl (
).

processData
, , j Query
.
(,
DOM ),
processData fa lse .

traditional
;
j Query .
.
, , true.
$.ajax 383

Ajax- ,
, ,

Ajax-.

accepts
, ,
accepts; : { xm l: 'a p p lic a tio n /
xm l'. t e x t : ' te x t/p i ai n ' }. ,
Ajax.

contents
, j Query
,
. , xml regex /xml /,
a te x t /te x t/.

contentType
contentType
. appl ication/x-www-form -url encoded,
.

context
Ajax- ca llb a ck
wi ndow, . context
, th i s cal 1back
- , JavaScript-
j Query-.

converters
,
dataType dataType.

data
, JavaScript-
data. (
processData),
jQuery .params.
( )! GET,
URL-.
384 .

dataType
contentType , ,
dataType , .
(*/*), xml,
html, s c rip t, json te x t jQuery
.

headers

, .

jsonp
jsonp (
) ,
ca llb a ck . , , ,
, jsonp.

mimeType
, MIME,
.

password

. password.

scriptCharset
s crip tC h a rse t s c r ip t,
Ajax- s c r ip t jsonp.

statusCode

. (
, 404 not found), JavaScript-.

timeout
timeout Ajax, :
, , Ajax- .

type
type Ajax-,
HTTP: GET, POST, PUT DELETE.

url
u rl type
.
$.ajax 385

username
password username,
.

xhrFields

, XHR.

callback

callback
,
, .
6.
compl ete , $. ajax ,
, ,
- . error ,
, success
.
callback, ,
,

. beforeSend ,
,
. j Que
ry-. ,
. ,
-: false, .
jsonpCal 1back ( )
, j Query
JSONP-. ,
, .
Ajax
XMLHTTPRequest ( XHR).
, j Query
XHR Ajax-.
, ,
xhr. ,
.
dataFi 1ter.

, . ,
, . dataFi Iter
, ,
.
386 .

(.support
,
,
. :
. , ,
, ,
,
.
j Query,
,
JavaScript, , ,
support.
6 ,
. .
tru e fa ls e , ,
, if / t h e n / e ls e
, , :
var domObject = document.getElementById('content'):
i f ($.support.cssFloat) {
domObject.style.cssFloat = "left";
} e lse {
d o m O b je ct.sty le .sty le F lo a t = " le f t " :
}
.

ajax
true,
XHR.

boxModel
boxModel ( nul 1,
tru e fa ls e ) true,
W3C.

checkClone
,
checked , checkClone fa lse .

checkOn
true,
"on", .
(.support 387

cors
true,
XHR, wi thCredenti al s,

.

changeBubbles
,
,
.
, ,
,
change, changeBubbles.

cssFloat
cssFl oat , .
, cssFl oat
float JavaScript ( fl oat ,
JavaScript, ). Internet
Explorer styleFloat cssFloat.

hrefNormalized
, , ,
, !
href Normal i zed true,
.

htmISerialize
, (,
link script) innerHTML,
html Serial ize. Internet Explorer
,
-, , .

leadingWhitespace
leadingWhitespace ,
DOM
. i nnerHTML Internet Explorer
, - ,
jQuery-,
.
388 .

noCloneEvent
DOM
, .
, noCloneEvent
true.

opacity
opacity:
- . ,
o p a city JavaScript (, ,
, jQuery). op acity
, ,
,
.

optDisabled
true, option sel ect
.

optSelected
true, opti on, ,
, .

scriptEval
-
s c rip t. s c ri ptEval ,
appendChi 1d s c r i p t . text.

style
, ,
g e tA ttrib u te . ,
g e tA ttri bute( "s ty l " ) , s ty l .

submitBubbles
, , submit,
submi tBubbl es. ,
,
changeBubbles.
(.support 389

tbody
, tbody
ta b le ,
DOM. ,
, tbody. tru e (),
, ,
tbody .
support ,
, .
,
, .
support, ,
,
, .

,
, j Query -
W3C.
,
. , ,
!
j Query 1.


9 : type
( ,
).

DOM, , target.
j Query,
DOM j Query. ,
,
, (
), relatedTarget.
,
, re l atedTarget .
data ,
, ,
, .

1
http://docs.jquery.com/Events/jQuery. Event
390 .

, ,
timeStamp: , ,
, . ,
- t r ip le - c lic k ,
, ,

.


, preventDefault
stopPropagation, ,
. stoplmmediate
Propagation, , stopPropagation.
stopPropagati on ,
, stopImmediatePropagation
,
.
, .
isD efau ltP re ve n ted , isPropagationStopped isImmediatePropagationStopped
, fa ls e ,
.


, ,
:
. :
//
$ ( ' ) .b in d ( c l i c k ' , fu n ction (e) {
$ ( t h is ) .tex t(e .p a g e X );
}):
//
var = $ .Event 'c l i c k ' ) :
. pageX = 100;
e.pageY = 100;
$ ( 'p ) .t r ig g e r ( e ) ;

c lic k
pageX pageY. ,
.
,
JavaScript
: j Query JavaScript,
j Query
, JavaScript.
, JavaScript,
.

JAVASCRIPT
JavaScript,
JavaScript: ( C ro c k fo rd D. JavaScript: The
Good Parts. Sebastopol. O'Reilly, 2008). ,
, JavaScript
.


JavaScript . ,
Java, ,
. JavaScript
. ,
, :
var = 2:
var b = "two":
var = "2";
a le rt(ty p e o f ):// ""
a le rt(ty p e o f b ) :// ""
a le rt(ty p e o f ) : / / ""

:
. , JavaScript ,
:
a le r t ( * ):// 4
a le r t ( + b):/ / 2
392 . , JavaScript

a le r t ( * ) ; / / 4
a le rt(ty p e o f ( * ) ) ;/ / ""
a le rt(ty p e o f ( + )) ;/ / ""
a le rt(ty p e o f ( * ) ) ; / / ""

, +, JavaScript
, , .
s trin g .
(*), JavaScript ,
.
, -
. JavaScript,
, , JavaScript,
. :
a le rt( a + ) : / / 22
a le r t (a + p a r s e ln t ( c ) ) :// 4

JQUERY JAVASCRIPT
jQuery ,
S.type. .
, $.type(5) "number", $ .type([])
"array".


(=)
.
, JavaScript 1.3.
, ,
:
var = 2;
var b = "2":


. ,
, , :
var = ( == b);

=, ==,
.
tru e, JavaScript
. ,
JavaScript
.
true false 393


, (!=).
false, , true, :
var d = ( != b);
d false, b .
,
.
JavaScript 1.3 -
, ,
===.
var = ( === );
,
, ,
. d fal se:
b 2,
.
, , ,
,
:
var f = ( !== b);
f true, ,
,
.
, ,
, !

true false
JavaScript true fal se:
var jQuerylsFun = true:
var javaScriptlsJava = false:
, JavaScript .
,
tru e fa lse .
. , i f ( vari abl ) { ... }, vari abl
:
, v a ria b le 5, "H ello . W orld! ",
. , tru e
, , , fa l se,
.
394 . , JavaScript

JavaScript :
true;
1 ( );
"0( );
"f 1se ( );
fu n ctio n O {} ( );
{} ( );
[] ( ).
:
false ;
0 ( );
"" ( );
n u ll;.
undefined;
NaN ( , Not a Number ( -
.
NOT
. ,
:
var = 0:
var b = 1:

i f ( !b) {
// -
}
e ls e i f ( ! ) {
// -
}
NOT true, fa ls e ,
, , fa lse , true.
b , !b fa l se,
, ! true, el se i f .
: == true,
, true:
var = true;
var b = 1;

a le rt( a b ) :// tru e


a le rt( a *= b ) :// fa ls e
a le rt(a !- b): // fa ls e
a le rt(a ! = b); // tru e
jQuery 395

,
true fa l se. :
- !


, = = null j 1 ===== undefined == n u ll.
, =!

jQuery
, j Query - .
JavaScript. JavaScript , ,
jQuery, .
jQ uery JavaScript:
$ (" d iv M); // jQuery
docum ent.querySelectorAl1( " d iv " ) : // JavaS crip t

$("<div/>"): // jQuery
docum ent.createElem ent("div"); // JavaS crip t

myElement.addClass( "cl assy "); // jQuery


newDi v .c la s s L i s t .add("cl a ssy "): // JavaS crip t

n e w D iv .to g g le C la ssC c la ssy "); // jQuery


.. newDi v. c l assLi s t. toggle( "cl a ssy "): // JavaS crip t

$ ("#my El ement "J .n e x tO : // jQuery .


document.getElementByldC"myElement").nextSibling; //
U
JavaS crip t

, jQ uery- .
, JavaScript- ,
. , jQuery , ,
, JavaScript, jQuery --
.

, , ,
jQ,uery.*

,



j Query, j Query-
,
. , ,
, . ,
, ,
.

selector context
, se le cto r context.
, j Query .
, ,
, .
selector
j Query, $( * : f i r s t ') .selector ": first".
, ,
.
,
j Query context ,
context, . ,
context , j Query,
selector:
var s e le c to r = $ ( ' :f i r s t '. '# con ten t') .s e le c to r
var context = S C p i f i r s t '. '# co n ten t') .context

se le c to r "#content : f ir s t " , a context


Document (,
jQuery- pushstack 397

). context ,
DOM:
var domContext = $ ( *#content')[0 ]; //
// D0M
var s e le c to r = $ ( ' : f i r s t ' , dom Context).selector;
var context = $ ( ' p : f i r s t ' , domContext).context;

s e le c to r : f i rs t " , a context
DOM (
<div id="content">).
DOM ,
. jQuery
,
context Document.

jQ uery- pushstack
j Query
j Query ,
.
, ,
,
.
pushstack. j Query-
.
,
, .
.
,
:
jQ uery.fn.surrounds = fu n c tio n {
var prev = th is .in d e x O == 0 ?
t h is . s ib lin g s ( ' : l a s t ' ) :
th is .p re v O ;
var next = th is .in d e x O == t h is . s ib lin g s O .length ?
t h i s .s ib lin g s ( ' : f i r s t * ) :
t h is .n e x tO ;

var newStack = prev.add(n ext);


return this.pushStack(newStack. 'su rrou n ds', ' ' ) ;
}:

add.
pushstack, ,
, .
398 . ,

selector, .
,
categories :
$(^categories l i : f i r s t ')
.surrounds
.css(co lo r', 'r e d ')
.end()
.c ss('c o lo r', 'b lu e');
, ,
.
pushStack, jQuery .
end (
) .
pushStack .
jQuery, ,
.
, end ,
jQuery-. jQuery,
, end prevObject.
jQuery-
, th is .prevObject. , ,
, !


, jQuery,
jQuery jQuery:
. ?
, -
, jQuery (
, ). , ,
, .min .
jQ uery 250 , 100 ,
.
,
Gzip (
), -
.
,
.
-, ,

, , .
399

, ,
.
JavaScript
, .
, ,
YUI Compressor Yahoo1 Closure Compiler Google12.
UglifyJS3,
j Query .
,
.
, JavaScript-
. , ,
:
$growl.animate({
border: "none",
height: 0.
marginBottom: 0.
marginTop: "-6px",
opacity : 0.
paddingBottom: 0.
paddingTop: 0.
queue: false
}
:
Sgrowl.animate({border:".height:0,marginBottom:0.marginTop:
ta*"-6px",opacity :0,paddingBottom:0,paddingTop:0,queue:false}
, , ,
, .
,
. 9000
j Query, ,
. ,
.

. Closure Compiler
YUI Compressor Java-,
. UglifyJS JavaScript
Node.JS. Node.JS
, Java,
, .

1 http://developer.yahoo.cx)m/yui/compressor
2 http://code.googte.confVclosure/compiler
3 https://github.com/mishoo/UgllfyJS
400 . ,

, hel 1. js Closure Compiler


:
java -jar compiler.jar --js hello.js --js_output_file
^hello-compiled, js
,

.

, ,
- Closure Compiler1,
Compile ().

( ,
, , UglifyJSI).
,
; ,

.

1
http://closure-com piler.appspotcom

Оценить