Sams - Pure JavaScript, Second Edition
Sams - Pure JavaScript, Second Edition
Sams - Pure JavaScript, Second Edition
PURE
JavaScript
Second Edition
R. Allen Wyke
Jason D. Gilliam
Charlton Ting
Sean Michaels
All rights reserved. No part of this book shall be reproduced, stored in a DEVELOPMENT EDITOR
retrieval system, or transmitted by any means, electronic, mechanical, Jonathan Steever
photocopying, recording, or otherwise, without written permission from
MANAGING EDITOR
the publisher. No patent liability is assumed with respect to the use of the
Charlotte Clapp
information contained herein. Although every precaution has been taken in
the preparation of this book, the publisher and author assume no responsi- PROJECT EDITOR
bility for errors or omissions. Nor is any liability assumed for damages Elizabeth Finney
resulting from the use of the information contained herein.
COPY EDITOR
International Standard Book Number: 0-672-32141-6 Rhonda Tinch-Mize
Library of Congress Catalog Card Number: 00-111512 INDEXER
Printed in the United States of America Sandra Henselmeier
First Printing: August 2001 PROOFREADERS
04 03 02 01 4 3 2 1 Antonio Reitz
Rebecca Martin
Trademarks Debra Sexton
All terms mentioned in this book that are known to be trademarks or ser- TECHNICAL EDITOR
vice marks have been appropriately capitalized. Sams Publishing cannot Andrew Watt
attest to the accuracy of this information. Use of a term in this book
should not be regarded as affecting the validity of any trademark or ser- TEAM COORDINATOR
vice mark. Amy Patton
Overview
Introduction 1
CD-ROM
10 DOM Core CD:1403
11 DOM HTML CD:1479
12 DOM Events CD:1731
13 DOM CSS CD:1767
14 JScript RunTime CD:1823
15 Windows Script Host CD:1927
00 0672321419 FM 7/24/01 11:46 AM Page iv
Contents
INTRODUCTION 1
Arithmetic ........................................................................................45
String ................................................................................................49
Assignment ......................................................................................50
Logical ..............................................................................................54
Comparison ......................................................................................55
Conditional ......................................................................................58
Bitwise ..............................................................................................59
Precedence ........................................................................................61
Loops and Conditionals ........................................................................62
Conditionals......................................................................................62
Loops ................................................................................................65
Functions................................................................................................76
Syntax ..............................................................................................77
Call By Value Versus Call By Reference ........................................77
Returning Values ..............................................................................79
Functions as Objects ........................................................................80
Moving On ............................................................................................81
vi
vii
viii
// (Comment) ..................................................................................216
/= (Division Assignment) ..............................................................217
?: (Conditional) ..............................................................................218
^ (Bitwise Exclusive OR) ..............................................................219
^= (Bitwise Exclusive OR Assignment) ........................................220
| (Bitwise OR) ................................................................................221
|| (Logical OR) ................................................................................222
|= (Bitwise OR Assignment) ..........................................................223
~ (Bitwise NOT) ............................................................................224
+ (Addition) ....................................................................................225
++ (Increment)................................................................................226
+= (Addition Assignment)..............................................................227
< (Less Than)..................................................................................228
<< (Shift Left) ................................................................................229
<<= (Shift Left Assignment) ..........................................................230
<= (Less Than or Equal) ................................................................231
= (Assignment) ..............................................................................232
-= (Subtraction Assignment) ..........................................................232
== (Equal) ......................................................................................233
=== (Identity) ................................................................................234
> (Greater Than) ............................................................................235
>= (Greater Than or Equal)............................................................236
>> (Shift Right with Sign) ............................................................237
>>= (Shift Right with Sign Assignment) ......................................238
>>> (Shift Right Zero Fill) ............................................................239
>>>= (Shift Right Zero Fill Assignment) ......................................240
abstract............................................................................................241
ActiveXObject ................................................................................241
Arguments ......................................................................................243
Arguments.callee ............................................................................244
Arguments.caller ............................................................................246
Arguments.length ..........................................................................247
Array ..............................................................................................249
Array.concat( ) ................................................................................251
Array.constructor ............................................................................253
Array.index ....................................................................................253
Array.input......................................................................................254
Array.join() ....................................................................................254
Array.lastIndex ..............................................................................255
Array.length ....................................................................................256
Array.pop() ....................................................................................257
Array.prototype ..............................................................................258
Array.push()....................................................................................259
Array.reverse() ................................................................................260
Array.shift() ....................................................................................261
00 0672321419 FM 7/24/01 11:46 AM Page ix
ix
Array.slice() ....................................................................................262
Array.sort() ....................................................................................263
Array.splice() ..................................................................................265
Array.toSource() ............................................................................267
Array.toString() ..............................................................................268
Array.unshift() ................................................................................269
Array.unwatch() ..............................................................................270
Array.valueOf() ..............................................................................271
Array.watch() ..................................................................................271
Automation ....................................................................................272
boolean............................................................................................272
Boolean ..........................................................................................273
Boolean.constructor........................................................................275
Boolean.prototype ..........................................................................275
Boolean.toSource() ........................................................................276
Boolean.toString() ..........................................................................277
Boolean.unwatch()..........................................................................278
Boolean.valueOf() ..........................................................................279
Boolean.watch()..............................................................................279
break ..............................................................................................280
byte ................................................................................................281
case ................................................................................................282
char ................................................................................................282
class ................................................................................................282
const................................................................................................283
continue ..........................................................................................283
Date ................................................................................................285
Date.constructor..............................................................................289
Date.getDate() ................................................................................289
Date.getDay() ................................................................................290
Date.getFullYear() ..........................................................................291
Date.getHours() ..............................................................................292
Date.getMilliseconds() ..................................................................292
Date.getMinutes() ..........................................................................293
Date.getMonth() ............................................................................294
Date.getSeconds() ..........................................................................295
Date.getTime()................................................................................296
Date.getTimezoneOffset() ..............................................................297
Date.getUTCDate() ........................................................................298
Date.getUTCDay() ........................................................................298
Date.getUTCFullYear() ..................................................................300
Date.getUTCHours() ......................................................................300
Date.getUTCMilliseconds() ..........................................................301
Date.getUTCMinutes() ..................................................................301
Date.getUTCMonth() ....................................................................302
00 0672321419 FM 7/24/01 11:46 AM Page x
Date.getUTCSeconds() ..................................................................304
Date.getVarDate() ..........................................................................304
Date.getYear() ................................................................................305
Date.parse() ....................................................................................306
Date.prototype ................................................................................307
Date.setDate() ................................................................................308
Date.setFullYear() ..........................................................................309
Date.setHours() ..............................................................................310
Date.setMilliseconds()....................................................................310
Date.setMinutes() ..........................................................................311
Date.setMonth()..............................................................................312
Date.setSeconds() ..........................................................................313
Date.setTime() ................................................................................314
Date.setUTCDate() ........................................................................314
Date.setUTCFullYear() ..................................................................315
Date.setUTCHours() ......................................................................316
Date.setUTCMilliseconds()............................................................317
Date.setUTCMinutes() ..................................................................318
Date.setUTCMonth()......................................................................318
Date.setUTCSeconds() ..................................................................319
Date.setYear() ................................................................................320
Date.toGMTString() ......................................................................321
Date.toLocaleString() ....................................................................322
Date.toSource() ..............................................................................322
Date.toString() ................................................................................323
Date.toUTCString() ........................................................................324
Date.unwatch() ..............................................................................325
Date.UTC() ....................................................................................326
Date.valueOf() ................................................................................327
Date.watch ......................................................................................328
debugger ........................................................................................328
decodeURI() ..................................................................................329
decodeURIComponent() ................................................................330
default ............................................................................................331
delete ..............................................................................................331
do ....................................................................................................332
do...while ........................................................................................332
double ............................................................................................333
else ..................................................................................................334
encodeURI() ..................................................................................334
encodeURIComponent() ................................................................335
enum ..............................................................................................336
Enumerator ....................................................................................336
Enumerator.atEnd() ........................................................................337
Enumerator.item() ..........................................................................338
00 0672321419 FM 7/24/01 11:46 AM Page xi
xi
Enumerator.moveFirst()..................................................................339
Enumerator.moveNext() ................................................................340
Error................................................................................................341
Error.description ............................................................................342
Error.message ................................................................................343
Error.name ......................................................................................343
Error.number ..................................................................................344
escape() ..........................................................................................345
eval() ..............................................................................................346
export ..............................................................................................347
extends ............................................................................................348
false ................................................................................................349
final ................................................................................................349
float ................................................................................................349
for....................................................................................................350
for...in..............................................................................................351
function ..........................................................................................352
Function() ......................................................................................352
Function.apply() ............................................................................353
Function.arguments ........................................................................354
Function.arity..................................................................................355
Function.call() ................................................................................356
Function.callee................................................................................357
Function.caller ................................................................................358
Function.constructor ......................................................................359
Function.length ..............................................................................360
Function.prototype..........................................................................360
Function.toSource() ........................................................................361
Function.toString() ........................................................................362
Function.valueOf()..........................................................................363
GetObject........................................................................................364
Global ............................................................................................365
Global.decodeURI() ......................................................................366
Global.decodeURIComponent() ....................................................367
Global.encodeURI() ......................................................................368
Global.encodeURIComponent() ....................................................369
Global.escape() ..............................................................................370
Global.eval() ..................................................................................371
Global.Infinity ................................................................................373
Global.isFinite()..............................................................................374
Global.isNaN() ..............................................................................375
Global.NaN ....................................................................................376
Global.Number() ............................................................................376
Global.parseFloat() ........................................................................377
Global.parseInt() ............................................................................378
00 0672321419 FM 7/24/01 11:46 AM Page xii
xii
Global.String()................................................................................379
Global.unescape() ..........................................................................380
Global.undefined ............................................................................380
goto ................................................................................................381
if......................................................................................................381
if...else ............................................................................................382
implements......................................................................................383
import..............................................................................................383
in ....................................................................................................384
Infinity ............................................................................................385
instanceof........................................................................................386
int ....................................................................................................387
interface ..........................................................................................387
isFinite()..........................................................................................387
isNaN() ..........................................................................................388
java..................................................................................................389
javaArray ........................................................................................390
javaArray.length..............................................................................391
javaArray.toString ..........................................................................392
javaClass ........................................................................................392
javaObject ......................................................................................393
javaPackage ....................................................................................394
JSException ....................................................................................395
JSException.getWrappedException() ............................................396
JSObject..........................................................................................396
JSObject.call() ................................................................................398
JSObject.equals()............................................................................399
JSObject.eval()................................................................................400
JSObject.getMember()....................................................................401
JSObject.getSlot() ..........................................................................403
JSObject.getWindow()....................................................................403
JSObject.removeMember() ............................................................404
JSObject.setMember() ....................................................................405
JSObject.setSlot() ..........................................................................405
JSObject.toString() ........................................................................406
label ................................................................................................406
long ................................................................................................407
Math() ............................................................................................408
Math.abs() ......................................................................................409
Math.acos() ....................................................................................410
Math.asin()......................................................................................411
Math.atan() ....................................................................................412
Math.atan2() ..................................................................................413
Math.ceil() ......................................................................................414
Math.cos() ......................................................................................415
00 0672321419 FM 7/24/01 11:46 AM Page xiii
xiii
Math.E ............................................................................................416
Math.exp() ......................................................................................417
Math.floor() ....................................................................................418
Math.LN10 ....................................................................................419
Math.LN2 ......................................................................................420
Math.log() ......................................................................................420
Math.LOG10E ................................................................................421
Math.LOG2E ..................................................................................422
Math.max() ....................................................................................423
Math.min()......................................................................................424
Math.PI ..........................................................................................425
Math.pow() ....................................................................................426
Math.random()................................................................................427
Math.round() ..................................................................................428
Math.sin() ......................................................................................429
Math.sqrt() ......................................................................................430
Math.SQRT1_2 ..............................................................................431
Math.SQRT2 ..................................................................................432
Math.tan() ......................................................................................432
Math.toSource()..............................................................................433
Math.toString() ..............................................................................434
Math.unwatch() ..............................................................................435
Math.watch() ..................................................................................435
NaN ................................................................................................436
native ..............................................................................................436
netscape ..........................................................................................437
new..................................................................................................437
null ..................................................................................................438
Number() ........................................................................................438
Number() ........................................................................................439
Number.constructor ........................................................................440
Number.MAX_VALUE ..................................................................441
Number.MIN_VALUE ..................................................................442
Number.NaN ..................................................................................443
Number.NEGATIVE_INFINITY ..................................................443
Number.POSITIVE_INFINITY ....................................................444
Number.prototype ..........................................................................445
Number.toExponential() ................................................................446
Number.toFixed() ..........................................................................447
Number.toLocaleString()................................................................447
Number.toPrecision()......................................................................448
Number.toSource() ........................................................................448
Number.toString() ..........................................................................449
Number.unwatch() ..........................................................................449
Number.valueOf() ..........................................................................450
00 0672321419 FM 7/24/01 11:46 AM Page xiv
xiv
Number.watch() ..............................................................................451
Object() ..........................................................................................452
Object.constructor ..........................................................................453
Object.eval() ..................................................................................454
Object.prototype ............................................................................455
Object.toSource()............................................................................455
Object.toString() ............................................................................456
Object.unwatch() ............................................................................457
Object.valueOf() ............................................................................458
Object.watch() ................................................................................458
package ..........................................................................................459
Packages ........................................................................................460
Packages.className ......................................................................461
Packages.java..................................................................................461
Packages.netscape ..........................................................................462
Packages.sun ..................................................................................463
parseFloat() ....................................................................................464
parseInt() ........................................................................................465
private ............................................................................................465
protected ........................................................................................466
public ..............................................................................................466
RegExp() ........................................................................................466
RegExp,$* ......................................................................................469
RegExp.$& ....................................................................................470
RegExp,$_ ......................................................................................470
RegExp.$` ......................................................................................471
RegExp.$’ ......................................................................................472
RegExp.$+ ......................................................................................473
RegExp.$1,$2,..$9 ..........................................................................474
RegExp.constructor()......................................................................475
RegExp.compile() ..........................................................................476
RegExp.exec() ................................................................................477
RegExp.global ................................................................................478
RegExp.ignoreCase ........................................................................479
RegExp.input ..................................................................................480
RegExp.lastIndex............................................................................481
RegExp.lastMatch ..........................................................................481
RegExp.lastParen............................................................................482
RegExp.leftContext ........................................................................483
RegExp.multiline............................................................................484
RegExp.prototype ..........................................................................485
RegExp.rightContext ......................................................................486
RegExp.source ................................................................................487
RegExp.test() ..................................................................................487
RegExp.toSource() ........................................................................488
00 0672321419 FM 7/24/01 11:46 AM Page xv
xv
RegExp.toString() ..........................................................................489
RegExp.unwatch() ..........................................................................490
RegExp.valueOf() ..........................................................................491
RegExp.watch() ..............................................................................492
return ..............................................................................................493
ScriptEngine ..................................................................................494
ScriptEngineBuildVersion ..............................................................494
ScriptEngineMajorVersion ............................................................495
ScriptEngineMinorVersion ............................................................495
short ................................................................................................496
static................................................................................................496
String (Function) ............................................................................497
String (Object) ................................................................................497
String.anchor()................................................................................501
String.big()......................................................................................502
String.blink() ..................................................................................503
String.bold()....................................................................................503
String.charAt()................................................................................504
String.charCodeAt() ......................................................................505
String.concat() ................................................................................507
String.constructor ..........................................................................507
String.fixed() ..................................................................................508
String.fontcolor() ............................................................................509
String.fontsize() ..............................................................................509
String.fromCharCode() ..................................................................510
String.indexOf()..............................................................................511
String.italics() ................................................................................512
String.lastIndexOf() ........................................................................513
String.length ..................................................................................514
String.link() ....................................................................................515
String.localeCompare() ..................................................................515
String.match() ................................................................................516
String.prototype ..............................................................................517
String.replace() ..............................................................................519
String.search() ................................................................................520
String.slice() ..................................................................................521
String.small() ..................................................................................522
String.split()....................................................................................522
String.strike()..................................................................................524
String.sub() ....................................................................................525
String.substr() ................................................................................526
String.substring() ............................................................................527
String.sup() ....................................................................................528
String.toLocaleLowerCase() ..........................................................528
String.toLocaleUpperCase() ..........................................................529
00 0672321419 FM 7/24/01 11:46 AM Page xvi
xvi
String.toLowerCase()......................................................................530
String.toSource() ............................................................................531
String.toString()..............................................................................532
String.toUpperCase()......................................................................533
String.unwatch() ............................................................................533
String.valueOf() ..............................................................................534
String.watch() ................................................................................535
sun ..................................................................................................536
super................................................................................................537
switch..............................................................................................537
synchronized ..................................................................................539
this ..................................................................................................539
throw ..............................................................................................541
throws ............................................................................................543
transient ..........................................................................................543
true ..................................................................................................544
try...catch...finally ..........................................................................544
typeof ..............................................................................................546
undefined ........................................................................................548
unescape() ......................................................................................548
var ..................................................................................................549
VBArray ........................................................................................551
VBArray.dimensions()....................................................................552
VBArray.getItem()..........................................................................553
VBArray.lbound() ..........................................................................555
VBArray.toArray()..........................................................................556
VBArray.ubound() ..........................................................................557
void ................................................................................................559
volatile ............................................................................................559
while ..............................................................................................560
with ................................................................................................561
8 CLIENT-SIDE 563
Anchor ............................................................................................564
Anchor.name ..................................................................................566
Anchor.text ....................................................................................567
Anchor.unwatch() ..........................................................................568
Anchor.watch() ..............................................................................569
Anchor.x ........................................................................................570
Anchor.y ........................................................................................571
Applet ............................................................................................572
Area ................................................................................................573
Area.handleEvent() ........................................................................576
Area.hash ........................................................................................578
Area.host ........................................................................................580
00 0672321419 FM 7/24/01 11:46 AM Page xvii
xvii
Area.hostname ................................................................................582
Area.href ........................................................................................583
Area.onDblClick ............................................................................584
Area.onMouseOut ..........................................................................585
Area.onMouseOver ........................................................................586
Area.pathname................................................................................587
Area.port ........................................................................................588
Area.protocol ..................................................................................589
Area.search ....................................................................................590
Area.target ......................................................................................591
Area.unwatch() ..............................................................................594
Area.watch() ..................................................................................596
Button ............................................................................................597
Button.blur() ..................................................................................599
Button.click()..................................................................................600
Button.focus() ................................................................................601
Button.form ....................................................................................602
Button.handleEvent()......................................................................603
Button.name....................................................................................605
Button.onBlur ................................................................................606
Button.onClick................................................................................606
Button.onFocus ..............................................................................607
Button.onMouseDown....................................................................608
Button.onMouseUp ........................................................................608
Button.type ....................................................................................609
Button.unwatch() ............................................................................610
Button.value....................................................................................612
Button.watch() ................................................................................613
Checkbox ........................................................................................614
Checkbox.blur()..............................................................................617
Checkbox.checked..........................................................................618
Checkbox.click() ............................................................................620
Checkbox.defaultChecked ..............................................................621
Checkbox.focus()............................................................................622
Checkbox.form ..............................................................................623
Checkbox.handleEvent() ................................................................624
Checkbox.name ..............................................................................626
Checkbox.onBlur............................................................................627
Checkbox.onClick ..........................................................................628
Checkbox.onFocus ........................................................................630
Checkbox.type ................................................................................631
Checkbox.unwatch() ......................................................................632
Checkbox.value ..............................................................................634
Checkbox.watch() ..........................................................................635
Document........................................................................................636
00 0672321419 FM 7/24/01 11:46 AM Page xviii
xviii
document.alinkColor ......................................................................637
document.all ..................................................................................638
document.all.item() ........................................................................639
document.all.tags() ........................................................................640
document.anchors ..........................................................................641
document.anchors.length ................................................................642
document.applets ............................................................................643
document.applets.length ................................................................644
document.bgColor ..........................................................................645
document.captureEvents() ..............................................................646
document.classes ............................................................................648
document.close() ............................................................................651
document.contextual() ....................................................................652
document.cookie ............................................................................652
document.domain ..........................................................................653
document.embeds ..........................................................................654
document.embeds.length ................................................................655
document.fgColor ..........................................................................655
document.formName ......................................................................656
document.forms ..............................................................................657
document.forms.length ..................................................................658
document.getSelection() ................................................................659
document.handleEvent() ................................................................660
document.ids ..................................................................................661
document.images ............................................................................664
document.images.length ................................................................665
document.lastModified ..................................................................666
document.layers..............................................................................667
document.layers.length ..................................................................668
document.linkColor ........................................................................669
document.links................................................................................670
document.links.length ....................................................................671
document.onClick ..........................................................................672
document.onDblClick ....................................................................673
document.onKeyDown ..................................................................674
document.onKeyPress ....................................................................675
document.onKeyUp ........................................................................676
document.onLoad ..........................................................................677
document.onMouseDown ..............................................................677
document.onMouseUp....................................................................678
document.onUnLoad ......................................................................679
document.open() ............................................................................680
document.plugins............................................................................681
document.plugins.length ................................................................682
document.referrer ..........................................................................682
00 0672321419 FM 7/24/01 11:46 AM Page xix
xix
document.releaseEvents() ..............................................................683
document.routeEvent() ..................................................................685
document.tags ................................................................................687
document.title ................................................................................690
document.unwatch() ......................................................................690
document.URL ..............................................................................692
document.vlinkColor ......................................................................692
document.watch() ..........................................................................693
document.write() ............................................................................694
document.writeln() ........................................................................695
Embed ............................................................................................697
Event ..............................................................................................698
event.data ........................................................................................701
event.height ....................................................................................702
event.layerX....................................................................................703
event.layerY....................................................................................704
event.modifiers ..............................................................................705
event.pageX ....................................................................................707
event.pageY ....................................................................................708
event.screenX..................................................................................709
event.screenY..................................................................................711
event.target......................................................................................712
event.type........................................................................................713
event.unwatch() ..............................................................................715
event.watch() ..................................................................................716
event.which ....................................................................................718
event.width......................................................................................718
Event.ABORT ................................................................................720
Event.BLUR ..................................................................................721
Event.CHANGE ............................................................................722
Event.CLICK..................................................................................723
Event.DBLCLICK..........................................................................724
Event.DRAGDROP ........................................................................725
Event.ERROR ................................................................................726
Event.FOCUS ................................................................................728
Event.KEYDOWN ........................................................................729
Event.KEYPRESS..........................................................................730
Event.KEYUP ................................................................................731
Event.LOAD ..................................................................................732
Event.MOUSEDOWN....................................................................733
Event.MOUSEMOVE ....................................................................734
Event.MOUSEOUT........................................................................735
Event.MOUSEOVER ....................................................................736
Event.MOUSEUP ..........................................................................737
Event.MOVE ..................................................................................738
00 0672321419 FM 7/24/01 11:46 AM Page xx
xx
Event.RESET..................................................................................739
Event.RESIZE ................................................................................741
Event.SELECT ..............................................................................742
Event.SUBMIT ..............................................................................743
Event.UNLOAD ............................................................................744
FileUpload ......................................................................................745
FileUpload.blur() ............................................................................747
FileUpload.focus()..........................................................................748
FileUpload.form ............................................................................749
FileUpload.handleEvent() ..............................................................750
FileUpload.name ............................................................................752
FileUpload.onBlur ..........................................................................753
FileUpload.onChange ....................................................................754
FileUpload.onFocus........................................................................755
FileUpload.select() ........................................................................756
FileUpload.type ..............................................................................757
FileUpload.unwatch() ....................................................................758
FileUpload.value ............................................................................759
FileUpload.watch() ........................................................................760
Form................................................................................................761
Form.action ....................................................................................763
Form.elements ................................................................................764
Form.elements.length ....................................................................765
Form.encoding................................................................................766
Form.handleEvent() ........................................................................767
Form.length ....................................................................................768
Form.method ..................................................................................769
Form.name......................................................................................770
Form.onReset..................................................................................771
Form.onSubmit ..............................................................................772
Form.reset() ....................................................................................773
Form.submit() ................................................................................774
Form.target......................................................................................775
Form.unwatch() ..............................................................................776
Form.watch() ..................................................................................777
Frame ..............................................................................................778
Frame.blur() ..................................................................................779
Frame.clearInterval() ......................................................................780
Frame.clearTimeout() ....................................................................781
Frame.document ............................................................................781
Frame.focus()..................................................................................782
Frame.frames ..................................................................................782
Frame.length ..................................................................................783
Frame.name ....................................................................................784
Frame.onBlur..................................................................................784
00 0672321419 FM 7/24/01 11:46 AM Page xxi
xxi
Frame.onFocus ..............................................................................785
Frame.onMove................................................................................786
Frame.onResize ..............................................................................786
Frame.parent ..................................................................................787
Frame.print() ..................................................................................787
Frame.self ......................................................................................788
Frame.setInterval()..........................................................................788
Frame.setTimeout() ........................................................................789
Frame.top........................................................................................790
Frame.unwatch() ............................................................................790
Frame.watch() ................................................................................791
Frame.window ................................................................................792
Hidden ............................................................................................793
Hidden.form....................................................................................794
Hidden.name ..................................................................................795
Hidden.type ....................................................................................795
Hidden.unwatch() ..........................................................................796
Hidden.value ..................................................................................797
Hidden.watch() ..............................................................................798
History ............................................................................................799
History.back() ................................................................................800
History.current ................................................................................800
History.forward() ............................................................................801
History.go() ....................................................................................802
History.length ................................................................................802
History.next ....................................................................................803
History.previous..............................................................................804
History.unwatch() ..........................................................................805
History.watch() ..............................................................................806
Image ..............................................................................................807
Image.border ..................................................................................809
Image.complete ..............................................................................810
Image.handleEvent() ......................................................................811
Image.height ..................................................................................811
Image.hspace ..................................................................................812
Image.lowsrc ..................................................................................813
Image.name ....................................................................................814
Image.onAbort................................................................................814
Image.onError ................................................................................815
Image.onKeyDown ........................................................................815
Image.onKeyPress ..........................................................................816
Image.onKeyUp..............................................................................816
Image.onLoad ................................................................................816
Image.src ........................................................................................817
Image.unwatch() ............................................................................818
00 0672321419 FM 7/24/01 11:46 AM Page xxii
xxii
Image.vspace ..................................................................................819
Image.watch() ................................................................................819
Image.width ....................................................................................820
Layer ..............................................................................................821
Layer.above ....................................................................................823
Layer.background ..........................................................................824
Layer.below ....................................................................................825
Layer.bgColor ................................................................................826
Layer.captureEvents() ....................................................................827
Layer.clip.bottom............................................................................828
Layer.clip.height ............................................................................829
Layer.clip.left..................................................................................830
Layer.clip.right................................................................................831
Layer.clip.top ..................................................................................832
Layer.clip.width ..............................................................................833
Layer.document ..............................................................................834
Layer.handleEvent() ......................................................................835
Layer.left ........................................................................................837
Layer.load() ....................................................................................838
Layer.moveAbove() ........................................................................838
Layer.moveBelow() ........................................................................839
Layer.moveBy() ..............................................................................840
Layer.moveTo() ..............................................................................841
Layer.moveToAbsolute() ................................................................842
Layer.name ....................................................................................843
Layer.onBlur ..................................................................................844
Layer.onFocus ................................................................................845
Layer.onLoad..................................................................................846
Layer.onMouseOut ........................................................................847
Layer.onMouseOver ......................................................................848
Layer.pageX....................................................................................849
Layer.pageY....................................................................................850
Layer.parentLayer ..........................................................................851
Layer.releaseEvents() ....................................................................852
Layer.resizeBy() ............................................................................853
Layer.resizeTo() ..............................................................................854
Layer.routeEvent() ..........................................................................855
Layer.siblingAbove ........................................................................856
Layer.siblingBelow ........................................................................857
Layer.src ........................................................................................858
Layer.top ........................................................................................859
Layer.unwatch()..............................................................................860
Layer.visibility................................................................................861
Layer.watch()..................................................................................862
Layer.zIndex ..................................................................................864
00 0672321419 FM 7/24/01 11:46 AM Page xxiii
xxiii
Link ................................................................................................864
Link.handleEvent() ........................................................................866
Link.hash ........................................................................................867
Link.host ........................................................................................868
Link.hostname ................................................................................869
Link.href ........................................................................................870
Link.onClick ..................................................................................871
Link.onDblClick ............................................................................871
Link.onKeyDown ..........................................................................872
Link.onKeyPress ............................................................................873
Link.onKeyUp ................................................................................874
Link.onMouseDown ......................................................................874
Link.onMouseOut ..........................................................................875
Link.onMouseOver ........................................................................876
Link.onMouseUp............................................................................877
Link.pathname ................................................................................877
Link.port ........................................................................................878
Link.protocol ..................................................................................879
Link.search ....................................................................................880
Link.target ......................................................................................881
Link.text..........................................................................................882
Link.unwatch() ..............................................................................883
Link.watch() ..................................................................................884
Location ..........................................................................................885
Location.hash..................................................................................886
Location.host ..................................................................................887
Location.hostname..........................................................................889
Location.href ..................................................................................890
Location.pathname ........................................................................891
Location.port ..................................................................................892
Location.protocol............................................................................893
Location.reload() ............................................................................894
Location.replace() ..........................................................................895
Location.search ..............................................................................895
Location.unwatch() ........................................................................896
Location.watch() ............................................................................898
MimeType ......................................................................................899
MimeType.description ....................................................................900
MimeType.enabledPlugin ..............................................................901
MimeType.suffixes ........................................................................901
MimeType.type ..............................................................................902
MimeType.unwatch()......................................................................903
MimeType.watch()..........................................................................903
navigator ........................................................................................904
navigator.appCodeName ................................................................905
00 0672321419 FM 7/24/01 11:46 AM Page xxiv
xxiv
navigator.appName ........................................................................906
navigator.appVersion ......................................................................906
navigator.javaEnabled() ..................................................................907
navigator.language ..........................................................................908
navigator.mimeTypes......................................................................908
navigator.platform ..........................................................................909
navigator.plugins ............................................................................910
navigator.plugins.refresh()..............................................................911
navigator.preference() ....................................................................911
navigator.taintEnabled()..................................................................912
navigator.userAgent ........................................................................913
navigator.unwatch() ........................................................................914
navigator.watch() ............................................................................914
Option ............................................................................................914
Option.defaultSelected ..................................................................916
Option.selected ..............................................................................917
Option.text ......................................................................................918
Option.unwatch()............................................................................919
Option.value ..................................................................................920
Option.watch()................................................................................921
Password ........................................................................................922
Password.blur() ..............................................................................923
Password.defaultValue....................................................................924
Password.focus() ............................................................................925
Password.form ................................................................................925
Password.handleEvent() ................................................................926
Password.name ..............................................................................927
Password.onBlur ............................................................................928
Password.onFocus ..........................................................................929
Password.select() ............................................................................930
Password.type ................................................................................930
Password.unwatch()........................................................................931
Password.value ..............................................................................932
Password.watch()............................................................................933
Plugin..............................................................................................934
Plugin.description ..........................................................................935
Plugin.filename ..............................................................................935
Plugin.length ..................................................................................936
Plugin.name ....................................................................................937
Plugin.unwatch() ............................................................................937
Plugin.watch() ................................................................................938
Radio ..............................................................................................938
Radio.blur() ....................................................................................939
Radio.checked ................................................................................940
Radio.click() ..................................................................................941
00 0672321419 FM 7/24/01 11:46 AM Page xxv
xxv
Radio.defaultChecked ....................................................................942
Radio.focus() ..................................................................................943
Radio.form......................................................................................944
Radio.handleEvent() ......................................................................944
Radio.name ....................................................................................946
Radio.onBlur ..................................................................................946
Radio.onClick ................................................................................947
Radio.onFocus() ............................................................................948
Radio.type ......................................................................................949
Radio.unwatch() ............................................................................949
Radio.value ....................................................................................950
Radio.watch() ................................................................................951
Reset ..............................................................................................952
Reset.blur() ....................................................................................953
Reset.click()....................................................................................954
Reset.focus() ..................................................................................955
Reset.form ......................................................................................956
Reset.handleEvent()........................................................................957
Reset.name......................................................................................958
Reset.onBlur ..................................................................................959
Reset.onClick..................................................................................960
Reset.onFocus ................................................................................961
Reset.type ......................................................................................962
Reset.unwatch() ..............................................................................962
Reset.value......................................................................................964
Reset.watch() ..................................................................................965
screen ..............................................................................................967
screen.availHeight ..........................................................................968
screen.availLeft ..............................................................................969
screen.availTop ..............................................................................969
screen.availWidth............................................................................970
screen.colorDepth ..........................................................................971
screen.height ..................................................................................971
Screen.pixelDepth ..........................................................................972
screen.unwatch() ............................................................................972
screen.watch() ................................................................................973
screen.width....................................................................................974
Select ..............................................................................................974
Select.blur() ....................................................................................976
Select.focus() ..................................................................................978
Select.form......................................................................................979
Select.handleEvent() ......................................................................980
Select.length ..................................................................................982
Select.name ....................................................................................983
Select.onBlur ..................................................................................984
00 0672321419 FM 7/24/01 11:46 AM Page xxvi
xxvi
Select.onChange ............................................................................985
Select.onFocus................................................................................986
Select.options..................................................................................987
Select.options.length ......................................................................989
Select.options.selectedIndex ..........................................................989
Select.options.value ........................................................................990
Select.selectedIndex ......................................................................991
Select.type ......................................................................................991
Select.unwatch() ............................................................................992
Select.watch() ................................................................................993
Style ................................................................................................994
Style.align ......................................................................................997
Style.backgroundColor ..................................................................998
Style.backgroundImage ..................................................................999
Style.borderBottomWidth ............................................................1000
Style.borderColor ........................................................................1001
Style.borderLeftWidth ..................................................................1001
Style.borderRightWidth................................................................1002
Style.borderStyle ..........................................................................1003
Style.borderTopWidth ..................................................................1004
Style.borderWidths() ....................................................................1004
Style.clear ....................................................................................1006
Style.color ....................................................................................1007
Style.display ................................................................................1007
Style.fontFamily ..........................................................................1008
Style.fontSize................................................................................1009
Style.fontStyle ..............................................................................1010
Style.fontWeight ..........................................................................1011
Style.lineHeight ............................................................................1012
Style.listStyleType ........................................................................1013
Style.marginBottom......................................................................1014
Style.marginLeft ..........................................................................1015
Style.marginRight ........................................................................1016
Style.margins() ............................................................................1016
Style.marginTop............................................................................1018
Style.paddingBottom ....................................................................1018
Style.paddingLeft ........................................................................1019
Style.paddingRight ......................................................................1020
Style.paddings()............................................................................1021
Style.paddingTop ..........................................................................1022
Style.textAlign..............................................................................1023
Style.textDecoration ....................................................................1024
Style.textIndent ............................................................................1024
Style.textTransform ......................................................................1025
Style.unwatch() ............................................................................1026
00 0672321419 FM 7/24/01 11:46 AM Page xxvii
xxvii
Style.watch() ................................................................................1027
Style.whiteSpace ..........................................................................1028
Style.width....................................................................................1028
Submit ..........................................................................................1029
Submit.blur() ................................................................................1031
Submit.click() ..............................................................................1032
Submit.focus() ..............................................................................1034
Submit.form..................................................................................1034
Submit.handleEvent() ..................................................................1036
Submit.name ................................................................................1037
Submit.onBlur ..............................................................................1038
Submit.onClick ............................................................................1039
Submit.onFocus ............................................................................1040
Submit.type ..................................................................................1041
Submit.unwatch() ........................................................................1042
Submit.value ................................................................................1043
Submit.watch() ............................................................................1044
taint() ............................................................................................1045
Text ..............................................................................................1046
Text.blur() ....................................................................................1048
Text.defaultValue ..........................................................................1049
Text.focus() ..................................................................................1050
Text.form ......................................................................................1051
Text.handleEvent()........................................................................1052
Text.name......................................................................................1053
Text.onBlur ..................................................................................1054
Text.onChange ..............................................................................1055
Text.onFocus ................................................................................1056
Text.onSelect ................................................................................1057
Text.select() ..................................................................................1058
Text.type ......................................................................................1059
Text.unwatch() ..............................................................................1060
Text.value......................................................................................1061
Text.watch() ..................................................................................1062
Textarea ........................................................................................1063
Textarea.blur() ..............................................................................1065
Textarea.defaultValue ..................................................................1066
Textarea.focus() ............................................................................1067
Textarea.form................................................................................1068
Textarea.handleEvent() ................................................................1070
Textarea.name ..............................................................................1071
Textarea.onBlur ............................................................................1072
Textarea.onChange ......................................................................1073
Textarea.onFocus ..........................................................................1074
Textarea.onKeyDown ..................................................................1075
00 0672321419 FM 7/24/01 11:46 AM Page xxviii
xxviii
Textarea.onKeyPress ....................................................................1076
Textarea.onKeyUp ........................................................................1077
Textarea.onSelect..........................................................................1078
Textarea.select()............................................................................1079
Textarea.type ................................................................................1080
Textarea.unwatch() ......................................................................1081
Textarea.value ..............................................................................1082
Textarea.watch() ..........................................................................1083
untaint() ........................................................................................1084
Window ........................................................................................1085
window.alert() ..............................................................................1090
window.atob() ..............................................................................1091
window.back() ..............................................................................1092
window.blur()................................................................................1092
window.btoa() ..............................................................................1094
window.captureEvents() ..............................................................1094
window.clearInterval()..................................................................1096
window.clearTimeout() ................................................................1098
window.close()..............................................................................1099
window.closed ..............................................................................1100
window.confirm() ........................................................................1102
window.crypto ..............................................................................1103
window.crypto.random() ..............................................................1104
window.crypto.signText() ............................................................1104
window.defaultStatus....................................................................1105
window.disableExternalCapture() ................................................1106
window.document ........................................................................1107
window.enableExternalCapture() ................................................1110
window.find()................................................................................1111
window.focus() ............................................................................1112
window.forward() ........................................................................1113
window.frames..............................................................................1114
window.frames.length ..................................................................1115
window.handleEvent() ..................................................................1115
window.history..............................................................................1116
window.home() ............................................................................1118
window.innerHeight......................................................................1118
window.innerWidth ......................................................................1120
window.length ..............................................................................1121
window.location............................................................................1122
window.locationbar ......................................................................1122
window.locationbar.visible ..........................................................1123
window.menubar ..........................................................................1123
window.menubar.visible ..............................................................1124
window.moveBy() ........................................................................1125
00 0672321419 FM 7/24/01 11:46 AM Page xxix
xxix
window.moveTo() ........................................................................1126
window.name ................................................................................1127
window.offscreenBuffering ..........................................................1129
window.onBlur..............................................................................1129
window.onDragDrop ....................................................................1130
window.onError ............................................................................1130
window.onFocus ..........................................................................1131
window.onLoad ............................................................................1132
window.onMove ..........................................................................1132
window.onResize ..........................................................................1133
window.onUnload ........................................................................1133
window.open() ..............................................................................1134
window.opener..............................................................................1137
window.outerHeight......................................................................1139
window.outerWidth ......................................................................1140
window.pageXOffset ....................................................................1142
window.pageYOffset ....................................................................1143
window.parent ..............................................................................1144
window.personalbar ......................................................................1144
window.personalbar.visible ..........................................................1145
window.print() ..............................................................................1146
window.prompt() ..........................................................................1147
window.releaseEvents() ................................................................1148
window.resizeBy() ........................................................................1150
window.resizeTo() ........................................................................1151
window.routeEvent() ....................................................................1152
window.screenX............................................................................1154
window.screenY............................................................................1155
window.scroll() ............................................................................1156
window.scrollbars ........................................................................1157
window.scrollbars.visible ............................................................1158
window.scrollBy() ........................................................................1158
window.scrollTo() ........................................................................1160
window.self ..................................................................................1161
window.setHotKeys() ..................................................................1162
window.setInterval() ....................................................................1162
window.setResizable() ..................................................................1164
window.setTimeout() ....................................................................1164
window.setZOptions() ..................................................................1165
window.status................................................................................1166
window.statusbar ..........................................................................1167
window.statusbar.visible ..............................................................1167
window.stop() ..............................................................................1168
window.toolbar ............................................................................1169
window.toolbar.visible..................................................................1169
00 0672321419 FM 7/24/01 11:46 AM Page xxx
xxx
window.top....................................................................................1170
window.unwatch() ........................................................................1171
window.watch() ............................................................................1172
window.window............................................................................1173
9 SERVER-SIDE 1175
addClient() ....................................................................................1176
addResponseHeader() ..................................................................1176
Application ..................................................................................1177
Application.Application_OnEnd ..................................................1178
Application.Application_OnStart ................................................1179
Application.Contents ....................................................................1179
Application.Contents.Remove() ..................................................1180
Application.Contents.RemoveAll() ..............................................1180
Application.Lock() ......................................................................1181
Application.StaticObjects ............................................................1182
Application.Unlock()....................................................................1182
ASPError ......................................................................................1183
ASPError.ASPCode......................................................................1184
ASPError.ASPDescription............................................................1184
ASPError.Category ......................................................................1185
ASPError.Column ........................................................................1185
ASPError.Description ..................................................................1185
ASPError.File ..............................................................................1186
ASPError.Line ..............................................................................1186
ASPError.Number ........................................................................1187
ASPError.Source ..........................................................................1187
blob() (Function) ..........................................................................1188
blob (Object) ................................................................................1189
blob.blobImage() ..........................................................................1190
blob.blobLink() ............................................................................1191
callC() ..........................................................................................1192
client ............................................................................................1193
client.destroy()..............................................................................1195
client.expiration() ........................................................................1196
client.property ..............................................................................1196
client.unwatch() ............................................................................1197
client.watch() ................................................................................1198
Connection....................................................................................1199
Connection.beginTransaction() ....................................................1201
Connection.commitTransaction() ................................................1202
Connection.connected()................................................................1203
Connection.cursor() ......................................................................1204
Connection.execute() ....................................................................1205
Connection.majorErrorCode()......................................................1205
00 0672321419 FM 7/24/01 11:46 AM Page xxxi
xxxi
Connection.majorErrorMessage() ................................................1206
Connection.minorErrorCode()......................................................1207
Connection.minorErrorMessage() ................................................1208
Connection.prototype ..................................................................1209
Connection.release() ....................................................................1210
Connection.rollbackTransaction() ................................................1211
Connection.SQLTable() ................................................................1212
Connection.storedProc() ..............................................................1213
Connection.toString() ..................................................................1215
Connection.unwatch() ..................................................................1216
Connection.watch() ......................................................................1218
Cursor ..........................................................................................1219
Cursor.close()................................................................................1221
Cursor.columnName ....................................................................1222
Cursor.columnName() ..................................................................1222
Cursor.columns() ..........................................................................1224
Cursor.deleteRow() ......................................................................1225
Cursor.insertRow() ......................................................................1226
Cursor.next() ................................................................................1227
Cursor.prototype ..........................................................................1228
Cursor.unwatch() ..........................................................................1229
Cursor.updateRow()......................................................................1231
Cursor.watch() ..............................................................................1232
database ........................................................................................1233
database.beginTransaction() ........................................................1235
database.commitTransaction()......................................................1236
database.connect() ........................................................................1237
database.connected() ....................................................................1239
database.cursor() ..........................................................................1240
database.disconnect()....................................................................1241
database.execute() ........................................................................1242
database.majorErrorCode() ..........................................................1242
database.majorErrorMessage() ....................................................1243
database.minorErrorCode() ..........................................................1244
database.minorErrorMessage() ....................................................1245
database.prototype ........................................................................1246
database.rollbackTransaction() ....................................................1247
database.SQLTable() ....................................................................1248
database.storedProc()....................................................................1249
database.storedProcArgs() ............................................................1250
database.toString()........................................................................1251
database.unwatch() ......................................................................1253
database.watch() ..........................................................................1254
DbPool ..........................................................................................1255
DbPool.connect()..........................................................................1258
00 0672321419 FM 7/24/01 11:46 AM Page xxxii
xxxii
DbPool.connected() ......................................................................1260
DbPool.connection() ....................................................................1261
DbPool.DbPool() ..........................................................................1262
DbPool.disconnect() ....................................................................1263
DbPool.majorErrorCode() ............................................................1264
DbPool.majorErrorMessage() ......................................................1264
DbPool.minorErrorCode()............................................................1265
DbPool.minorErrorMessage() ......................................................1266
DbPool.prototype..........................................................................1267
DbPool.storedProcArgs() ............................................................1268
DbPool.toString() ........................................................................1269
DBPool.unwatch() ........................................................................1270
DBPool.watch() ............................................................................1272
debug()..........................................................................................1273
deleteResponseHeader() ..............................................................1274
File() ............................................................................................1274
File.byteToString() ......................................................................1277
File.clearError() ............................................................................1278
File.close() ....................................................................................1279
File.constructor ............................................................................1279
File.eof() ......................................................................................1280
File.error() ....................................................................................1281
File.exists() ..................................................................................1282
File.flush() ....................................................................................1283
File.getLength() ............................................................................1284
File.getPosition() ..........................................................................1284
File.open() ....................................................................................1285
File.prototype................................................................................1286
File.read() ....................................................................................1288
File.readByte()..............................................................................1288
File.readln() ..................................................................................1289
File.setPosition() ..........................................................................1290
File.stringToByte() ......................................................................1291
File.unwatch() ..............................................................................1292
File.watch() ..................................................................................1294
File.write() ....................................................................................1295
File.writeByte() ............................................................................1296
File.writeln() ................................................................................1297
flush()............................................................................................1298
getOptionValue() ..........................................................................1299
getOptionValueCount() ................................................................1300
Lock() ..........................................................................................1300
Lock.constructor ..........................................................................1301
Lock.isValid() ..............................................................................1302
Lock.lock() ..................................................................................1303
00 0672321419 FM 7/24/01 11:46 AM Page xxxiii
xxxiii
Lock.prototype..............................................................................1303
Lock.unlock() ..............................................................................1305
Lock.unwatch() ............................................................................1305
Lock.watch() ................................................................................1307
ObjectContext ..............................................................................1308
ObjectContext.OnTransactionAbort ............................................1309
ObjectContext.OnTransactionCommit ........................................1310
ObjectContext.SetAbort() ............................................................1310
ObjectContext.SetComplete() ......................................................1311
project ..........................................................................................1312
project.lock() ................................................................................1313
project.unlock() ............................................................................1313
project.unwatch()..........................................................................1314
project.watch()..............................................................................1315
redirect() ......................................................................................1316
registerCFunction() ......................................................................1317
Request ........................................................................................1318
Request.BinaryRead() ..................................................................1318
Request.ClientCertificate..............................................................1319
Request.Cookies ..........................................................................1321
Request.Form................................................................................1321
Request.Form.Form.Count ..........................................................1322
Request.QueryString ....................................................................1323
Request.QueryString.Count..........................................................1323
Request.ServerVariables ..............................................................1324
Request.TotalBytes ......................................................................1326
request ..........................................................................................1327
request.agent ................................................................................1328
request.formKey ..........................................................................1328
request.imageX ............................................................................1329
request.imageY ............................................................................1330
request.ip ......................................................................................1331
request.method..............................................................................1331
request.protocol ............................................................................1332
request.unwatch() ........................................................................1333
request.watch() ............................................................................1334
Response ......................................................................................1334
Response.AddHeader() ................................................................1335
Response.AppendToLog() ............................................................1336
Response.BinaryWrite() ..............................................................1336
Response.Buffer ..........................................................................1337
Response.CacheControl................................................................1337
Response.Charset..........................................................................1338
Response.Clear() ..........................................................................1338
Response.ContentType ................................................................1339
00 0672321419 FM 7/24/01 11:46 AM Page xxxiv
xxxiv
Response.Cookies ........................................................................1339
Response.End() ............................................................................1340
Response.Expires..........................................................................1340
Response.ExpiresAbsolute ..........................................................1341
Response.Flush() ..........................................................................1341
Response.IsClientConnected ........................................................1342
Response.PICS ............................................................................1342
Response.Redirect()......................................................................1343
Response.Status ............................................................................1343
Response.Write() ..........................................................................1344
Resultset........................................................................................1344
Resultset.close()............................................................................1346
Resultset.columnName() ..............................................................1347
Resultset.columns() ......................................................................1348
Resultset.next() ............................................................................1349
Resultset.prototype ......................................................................1350
Resultset.unwatch() ......................................................................1351
Resultset.watch() ..........................................................................1353
ScriptingContext ..........................................................................1354
SendMail ......................................................................................1354
SendMail.Bcc ..............................................................................1357
SendMail.Body ............................................................................1357
SendMail.Cc ................................................................................1358
SendMail.constructor....................................................................1358
SendMail.errorCode() ..................................................................1359
SendMail.errorMessage() ............................................................1360
SendMail.Errorsto ........................................................................1361
SendMail.From ............................................................................1361
SendMail.Organization ................................................................1362
SendMail.prototype ......................................................................1362
SendMail.Replyto ........................................................................1363
SendMail.send()............................................................................1364
SendMail.Smtpserver ..................................................................1365
SendMail.Subject..........................................................................1365
SendMail.To ................................................................................1366
SendMail.unwatch() ....................................................................1366
SendMail.watch() ........................................................................1367
Server............................................................................................1368
Server.CreateObject() ..................................................................1369
Server.Execute()............................................................................1369
Server.GetLastError() ..................................................................1370
Server.HTMLEncode() ................................................................1370
Server.MapPath() ..........................................................................1371
Server.ScriptTimeout ....................................................................1371
Server.Transfer() ..........................................................................1372
00 0672321419 FM 7/24/01 11:46 AM Page xxxv
xxxv
Server.URLEncode() ....................................................................1372
server ............................................................................................1373
server.host ....................................................................................1374
server.hostname ............................................................................1374
server.lock() ..................................................................................1375
server.port ....................................................................................1375
server.protocol ..............................................................................1376
server.unlock() ..............................................................................1376
server.unwatch()............................................................................1377
server.watch()................................................................................1378
Session ..........................................................................................1378
Session.Abandon()........................................................................1379
Session.CodePage ........................................................................1380
Session.Contents ..........................................................................1381
Session.Contents.Remove()..........................................................1381
Session.Contents.RemoveAll() ....................................................1382
Session.LCID................................................................................1383
Session.SessionID ........................................................................1383
Session.Session_OnEnd ..............................................................1384
Session.Session_OnStart ..............................................................1384
Session.StaticObjects....................................................................1385
Session.Timeout............................................................................1385
ssjs_generateClientID() ................................................................1385
ssjs_getCGIVariable() ..................................................................1386
ssjs_getClientID() ........................................................................1387
Stproc............................................................................................1388
Stproc.close()................................................................................1389
Stproc.outParamCount() ..............................................................1390
Stproc.outParameters() ................................................................1391
Stproc.prototype ..........................................................................1392
Stproc.resultSet() ..........................................................................1393
Stproc.returnValue() ....................................................................1395
Stproc.unwatch() ..........................................................................1395
Stproc.watch() ..............................................................................1397
write() ..........................................................................................1398
INDEX CD:2025
xxxvi
CDATASection ......................................................................CD:1406
CharacterData ........................................................................CD:1407
CharacterData.data ................................................................CD:1408
CharacterData.length ............................................................CD:1408
CharacterData.substringData() ..............................................CD:1409
CharacterData.appendData()..................................................CD:1409
CharacterData.insertData() ....................................................CD:1410
CharacterData.deleteData()....................................................CD:1411
CharacterData.replaceData()..................................................CD:1411
Comment................................................................................CD:1412
Document ..............................................................................CD:1412
Document.createAttribute() ..................................................CD:1414
Document.createAttributeNS() ..............................................CD:1414
Document.createCDATASection() ........................................CD:1415
Document.createComment()..................................................CD:1416
Document.createDocumentFragment()..................................CD:1416
Document.createElement() ....................................................CD:1417
Document.createElementNS() ..............................................CD:1417
Document.createEntityReference()........................................CD:1418
Document.createProcessingInstruction() ..............................CD:1419
Document.createTextNode() ..................................................CD:1419
Document.doctype ................................................................CD:1420
Document.documentElement ................................................CD:1421
Document.getElementById() ................................................CD:1421
Document.getElementsByTagName() ..................................CD:1422
Document.getElementsByTagNameNS() ..............................CD:1422
Document.implementation ....................................................CD:1423
Document.importNode()........................................................CD:1424
DocumentFragment................................................................CD:1424
DocumentType ......................................................................CD:1425
DocumentType.entities ..........................................................CD:1426
DocumentType.internalSubset ..............................................CD:1426
DocumentType.name ............................................................CD:1427
DocumentType.notations ......................................................CD:1427
DocumentType.publicId ........................................................CD:1428
DocumentType.systemId ......................................................CD:1429
DOMException ......................................................................CD:1429
DOMException.code ............................................................CD:1430
DOMImplementation ............................................................CD:1431
DOMImplementation.createDocument() ..............................CD:1432
DOMImplementation.createDocumentType() ......................CD:1433
DOMImplementation.hasFeature()........................................CD:1433
Element ..................................................................................CD:1434
Element.getAttribute() ..........................................................CD:1435
Element.getAttributeNode() ..................................................CD:1436
00 0672321419 FM 7/24/01 11:46 AM Page xxxvii
xxxvii
Element.getAttributeNodeNS() ............................................CD:1436
Element.getAttributeNS() ......................................................CD:1437
Element.getElementsByTagName() ......................................CD:1438
Element.getElementsByTagNameNS()..................................CD:1438
Element.hasAttribute() ..........................................................CD:1439
Element.hasAttributeNS()......................................................CD:1439
Element.removeAttribute() ....................................................CD:1440
Element.removeAttributeNode()............................................CD:1440
Element.removeAttributeNS() ..............................................CD:1441
Element.setAttribute()............................................................CD:1442
Element.setAttributeNode() ..................................................CD:1442
Element.setAttributeNodeNS() ..............................................CD:1443
Element.setAttributeNS() ......................................................CD:1444
Element.tagName ..................................................................CD:1444
Entity......................................................................................CD:1445
Entity.notationName ..............................................................CD:1445
Entity.publicId........................................................................CD:1446
Entity.systemId ......................................................................CD:1446
EntityReference......................................................................CD:1447
NamedNodeMap ....................................................................CD:1447
NamedNodeMap.getNamedItem() ........................................CD:1448
NamedNodeMap.getNamedItemNS() ..................................CD:1449
NamedNodeMap.item() ........................................................CD:1449
NamedNodeMap.length ........................................................CD:1450
NamedNodeMap.removeNamedItem()..................................CD:1451
NamedNodeMap.removeNamedItemNS() ............................CD:1451
NamedNodeMap.setNamedItem() ........................................CD:1452
NamedNodeMap.setNamedItemNS()....................................CD:1453
Node ......................................................................................CD:1453
Node.attributes ......................................................................CD:1456
Node.appendChild() ..............................................................CD:1457
Node.childNodes....................................................................CD:1457
Node.cloneNode()..................................................................CD:1458
Node.firstChild ......................................................................CD:1458
Node.hasAttributes() ..............................................................CD:1459
Node.hasChildNodes() ..........................................................CD:1460
Node.insertBefore() ..............................................................CD:1460
Node.isSupported() ................................................................CD:1461
Node.lastChild ......................................................................CD:1462
Node.localName ....................................................................CD:1462
Node.namespaceURI ............................................................CD:1463
Node.nextSibling ..................................................................CD:1463
Node.nodeName ....................................................................CD:1464
Node.nodeType ......................................................................CD:1465
Node.nodeValue ....................................................................CD:1465
00 0672321419 FM 7/24/01 11:46 AM Page xxxviii
xxxviii
Node.normalize() ..................................................................CD:1466
Node.ownerDocument ..........................................................CD:1466
Node.parentNode ..................................................................CD:1467
Node.prefix ............................................................................CD:1468
Node.previousSibling ............................................................CD:1468
Node.removeChild() ..............................................................CD:1469
Node.replaceChild() ..............................................................CD:1469
Notation..................................................................................CD:1470
Notation.publicId ..................................................................CD:1471
Notation.systemId ..................................................................CD:1471
ProcessingInstruction ............................................................CD:1472
ProcessingInstruction.data ....................................................CD:1472
ProcessingInstruction.target ..................................................CD:1473
Text ........................................................................................CD:1474
Text.splitText() ......................................................................CD:1474
xxxix
HTMLAreaElement.accessKey ............................................CD:1498
HTMLAreaElement.alt ..........................................................CD:1498
HTMLAreaElement.coords ..................................................CD:1499
HTMLAreaElement.href........................................................CD:1500
HTMLAreaElement.noHref ..................................................CD:1500
HTMLAreaElement.shape ....................................................CD:1501
HTMLAreaElement.tabIndex ................................................CD:1501
HTMLAreaElement.target ....................................................CD:1502
HTMLBaseElement ..............................................................CD:1503
HTMLBaseElement.href........................................................CD:1503
HTMLBaseElement.target ....................................................CD:1504
HTMLBaseFontElement........................................................CD:1505
HTMLBaseFontElement.color ..............................................CD:1505
HTMLBaseFontElement.face ................................................CD:1506
HTMLBaseFontElement.size ................................................CD:1507
HTMLBodyElement ..............................................................CD:1507
HTMLBodyElement.aLink....................................................CD:1508
HTMLBodyElement.background ..........................................CD:1509
HTMLBodyElement.bgColor ................................................CD:1509
HTMLBodyElement.link ......................................................CD:1510
HTMLBodyElement.text ......................................................CD:1511
HTMLBodyElement.vLink....................................................CD:1511
HTMLBRElement..................................................................CD:1512
HTMLBRElement.clear ........................................................CD:1512
HTMLButtonElement ............................................................CD:1513
HTMLButtonElement.accessKey ..........................................CD:1514
HTMLButtonElement.disabled..............................................CD:1514
HTMLButtonElement.form ..................................................CD:1515
HTMLButtonElement.name ..................................................CD:1516
HTMLButtonElement.tabIndex ............................................CD:1516
HTMLButtonElement.type ....................................................CD:1517
HTMLButtonElement.value ..................................................CD:1517
HTMLCollection....................................................................CD:1518
HTMLCollection.item() ........................................................CD:1519
HTMLCollection.length ........................................................CD:1520
HTMLCollection.namedItem()..............................................CD:1520
HTMLDirectoryElement........................................................CD:1521
HTMLDirectoryElement.compact ........................................CD:1522
HTMLDivElement ................................................................CD:1522
HTMLDivElement.align ........................................................CD:1523
HTMLDListElement..............................................................CD:1524
HTMLDListElement.compact ..............................................CD:1524
HTMLDocument....................................................................CD:1525
HTMLDocument.anchors ......................................................CD:1526
HTMLDocument.applets ......................................................CD:1527
00 0672321419 FM 7/24/01 11:46 AM Page xl
xl
HTMLDocument.body ..........................................................CD:1528
HTMLDocument.close()........................................................CD:1528
HTMLDocument.cookie........................................................CD:1529
HTMLDocument.domain ......................................................CD:1530
HTMLDocument.forms ........................................................CD:1530
HTMLDocument.getElementsByName()..............................CD:1531
HTMLDocument.images ......................................................CD:1532
HTMLDocument.links ..........................................................CD:1533
HTMLDocument.open() ........................................................CD:1533
HTMLDocument.referrer ......................................................CD:1534
HTMLDocument.title ............................................................CD:1535
HTMLDocument.URL ..........................................................CD:1535
HTMLDocument.write()........................................................CD:1536
HTMLDocument.writeln() ....................................................CD:1537
HTMLDOMImplementation..................................................CD:1537
HTMLDOMImplementation.createHTMLDocument() ........CD:1538
HTMLElement ......................................................................CD:1539
HTMLElement.className ....................................................CD:1540
HTMLElement.dir ................................................................CD:1540
HTMLElement.id ..................................................................CD:1541
HTMLElement.lang ..............................................................CD:1541
HTMLElement.title................................................................CD:1542
HTMLFieldSetElement..........................................................CD:1543
HTMLFieldSetElement.form ................................................CD:1543
HTMLFontElement................................................................CD:1544
HTMLFontElement.color ......................................................CD:1545
HTMLFontElement.face ........................................................CD:1545
HTMLFontElement.size ........................................................CD:1546
HTMLFormElement ..............................................................CD:1546
HTMLFormElement.acceptCharset ......................................CD:1547
HTMLFormElement.action ..................................................CD:1548
HTMLFormElement.elements ..............................................CD:1549
HTMLFormElement.enctype ................................................CD:1549
HTMLFormElement.length ..................................................CD:1550
HTMLFormElement.method ................................................CD:1551
HTMLFormElement.name ....................................................CD:1551
HTMLFormElement.reset() ..................................................CD:1552
HTMLFormElement.submit()................................................CD:1553
HTMLFormElement.target ....................................................CD:1553
HTMLFrameElement ............................................................CD:1554
HTMLFrameElement.contentDocument ..............................CD:1555
HTMLFrameElement.frameBorder ......................................CD:1555
HTMLFrameElement.longDesc ............................................CD:1556
HTMLFrameElement.marginHeight ....................................CD:1557
HTMLFrameElement.marginWidth ......................................CD:1557
00 0672321419 FM 7/24/01 11:46 AM Page xli
xli
HTMLFrameElement.name ..................................................CD:1558
HTMLFrameElement.noResize ............................................CD:1558
HTMLFrameElement.scrolling..............................................CD:1559
HTMLFrameElement.src ......................................................CD:1560
HTMLFrameSetElement........................................................CD:1560
HTMLFrameSetElement.cols ................................................CD:1561
HTMLFrameSetElement.rows ..............................................CD:1562
HTMLHeadElement ..............................................................CD:1562
HTMLHeadElement.profile ..................................................CD:1563
HTMLHeadingElement ........................................................CD:1564
HTMLHeadingElement.align ................................................CD:1564
HTMLHRElement ................................................................CD:1565
HTMLHRElement.align ........................................................CD:1566
HTMLHRElement.noShade ..................................................CD:1566
HTMLHRElement.size ..........................................................CD:1567
HTMLHRElement.width ......................................................CD:1567
HTMLHtmlElement ..............................................................CD:1568
HTMLHtmlElement.version ..................................................CD:1569
HTMLIFrameElement ..........................................................CD:1569
HTMLIFrameElement.align ..................................................CD:1570
HTMLIFrameElement.contentDocument..............................CD:1571
HTMLIFrameElement.frameBorder......................................CD:1571
HTMLIFrameElement.height ................................................CD:1572
HTMLIFrameElement.longDesc ..........................................CD:1573
HTMLIFrameElement.marginHeight ....................................CD:1573
HTMLIFrameElement.marginWidth ....................................CD:1574
HTMLIFrameElement.name..................................................CD:1574
HTMLIFrameElement.scrolling ............................................CD:1575
HTMLIFrameElement.src......................................................CD:1576
HTMLIFrameElement.width ................................................CD:1576
HTMLImageElement ............................................................CD:1577
HTMLImageElement.align....................................................CD:1578
HTMLImageElement.alt........................................................CD:1578
HTMLImageElement.border ................................................CD:1579
HTMLImageElement.height..................................................CD:1580
HTMLImageElement.hspace ................................................CD:1580
HTMLImageElement.isMap..................................................CD:1581
HTMLImageElement.longDesc ............................................CD:1581
HTMLImageElement.lowSrc ................................................CD:1582
HTMLImageElement.src ......................................................CD:1583
HTMLImageElement.useMap ..............................................CD:1583
HTMLImageElement.vspace ................................................CD:1584
HTMLImageElement.width ..................................................CD:1584
HTMLInputElement ..............................................................CD:1585
HTMLInputElement.accept ..................................................CD:1587
00 0672321419 FM 7/24/01 11:46 AM Page xlii
xlii
HTMLInputElement.accessKey ............................................CD:1587
HTMLInputElement.align ....................................................CD:1588
HTMLInputElement.alt ........................................................CD:1588
HTMLInputElement.blur() ....................................................CD:1589
HTMLInputElement.checked ................................................CD:1589
HTMLInputElement.click() ..................................................CD:1590
HTMLInputElement.defaultChecked ....................................CD:1591
HTMLInputElement.defaultValue ........................................CD:1591
HTMLInputElement.disabled ................................................CD:1592
HTMLInputElement.focus() ..................................................CD:1593
HTMLInputElement.form......................................................CD:1593
HTMLInputElement.maxLength ..........................................CD:1594
HTMLInputElement.name ....................................................CD:1594
HTMLInputElement.readOnly ..............................................CD:1595
HTMLInputElement.select()..................................................CD:1596
HTMLInputElement.size ......................................................CD:1596
HTMLInputElement.src ........................................................CD:1597
HTMLInputElement.tabIndex ..............................................CD:1597
HTMLInputElement.type ......................................................CD:1598
HTMLInputElement.useMap ................................................CD:1599
HTMLInputElement.value ....................................................CD:1599
HTMLIsIndexElement ..........................................................CD:1600
HTMLIsIndexElement.form ..................................................CD:1601
HTMLIsIndexElement.prompt ..............................................CD:1601
HTMLLabelElement..............................................................CD:1602
HTMLLabelElement.accessKey ............................................CD:1603
HTMLLabelElement.form ....................................................CD:1603
HTMLLabelElement.htmlFor ................................................CD:1604
HTMLLegendElement ..........................................................CD:1604
HTMLLegendElement.accessKey ........................................CD:1605
HTMLLegendElement.align ..................................................CD:1606
HTMLLegendElement.form ..................................................CD:1606
HTMLLIElement ..................................................................CD:1607
HTMLLIElement.type ..........................................................CD:1608
HTMLLIElement.value..........................................................CD:1608
HTMLLinkElement ..............................................................CD:1609
HTMLLinkElement.charset ..................................................CD:1610
HTMLLinkElement.disabled ................................................CD:1610
HTMLLinkElement.href........................................................CD:1611
HTMLLinkElement.hreflang ................................................CD:1612
HTMLLinkElement.media ....................................................CD:1612
HTMLLinkElement.rel ..........................................................CD:1613
HTMLLinkElement.rev ........................................................CD:1613
HTMLLinkElement.target ....................................................CD:1614
HTMLLinkElement.type ......................................................CD:1615
00 0672321419 FM 7/24/01 11:46 AM Page xliii
xliii
HTMLMapElement................................................................CD:1615
HTMLMapElement.areas ......................................................CD:1616
HTMLMapElement.name......................................................CD:1616
HTMLMenuElement..............................................................CD:1617
HTMLMenuElement.compact ..............................................CD:1618
HTMLMetaElement ..............................................................CD:1618
HTMLMetaElement.content..................................................CD:1619
HTMLMetaElement.httpEquiv ..............................................CD:1620
HTMLMetaElement.name ....................................................CD:1620
HTMLMetaElement.scheme..................................................CD:1621
HTMLModElement ..............................................................CD:1622
HTMLModElement.cite ........................................................CD:1622
HTMLModElement.dateTime ..............................................CD:1623
HTMLObjectElement ............................................................CD:1624
HTMLObjectElement.align ..................................................CD:1625
HTMLObjectElement.archive................................................CD:1625
HTMLObjectElement.border ................................................CD:1626
HTMLObjectElement.code....................................................CD:1627
HTMLObjectElement.codeBase............................................CD:1627
HTMLObjectElement.codeType............................................CD:1628
HTMLObjectElement.contentDocument ..............................CD:1628
HTMLObjectElement.data ....................................................CD:1629
HTMLObjectElement.declare................................................CD:1630
HTMLObjectElement.form ..................................................CD:1630
HTMLObjectElement.height ................................................CD:1631
HTMLObjectElement.hspace ................................................CD:1631
HTMLObjectElement.name ..................................................CD:1632
HTMLObjectElement.standby ..............................................CD:1633
HTMLObjectElement.tabIndex ............................................CD:1633
HTMLObjectElement.type ....................................................CD:1634
HTMLObjectElement.useMap ..............................................CD:1634
HTMLObjectElement.vspace ................................................CD:1635
HTMLObjectElement.width ..................................................CD:1636
HTMLOListElement..............................................................CD:1636
HTMLOListElement.compact ..............................................CD:1637
HTMLOListElement.start......................................................CD:1637
HTMLOListElement.type......................................................CD:1638
HTMLOptGroupElement ......................................................CD:1639
HTMLOptGroupElement.disabled ........................................CD:1639
HTMLOptGroupElement.label..............................................CD:1640
HTMLOptionElement............................................................CD:1641
HTMLOptionElement.defaultSelected ..................................CD:1642
HTMLOptionElement.disabled ............................................CD:1642
HTMLOptionElement.form ..................................................CD:1643
HTMLOptionElement.index ..................................................CD:1644
00 0672321419 FM 7/24/01 11:46 AM Page xliv
xliv
HTMLOptionElement.label ..................................................CD:1645
HTMLOptionElement.selected..............................................CD:1645
HTMLOptionElement.text ....................................................CD:1646
HTMLOptionElement.value ..................................................CD:1647
HTMLParagraphElement ......................................................CD:1647
HTMLParagraphElement.align..............................................CD:1648
HTMLParamElement ............................................................CD:1649
HTMLParamElement.name ..................................................CD:1649
HTMLParamElement.type ....................................................CD:1650
HTMLParamElement.value ..................................................CD:1651
HTMLParamElement.valueType ..........................................CD:1651
HTMLPreElement..................................................................CD:1652
HTMLPreElement.width ......................................................CD:1653
HTMLQuoteElement ............................................................CD:1653
HTMLQuoteElement.cite ......................................................CD:1654
HTMLScriptElement ............................................................CD:1654
HTMLScriptElement.charset ................................................CD:1655
HTMLScriptElement.defer ....................................................CD:1656
HTMLScriptElement.event....................................................CD:1657
HTMLScriptElement.htmlFor ..............................................CD:1657
HTMLScriptElement.src........................................................CD:1657
HTMLScriptElement.text ......................................................CD:1658
HTMLScriptElement.type ....................................................CD:1658
HTMLSelectElement ............................................................CD:1659
HTMLSelectElement.add()....................................................CD:1660
HTMLSelectElement.blur() ..................................................CD:1661
HTMLSelectElement.disabled ..............................................CD:1661
HTMLSelectElement.focus() ................................................CD:1662
HTMLSelectElement.form ....................................................CD:1663
HTMLSelectElement.length ..................................................CD:1663
HTMLSelectElement.multiple ..............................................CD:1664
HTMLSelectElement.name ..................................................CD:1665
HTMLSelectElement.options ................................................CD:1665
HTMLSelectElement.remove()..............................................CD:1666
HTMLSelectElement.selectedIndex ......................................CD:1667
HTMLSelectElement.size......................................................CD:1667
HTMLSelectElement.tabIndex ..............................................CD:1668
HTMLSelectElement.type ....................................................CD:1669
HTMLSelectElement.value....................................................CD:1669
HTMLStyleElement ..............................................................CD:1670
HTMLStyleElement.disabled ................................................CD:1671
HTMLStyleElement.media....................................................CD:1671
HTMLStyleElement.type ......................................................CD:1672
HTMLTableCaptionElement..................................................CD:1673
HTMLTableCaptionElement.align ........................................CD:1673
00 0672321419 FM 7/24/01 11:46 AM Page xlv
xlv
HTMLTableCellElement........................................................CD:1674
HTMLTableCellElement.abbr................................................CD:1675
HTMLTableCellElement.align ..............................................CD:1676
HTMLTableCellElement.axis ................................................CD:1676
HTMLTableCellElement.bgColor..........................................CD:1677
HTMLTableCellElement.cellIndex ........................................CD:1677
HTMLTableCellElement.ch ..................................................CD:1678
HTMLTableCellElement.chOff..............................................CD:1678
HTMLTableCellElement.colSpan..........................................CD:1679
HTMLTableCellElement.headers ..........................................CD:1680
HTMLTableCellElement.height ............................................CD:1680
HTMLTableCellElement.noWrap..........................................CD:1681
HTMLTableCellElement.rowSpan ........................................CD:1681
HTMLTableCellElement.scope..............................................CD:1682
HTMLTableCellElement.vAlign............................................CD:1682
HTMLTableCellElement.width..............................................CD:1683
HTMLTableColElement ........................................................CD:1683
HTMLTableColElement.align................................................CD:1684
HTMLTableColElement.ch....................................................CD:1685
HTMLTableColElement.chOff ..............................................CD:1686
HTMLTableColElement.span ................................................CD:1686
HTMLTableColElement.vAlign ............................................CD:1687
HTMLTableColElement.width ..............................................CD:1687
HTMLTableElement ..............................................................CD:1688
HTMLTableElement.align ....................................................CD:1689
HTMLTableElement.bgColor ................................................CD:1690
HTMLTableElement.border ..................................................CD:1690
HTMLTableElement.caption..................................................CD:1691
HTMLTableElement.cellPadding ..........................................CD:1692
HTMLTableElement.cellSpacing ..........................................CD:1692
HTMLTableElement.createCaption() ....................................CD:1693
HTMLTableElement.createTFoot() ......................................CD:1693
HTMLTableElement.createTHead() ......................................CD:1694
HTMLTableElement.deleteCaption() ....................................CD:1695
HTMLTableElement.deleteRow()..........................................CD:1695
HTMLTableElement.deleteTFoot() ......................................CD:1696
HTMLTableElement.deleteTHead() ......................................CD:1696
HTMLTableElement.frame ....................................................CD:1697
HTMLTableElement.insertRow() ..........................................CD:1698
HTMLTableElement.rows......................................................CD:1698
HTMLTableElement.rules......................................................CD:1699
HTMLTableElement.summary ..............................................CD:1699
HTMLTableElement.tBodies ................................................CD:1700
HTMLTableElement.tFoot ....................................................CD:1701
HTMLTableElement.tHead....................................................CD:1701
00 0672321419 FM 7/24/01 11:46 AM Page xlvi
xlvi
HTMLTableElement.width ....................................................CD:1702
HTMLTableRowElement ......................................................CD:1702
HTMLTableRowElement.align ..............................................CD:1703
HTMLTableRowElement.bgColor ........................................CD:1704
HTMLTableRowElement.cells ..............................................CD:1705
HTMLTableRowElement.ch ..................................................CD:1705
HTMLTableRowElement.chOff ............................................CD:1706
HTMLTableRowElement.deleteCell() ..................................CD:1706
HTMLTableRowElement.insertCell()....................................CD:1707
HTMLTableRowElement.rowIndex ......................................CD:1708
HTMLTableRowElement.sectionRowIndex ..........................CD:1708
HTMLTableRowElement.vAlign ..........................................CD:1709
HTMLTableSectionElement ..................................................CD:1709
HTMLTableSectionElement.align ........................................CD:1710
HTMLTableSectionElement.ch..............................................CD:1711
HTMLTableSectionElement.chOff ........................................CD:1711
HTMLTableSectionElement.deleteRow()..............................CD:1712
HTMLTableSectionElement.insertRow() ..............................CD:1713
HTMLTableSectionElement.rows..........................................CD:1713
HTMLTableSectionElement.vAlign ......................................CD:1714
HTMLTextAreaElement ........................................................CD:1714
HTMLTextAreaElement.accessKey ......................................CD:1715
HTMLTextAreaElement.blur() ..............................................CD:1716
HTMLTextAreaElement.cols ................................................CD:1717
HTMLTextAreaElement.defaultValue ..................................CD:1717
HTMLTextAreaElement.disabled ..........................................CD:1718
HTMLTextAreaElement.focus() ............................................CD:1718
HTMLTextAreaElement.form................................................CD:1719
HTMLTextAreaElement.name ..............................................CD:1720
HTMLTextAreaElement.readOnly ........................................CD:1720
HTMLTextAreaElement.rows................................................CD:1721
HTMLTextAreaElement.select()............................................CD:1721
HTMLTextAreaElement.tabIndex..........................................CD:1722
HTMLTextAreaElement.type ................................................CD:1723
HTMLTextAreaElement.value ..............................................CD:1723
HTMLTitleElement................................................................CD:1724
HTMLTitleElement.text ........................................................CD:1725
HTMLUListElement..............................................................CD:1725
HTMLUListElement.compact ..............................................CD:1726
HTMLUListElement.type......................................................CD:1727
xlvii
Event.type ..............................................................................CD:1734
Event.bubbles ........................................................................CD:1734
Event.cancelable ....................................................................CD:1735
Event.currentTarget................................................................CD:1736
Event.eventPhase ..................................................................CD:1736
Event.initEvent() ....................................................................CD:1737
Event.preventDefault() ..........................................................CD:1738
Event.stopPropagation() ........................................................CD:1739
Event.target ............................................................................CD:1739
Event.timeStamp....................................................................CD:1740
EventException ......................................................................CD:1741
EventException.code ............................................................CD:1742
EventListener ........................................................................CD:1743
EventTarget ............................................................................CD:1744
EventTarget.addEventListener() ............................................CD:1745
EventTarget.dispatchEvent() ..................................................CD:1746
EventTarget.removeEventListener() ......................................CD:1747
MouseEvent ..........................................................................CD:1748
MouseEvent.altKey................................................................CD:1749
MouseEvent.button ................................................................CD:1749
MouseEvent.clientX ..............................................................CD:1750
MouseEvent.clientY ..............................................................CD:1751
MouseEvent.ctrlKey ..............................................................CD:1751
MouseEvent.initMouseEvent() ..............................................CD:1752
MouseEvent.metaKey ............................................................CD:1753
MouseEvent.relatedTarget ....................................................CD:1753
MouseEvent.screenX ............................................................CD:1754
MouseEvent.screenY ............................................................CD:1754
MouseEvent.shiftKey ............................................................CD:1755
MutationEvent........................................................................CD:1756
MutationEvent.relatedNode ..................................................CD:1757
MutationEvent.attrChange ....................................................CD:1758
MutationEvent.attrName........................................................CD:1758
MutationEvent.initMutationEvent() ......................................CD:1759
MutationEvent.newValue ......................................................CD:1760
MutationEvent.prevValue ......................................................CD:1760
UIEvent ..................................................................................CD:1761
UIEvent.detail ........................................................................CD:1762
UIEvent.initUIEvent()............................................................CD:1762
UIEvent.view ........................................................................CD:1763
xlviii
Counter.separator ..................................................................CD:1769
CSSCharsetRule ....................................................................CD:1770
CSSCharsetRule.encoding ....................................................CD:1770
CSSFontFaceRule ..................................................................CD:1771
CSSFontFaceRule.style..........................................................CD:1771
CSSImportRule ......................................................................CD:1772
CSSImportRule.href ..............................................................CD:1773
CSSImportRule.media ..........................................................CD:1773
CSSImportRule.styleSheet ....................................................CD:1774
CSSMediaRule ......................................................................CD:1774
CSSMediaRule.cssRules........................................................CD:1775
CSSMediaRule.deleteRule()..................................................CD:1776
CSSMediaRule.insertRule() ..................................................CD:1776
CSSMediaRule.media............................................................CD:1777
CSSPageRule ........................................................................CD:1778
CSSPageRule.selectorText ....................................................CD:1778
CSSPageRule.style ................................................................CD:1779
CSSPrimitiveValue ................................................................CD:1779
CSSPrimitiveValue.getCounterValue() ..................................CD:1782
CSSPrimitiveValue.getFloatValue() ......................................CD:1782
CSSPrimitiveValue.getRectValue()........................................CD:1783
CSSPrimitiveValue.getRGBColorValue()..............................CD:1783
CSSPrimitiveValue.getStringValue() ....................................CD:1784
CSSPrimitiveValue.primitiveType ........................................CD:1785
CSSPrimitiveValue.setFloatValue() ......................................CD:1785
CSSPrimitiveValue.setStringValue()......................................CD:1786
CSSRule ................................................................................CD:1786
CSSRule.cssText ....................................................................CD:1787
CSSRule.parentRule ..............................................................CD:1788
CSSRule.parentStyleSheet ....................................................CD:1789
CSSRule.type ........................................................................CD:1789
CSSRuleList ..........................................................................CD:1790
CSSRuleList.item()................................................................CD:1791
CSSRuleList.length................................................................CD:1791
CSSStyleDeclaration..............................................................CD:1792
CSSStyleDeclaration.cssText ................................................CD:1793
CSSStyleDeclaration.getPropertyCSSValue() ......................CD:1794
CSSStyleDeclaration.getPropertyPriority() ..........................CD:1794
CSSStyleDeclaration.getPropertyValue() ..............................CD:1795
CSSStyleDeclaration.item() ..................................................CD:1796
CSSStyleDeclaration.length ..................................................CD:1796
CSSStyleDeclaration.parentRule ..........................................CD:1797
CSSStyleDeclaration.removeProperty() ................................CD:1797
CSSStyleDeclaration.setProperty()........................................CD:1798
CSSStyleRule ........................................................................CD:1799
00 0672321419 FM 7/24/01 11:46 AM Page xlix
xlix
CSSStyleRule.selectorText ....................................................CD:1799
CSSStyleRule.style ................................................................CD:1800
CSSStyleSheet ......................................................................CD:1800
CSSStyleSheet.cssRules ........................................................CD:1801
CSSStyleSheet.deleteRule() ..................................................CD:1802
CSSStyleSheet.insertRule() ..................................................CD:1802
CSSStyleSheet.ownerRule ....................................................CD:1803
CSSUnknownRule ................................................................CD:1804
CSSValue ..............................................................................CD:1804
CSSValue.cssText ..................................................................CD:1805
CSSValue.cssValueType ........................................................CD:1806
CSSValueList ........................................................................CD:1806
CSSValueList.item() ..............................................................CD:1807
CSSValueList.length ..............................................................CD:1808
DocumentCSS........................................................................CD:1809
DocumentCSS.getOverrideStyle() ........................................CD:1809
DOMImplementationCSS......................................................CD:1810
DOMImplementationCSS.createCSSStyleSheet() ................CD:1810
ElementCSSInlineStyle..........................................................CD:1811
ElementCSSInlineStyle.style ................................................CD:1812
Rect ........................................................................................CD:1812
Rect.bottom............................................................................CD:1813
Rect.left..................................................................................CD:1814
Rect.right................................................................................CD:1814
Rect.top ..................................................................................CD:1815
RGBColor ..............................................................................CD:1815
RGBColor.blue ......................................................................CD:1816
RGBColor.green ....................................................................CD:1817
RGBColor.red ........................................................................CD:1817
ViewCSS ................................................................................CD:1818
ViewCSS.getComputedStyle() ..............................................CD:1818
Drive.DriveLetter ..................................................................CD:1834
Drive.DriveType ....................................................................CD:1835
Drive.FileSystem....................................................................CD:1836
Drive.FreeSpace ....................................................................CD:1837
Drive.IsReady ........................................................................CD:1838
Drive.Path ..............................................................................CD:1838
Drive.RootFolder ..................................................................CD:1839
Drive.SerialNumber ..............................................................CD:1840
Drive.ShareName ..................................................................CD:1840
Drive.TotalSize ......................................................................CD:1841
Drive.VolumeName................................................................CD:1842
Drives ....................................................................................CD:1842
Drives.Count ..........................................................................CD:1843
Drives.Item() ..........................................................................CD:1844
File ........................................................................................CD:1845
File.Attributes ........................................................................CD:1846
File.Copy() ............................................................................CD:1847
File.DateCreated ....................................................................CD:1848
File.DateLastAccessed ..........................................................CD:1849
File.DateLastModified ..........................................................CD:1850
File.Delete..............................................................................CD:1851
File.Drive ..............................................................................CD:1852
File.Move() ............................................................................CD:1853
File.Name ..............................................................................CD:1854
File.OpenAsTextStream() ......................................................CD:1854
File.ParentFolder....................................................................CD:1856
File.Path ................................................................................CD:1857
File.ShortName ......................................................................CD:1857
File.ShortPath ........................................................................CD:1858
File.Size ................................................................................CD:1859
File.Type ................................................................................CD:1860
Files........................................................................................CD:1861
Files.Count ............................................................................CD:1862
Files.Item ..............................................................................CD:1863
FileSystemObject ..................................................................CD:1864
FileSystemObject.BuildPath() ..............................................CD:1865
FileSystemObject.CopyFile ..................................................CD:1866
FileSystemObject.CopyFolder() ............................................CD:1867
FileSystemObject.CreateFolder() ..........................................CD:1869
FileSystemObject.CreateTextFile()........................................CD:1869
FileSystemObject.DeleteFile() ..............................................CD:1871
FileSystemObject.DeleteFolder() ..........................................CD:1872
FileSystemObject.DriveExists() ............................................CD:1873
FileSystemObject.Drives ......................................................CD:1874
FileSystemObject.FileExists() ..............................................CD:1874
00 0672321419 FM 7/24/01 11:46 AM Page li
li
FileSystemObject.FolderExists() ..........................................CD:1876
FileSystemObject.GetAbsolutePathName() ..........................CD:1877
FileSystemObject.GetBaseName() ........................................CD:1878
FileSystemObject.GetDrive() ................................................CD:1879
FileSystemObject.GetDriveName() ......................................CD:1879
FileSystemObject.GetExtensionName()................................CD:1880
FileSystemObject.GetFile() ..................................................CD:1882
FileSystemObject.GetFileName()..........................................CD:1882
FileSystemObject.GetFolder() ..............................................CD:1883
FileSystemObject.GetParentFolderName() ..........................CD:1885
FileSystemObject.GetSpecialFolder() ..................................CD:1885
FileSystemObject.GetTempName() ......................................CD:1886
FileSystemObject.MoveFile()................................................CD:1887
FileSystemObject.MoveFolder()............................................CD:1888
FileSystemObject.OpenTextFile() ........................................CD:1889
Folder ....................................................................................CD:1891
Folder.Attributes ....................................................................CD:1892
Folder.Copy() ........................................................................CD:1893
Folder.DateCreated ................................................................CD:1894
Folder.DateLastAccessed ......................................................CD:1895
Folder.DateLastModified ......................................................CD:1896
Folder.Delete() ......................................................................CD:1897
Folder.Drive ..........................................................................CD:1898
Folder.Files ............................................................................CD:1899
Folder.IsRootFolder ..............................................................CD:1899
Folder.Move() ........................................................................CD:1900
Folder.Name ..........................................................................CD:1901
Folder.ParentFolder................................................................CD:1902
Folder.Path ............................................................................CD:1903
Folder.ShortName ..................................................................CD:1903
Folder.ShortPath ....................................................................CD:1904
Folder.Size ............................................................................CD:1905
Folder.SubFolders ..................................................................CD:1906
Folder.Type ............................................................................CD:1907
Folders....................................................................................CD:1908
Folders.Add() ........................................................................CD:1909
Folders.Count ........................................................................CD:1910
Folders.Item ..........................................................................CD:1911
TextStream ............................................................................CD:1912
TextStream.AtEndOfLine ......................................................CD:1913
TextStream.AtEndOfStream ..................................................CD:1914
TextStream.Close() ................................................................CD:1915
TextStream.Column ..............................................................CD:1915
TextStream.Line ....................................................................CD:1916
TextStream.Read() ................................................................CD:1917
00 0672321419 FM 7/24/01 11:46 AM Page lii
lii
TextStream.ReadAll() ............................................................CD:1918
TextStream.ReadLine() ..........................................................CD:1919
TextStream.Skip() ..................................................................CD:1919
TextStream.SkipLine() ..........................................................CD:1920
TextStream.Write() ................................................................CD:1921
TextStream.WriteBlankLines() ..............................................CD:1922
TextStream.WriteLine() ........................................................CD:1923
liii
WshController.WshRemote ..................................................CD:1954
WshEnvironment ..................................................................CD:1954
WshEnvironment.Count() ......................................................CD:1956
WshEnvironment.Item() ........................................................CD:1957
WshEnvironment.length ........................................................CD:1957
WshEnvironment.Remove() ..................................................CD:1958
WshNamed ............................................................................CD:1960
WshNamed.Count() ..............................................................CD:1961
WshNamed.Exists() ..............................................................CD:1961
WshNamed.Item ....................................................................CD:1962
WshNamed.length..................................................................CD:1963
WshNetwork ..........................................................................CD:1963
WshNetwork.AddPrinterConnection() ..................................CD:1964
WshNetwork.AddWindowsPrinterConnection() ..................CD:1965
WshNetwork.ComputerName................................................CD:1966
WshNetwork.EnumNetworkDrives() ....................................CD:1967
WshNetwork.EnumPrinterConnection()................................CD:1967
WshNetwork.MapNetworkDrive() ........................................CD:1968
WshNetwork.RemoveNetworkDrive() ..................................CD:1969
WshNetwork.RemovePrinterConnection() ............................CD:1970
WshNetwork.SetDefaultPrinter() ..........................................CD:1970
WshNetwork.UserDomain ....................................................CD:1971
WshNetwork.UserName ........................................................CD:1971
WshRemote............................................................................CD:1972
WshRemote.End ....................................................................CD:1973
WshRemote.Error (Event) ....................................................CD:1974
WshRemote.Error (Property) ................................................CD:1974
WshRemote.Execute() ..........................................................CD:1975
WshRemote.WshRemoteError ..............................................CD:1976
WshRemote.Start ..................................................................CD:1976
WshRemote.Status ................................................................CD:1977
WshRemote.Terminate() ........................................................CD:1978
WshRemoteError ..................................................................CD:1979
WshRemoteError.Character ..................................................CD:1980
WshRemoteError.Description................................................CD:1980
WshRemoteError.Line ..........................................................CD:1981
WshRemoteError.Number ....................................................CD:1982
WshRemoteError.Source ......................................................CD:1983
WshRemoteError.SourceText ................................................CD:1984
WshScriptExec ......................................................................CD:1985
WshScriptExec.Status ............................................................CD:1985
WshScriptExec.StdErr ..........................................................CD:1986
WshScriptExec.StdIn ............................................................CD:1987
WshScriptExec.StdOut ..........................................................CD:1988
WshScriptExec.Terminate() ..................................................CD:1989
00 0672321419 FM 7/24/01 11:46 AM Page liv
WshShell ................................................................................CD:1990
WshShell.AppActivate() ........................................................CD:1991
WshShell.CreateShortcut() ....................................................CD:1991
WshShell.CurrentDirectory ..................................................CD:1992
WshShell.Environment ..........................................................CD:1993
WshShell.Exec() ....................................................................CD:1993
WshShell.ExpandEnvironmentStrings() ................................CD:1994
WshShell.LogEvent() ............................................................CD:1995
WshShell.Popup() ..................................................................CD:1996
WshShell.RegDelete() ..........................................................CD:1997
WshShell.RegRead()..............................................................CD:1998
WshShell.RegWrite() ............................................................CD:1998
WshShell.Run()......................................................................CD:1999
WshShell.SendKeys() ............................................................CD:2000
WshShell.SpecialFolders ......................................................CD:2002
WshShell.WshShortcut ..........................................................CD:2003
WshShell.WshUrlShortcut ....................................................CD:2003
WshShell.WshEnvironment ..................................................CD:2003
WshShell.WshSpecialFolders ................................................CD:2004
WshShell.WshScriptExec ......................................................CD:2004
WshShortcut ..........................................................................CD:2004
WshShortcut.Arguments ........................................................CD:2005
WshShortcut.Description ......................................................CD:2006
WshShortcut.FullName..........................................................CD:2007
WshShortcut.Hotkey ..............................................................CD:2007
WshShortcut.IconLocation ....................................................CD:2008
WshShortcut.Save() ..............................................................CD:2009
WshShortcut.TargetPath ........................................................CD:2010
WshShortcut.WindowStyle....................................................CD:2010
WshShortcut.WorkingDirectory ............................................CD:2011
WshSpecialFolders ................................................................CD:2012
WshSpecialFolders.Count......................................................CD:2013
WshSpecialFolders.Item ........................................................CD:2014
WshSpecialFolders.length ....................................................CD:2015
WshUnnamed ........................................................................CD:2015
WshUnnamed.Count() ..........................................................CD:2017
WshUnnamed.Item ................................................................CD:2018
WshUnnamed.length..............................................................CD:2019
WshUrlShortcut ....................................................................CD:2019
WshUrlShortcut.FullName ....................................................CD:2020
WshUrlShortcut.Save() ..........................................................CD:2021
WshUrlShortcut.TargetPath ..................................................CD:2022
00 0672321419 FM 7/24/01 11:46 AM Page lv
Dedications
This one is for my sisters: Sandra, Valerie, and Evelyn. They truly are inspirations in my life
and have broadened my visions and provided support well beyond anything I would have ever
imagined. I love each of you very much.
—R. Allen Wyke
I dedicate this book to my wonderful wife, Deena, who is the greatest! Your constant encour-
agement, love, and support has carried me through the writing of this book. I love you!
—Jason D. Gilliam
This book is dedicated to my family: John, Alice, Angela, Melissa, Olivia, and Tilly. Thank you
for all your love and support for everything I’ve done in my life. I love you all very much.
—Charlton Ting
I would like to dedicate this book to my wife April and my two children Noah, and Anna, and
to the memory of my father Alan Michaels without whose influence I would not be here today.
—Sean Michaels
Acknowledgments
R. Allen Wyke
On the publishing side, I would like to thank Bob Kern of TIPS Publishing and my
coauthors, Jason and Chuck, for their professionalism, hard work, and overall support
in the proposing and writing of this book. I would also like to thank Shelley Johnston-
Markanday, who has been nothing short of an absolutely fabulous acquisitions editor,
and Jon Steever, who developed the book and kept us focused. Additionally, I would
like to thank everyone at Sams who worked on the book and helped make sure that was
the best it could be.
I would also like to thank Dan Jaye for the professional opportunities he has allowed
me to pursue at Engage, as well as the pressure to push the envelope a little more. And
finally, I would like to thank the wonderful woman in my life, J, and the rest of the
“Raccoons.” It’s never a dull moment around any of you.
Jason D. Gilliam
I would like to thank Bob Kern of TIPS Publishing and my coauthors, Allen and
Chuck, for their efforts in developing and writing this book. I would also like to thank
our acquisitions editor, Shelley Johnston-Markanday, and development editor, Jon
Steever, for all their hard work as well as everyone at Sams who helped make this book
a success.
I would also like to thank the “lunch guys” for their open ears and words of encour-
agement.
00 0672321419 FM 7/24/01 11:46 AM Page lvii
Charlton Ting
I would like to thank Bob Kern of TIPS Publishing for all his hard work in making this
book possible. I also want to thank my coauthors, Allen and Jason, for all their hard
work, dedication, and encouragement to bring this book together and make it such a
great success. It’s truly an honor to work with you guys. Additionally I would like to
thank Shelley Johnston-Markanday, Scott Meyers, Jon Steever, and everyone at Sams
who worked so hard at making this book so successful.
I also want to thank all my friends who have been there when I needed them: Mike,
Carolyn, Monty, Theresa, Mitch, Sabrina, John O, Sunil “the Z Doc” Cherukuri,
Blanke, Cosima, Nairn, Airmer Roberts, and anyone I may have forgotten to mention.
You guys are the greatest friends anyone could have.
Sean Michaels
I would like to thank Bob Kern at TIPS Publishing for putting up with my antics dur-
ing the authoring process. Also, the coauthors: Allen, Chuck, and Jason for giving me
a solid foundation to work with and making the first edition of this book successful. I
would also like to thank the folks at Sams Publishing: Shelley Johnston-Markanday,
Scott Meyers, and Jon Steever for guiding the book through the process.
00 0672321419 FM 7/24/01 11:46 AM Page lviii
Introduction
Welcome to Pure JavaScript, 2nd Edition! This book has been written by JavaScript
programmers for JavaScript programmers, and has been updated to cover the most cur-
rent version of the language. It is your complete reference for developing, testing, and
deploying JavaScript solutions in pages and on Web sites.
Pure JavaScript was not written to teach a person how to program, but rather to provide
the details and semantics of the JavaScript language so programmers can exploit it as
they see fit. JavaScript has evolved over the past few years and is reaching into new
areas, especially in the most current browsers and server-side environments, most of
which are addressed in this book. The book itself is broken into three main parts,
including references on concepts, techniques, and syntax. Each represents a valuable
step in learning and using the language.
Part I, “A Programmer’s Overview of JavaScript,” acts as a bridge for programmers
who are currently programming in another language. It covers some programming
techniques, such as the use of regular expressions, event handlers, exceptions, and even
debugging. Many times programmers don’t want to buy a beginners book on JavaScript
because they do not need to know how to program, but rather they need specifics about
the language. When they know these specifics and semantics, the syntax is easy. This
section provides the necessary information for such a programming migration.
Part II, “Programming in JavaScript,” shows you the advantages and strengths of
JavaScript. It discusses some of the pros and cons of using the language on the client-
side, server-side, and even within the Windows Script Host environment. Programmers
will learn how to use JavaScript in real-world instances. They will be introduced to
some of the browser issues as well as how to process Web information. In addition, pro-
grammers will be shown how to access Java functions within an applet and to use
server-side JavaScript for Internet, intranet, or extranet development. After you have
completed this section, you will be ready to move forward and start programming. This
leads you into the last section of the book.
Part III, “JavaScript Reference,” makes up the majority of the book and contains some
of the most useful information for current JavaScript programmers—reference mater-
ial organized by object. Each property, method, and event is discussed in detail under
its associated object; and you’ll see an example of its use. Each entry also shows the
appropriate language version and environment (browser, server, and so on) support.
The section itself is broken into nine chapters. The first chapter covers the core
JavaScript objects and syntax. The next chapter covers objects specific to the client-
side, which is where JavaScript really has its roots. The third, fourth, fifth, and sixth
chapter in this section outlines the various support for the Document Object Model
(DOM) within JavaScript. The seventh chapter covers server-side JavaScript objects for
the Netscape and iPlanet Enterprise servers, and the Active Server pages (ASP) envi-
ronment present in Microsoft’s IIS Web Servers. The second to last chapter in the sec-
tion covers the JScript RunTime objects, and the final chapter covers Windows Script
Host.
01 0672321416 Intro 7/24/01 11:47 AM Page 2
2 Introduction
And that covers it! For new JavaScript programmers, welcome to the world of
JavaScript. For those of you wanting a good, solid reference for your programming
needs, we hope you find this book to be the most resourceful and current title on the
shelves today!
R. Allen Wyke
Jason Gilliam
Charlton Ting
Sean Michaels
02 0672321416 Part I 7/24/01 11:47 AM Page 3
PA R T I
A PROGRAMMER’S
OVERVIEW OF
JAVASCRIPT
1 What Is JavaScript to a Programmer? 5
2 Details of the Language 31
02 0672321416 Part I 7/24/01 11:47 AM Page 4
03 0672321416 CH01 7/24/01 11:47 AM Page 5
What Is JavaScript to a
Programmer?
In the beginning, there were Assembly and compiled lan-
guages. Later came scripting languages such as sed, awk, and
Perl, which many programmers used to perform a variety of
tasks. Followed by, in the late 80s and early 90s, the Internet,
which exploded into a technological revolution that allowed
anyone with a modem to communicate and retrieve informa-
tion from around the world. As the Internet grew in number of
users, it was obvious that an increase in functionality was
needed in the browsers and the data they were rendering.
HTML, even with its advantages, was falling short of provid-
ing the control many developers wanted when creating Web
pages and applications. This prompted the use of server-side
programs, or scripts as they were often called, to handle some
of the page dynamics developers needed from their sites.
These programs helped Web developers by allowing them to
increase a site’s functionality as well as process user-submitted
information. However, CGI, or common gateway interface,
scripts had to generate and return a response when the user sent
incorrect or incomplete information. This led to the unneces-
sary back-and-forth transmission of data between browser and
server. But, overall, it was a minor price to pay for the func-
tionality it provided.
With time, and an increase in traffic, it became increasingly
obvious that client-side intelligence was needed to offload
some of the CGI functionality. Something was needed to per-
form this error checking and to decrease the amount of time a
user spent connecting to a server to validate data. This would
03 0672321416 CH01 7/24/01 11:47 AM Page 6
also enable the Web site to offload some of its processing load to the browser machine,
which meant an increase in the overall performance of a site.
It was partially this lack of client-side functionality and efficiency that helped spawn a
new scripting language—one that could be executed within a browser’s environment
and not on the server. This language could be used to perform client-side tasks such as
form validation and dynamic page content creation—one that would put the program-
ming into HTML publishing. Welcome to the birth of JavaScript.
Welcome to JavaScript
On December 4, 1995, Netscape and Sun jointly introduced JavaScript 1.0, originally
called LiveScript, to the world. This language, unlike its server-based predecessors,
could be interpreted within the then new Netscape Navigator 2 browsers. As an inter-
preted language, JavaScript was positioned as a complement to Java and would allow
Web developers to create and deploy custom applications across the enterprise and
Internet alike. JavaScript gave Web developers the power to truly program—not just
format data with HTML.
In addition to the client-side control developers desired, Netscape implemented server-
side JavaScript. This allowed developers to use the same programming language on the
server as they did in their pages for browsers. Database connection enhancements were
added to the language (called LiveWire), allowing the developer to pull information
directly from a database and maintain user sessions for common functionality such as
shopping carts. JavaScript had truly bridged the gap between the simple world of
HTML and the more complex CGI programs on the server. It provided a common lan-
guage for Web developers to design, implement, and deploy solutions across their net-
works and distributed the overall processing load of their applications.
The next level of acceptance in the world of JavaScript was Microsoft’s implementa-
tion of the language in its Internet Explorer 3 browser—the implementation was called
JScript. Similar to Netscape, Microsoft also implemented the language on the server-
side (JScript 2.0) within its ASP (Active Server Pages) environment. It also allowed
developers the flexibility of using a common language on both the client and server-
side, while providing many of the robust features, such as object invocation and usage,
in compiled languages.
J AVA S C R I P T V E R S U S J S C R I P T, A N D W H AT I S
ECMASCRIPT?
JScript 1.0 was based on the published documentation from Netscape, so essen-
tially it is the same thing as JavaScript 1.0. However, there were a few “features”
that Netscape did not publish, as well as some functionality that was not re-cre-
ated by Microsoft correctly. The result of this is that there are some discrepancies
between JScript 1.0 and JavaScript 1.0.
Since the release of these initial browsers, JavaScript and JScript were both submit-
ted to the ECMA (European Computer Manufacturers Association) standardization
03 0672321416 CH01 7/24/01 11:47 AM Page 7
O b j e c t - B a s e d Te c h n o l o g y 7
body and have become the standard known as ECMAScript (ECMA-262). Because
of this standardization, it is now considered that JavaScript is Netscape’s implemen-
tation of ECMAScript while JScript is Microsoft’s implementation.
The adoption of the first edition of ECMAScript occurred in June 1997 followed by
its adoption by the International Organization for Standardization and International
Electrotechnical Commission in April 1998 (ISO/IEC 16262). A second edition of
the standard was approved by ECMA in June 1998, and a third edition was
adopted in December 1999.
NOTE
Because Netscape’s JavaScript was the foundation of all this, the book will refer to
JavaScript, JScript, and ECMAScript simply as JavaScript except where a differentia-
tion is needed.
So, what is JavaScript to the programmer? Well, in its purest form, it is an object-based,
cross-platform, loosely-typed, multi-use language that allows a programmer to deploy
many types of solutions to many clients. It not only involves adding functionality to
Web pages as rendered within a browser, it also allows server-side processing for
Netscape and Microsoft Web servers.
JScript has also been included in Microsoft’s Windows Script Host (WSH), to allow
programmers to write scripts to be executed on the operating system itself, and most
recently as a major language under their .NET strategy (more on that later). When oper-
ating within the WSH environment, JScript is similar to the old DOS batch files, but
gives programmers more functionality and versatility in what they can accomplish.
This type of advancement has allowed the language to take hold in the computer world
and continue to progress.
In addition to the benefits of these environments in which JavaScript can be executed,
security measures are in place to protect end users against malicious code. Even though
it is still young in terms of age, JavaScript is very mature and powerful. This function-
ality, ability, and versatility positions JavaScript as the best solution for many pro-
grammers.
Now that you’ve learned about what JavaScript is, you should dive a little deeper into
what it means to a programmer. Being programmers ourselves, we know that a few
strategically placed words do not make a language useful; so first, we’ll look at the
object-based characteristics of JavaScript.
Object-Based Technology
The fact that you are reading this reference somewhat implies that you have pro-
grammed in JavaScript or at least one other language before, even if only for one
semester in college. Going one step further, I bet the language you programmed in was
either C++, Java, or Perl—with each having various levels of object orientation (OO).
Java specifically is OO by virtue of having all programmer created objects extend from
core Java language classes or their own.
03 0672321416 CH01 7/24/01 11:47 AM Page 8
Object-Oriented Programming
For those of you unfamiliar with object-oriented programming (OOP), it is a concept
that allows you to create reusable objects or classes in code. An object or class has
associated with it various characteristics and functionality that defines what kind of
properties and states it can take on. After these are created and defined, it is possible to
create new instances—sometimes referred to as children—that inherit the capability to
have the same characteristics of their parent object.
To give you an example of how this might work, let’s create a vehicle object. Some of
the characteristics assigned to this vehicle object are the number of doors, the color,
and the type (such as sports car or truck). In addition to these characteristics, let’s
define the ability to move or stop the vehicle. The pseudo-code for this type of object
might look something similar to the following:
object vehicle(){
// Characteristics of the vehicle
num_doors;
color;
type;
// Methods used to move and stop the truck. Note that the move()
// method takes a direction as an argument. This direction could
// be something like forward, backward, left, or right.
move(direction);
stop();
}
Now that this vehicle object is defined, it is easy to create new instances of it. A vehi-
cle that is a car with four doors and is red can be easily created. You could also create
a vehicle that is a truck with two doors and is black. The possibilities are endless.
In addition to creating these instances of the vehicle object, you have also made it pos-
sible to program in the ability to change the state of your instance. This is accomplished
by specifying whether it is stopped or moving. Again, this method of programming can
make the possibilities endless and certainly reusable.
Here is another example in pseudo-code to illustrate this concept. The sample creates
a black, two-door truck that is moving forward:
// Create the new instance of the vehicle
myTruck = new vehicle();
Object-Oriented Programming 9
The basic process here is to create an instance of the vehicle object and then to assign
characteristic values to it. It is these values that make it a unique instance of this object,
which we have specified as a truck.
The existence of the vehicle object itself allows us to easily create more vehicles with
different characteristics. When programming, this “ease” translates into less code—
something all programmers like to hear.
Now that this object is defined, it is possible to create new instances that inherit its
characteristics without having to redefine them. You are able to capitalize on any over-
laps in characteristics within objects by doing this. The idea is to create a general, mas-
ter object that gives you the ability to then derive child instances that provide all the
functionality and characteristics you need.
We can take this a step further by creating new objects—not instances—that inherit the
parent objects’ characteristics. Doing so allows us to derive child instances from the
child object that we have decided will inherit only certain characteristics. We could
define a child object to only pass on the parent object’s color characteristic to any child
instances of its own. It is the concept of this object orientation that allows you to per-
form this modular type of programming.
The following pseudo-code example shows how we could create an airplane object
based on the previous vehicle object:
// Create the new object that inherits the vehicle
object airplane(){
// Now that the object is created with the values, return the
// object.
return this;
}
Not all languages support this concept, and there are other languages only based on its
concepts. This concept definitely supplies advantages to the language, but it is not
required to write good, effective, modular code. JavaScript is a perfect example of how
03 0672321416 CH01 7/24/01 11:47 AM Page 10
a language has applied some of these concepts, but is not completely OO. It does this
by being object based.
NOTE
Talking about OOP in further detail is beyond the focus of a JavaScript book, but it
is worth some investigation if you are a real programming enthusiast. Check out
your local bookstore for a selection of titles on this subject. You can also visit
Object Central (http://www.objectcentral.com) on the Web for reference and
links to OOP information.
So how does object-based programming fit into the equation? It is very similar to OO
except that it does not have all the functionality or characteristics. There are limited
amounts of inheritance, scope, and functionality that you can perform with an object-
based language. This should not be taken as mark against JavaScript, because it makes
the language easier to learn and maintain for the developer. OOP is no easy beast to
tackle and will provide many headaches before it is implemented correctly.
JavaScript also makes up for many of its OO limitations by allowing you to create your
own object-like elements, as well as extend the core objects in the language by proto-
typing new properties. To get an idea of how this is done, take a look at JavaScript
object orientation.
Core
First and foremost, it is important for you to know and understand the core objects in
the JavaScript language. These objects are generally found across all implementations
and are defined in the ECMAScript standard. These objects lay the foundation for the
shared functionality, such as mathematical, array, or date related, which are used in
most all scripts. Figure 1.1 shows a list of these core objects.
As you can see, the core objects are Array, Boolean, Date, Function, Global, Math,
Number, Object, RegExp, Error, and String. In addition to these objects, both Netscape
03 0672321416 CH01 7/24/01 11:47 AM Page 11
Object-Oriented Programming 11
and Microsoft have created objects specific to their core implementations. These are
not specific to any environment, and are therefore core objects in the sense of their con-
sistency. Figure 1.2 shows these objects.
Array
Boolean
Date
Core Error
Function
Global
Math
Number
Object
RegExp
String
Figure 1.1
Core ECMAScript object hierarchy.
Client-Side
Client-side JavaScript is, at its lowest level, a set of objects created when a page
is loaded in the browser. In addition, there are also objects that revolve around
the browser loading the page and other derived objects that are created when certain
tags are contained on a page. These derived objects inherit some of the various char-
acteristics of their parent object and also allow scripting access to the HTML tag’s
properties.
Understanding the hierarchy of the JavaScript objects is essential if you plan on doing
any in-depth programming. You will get a better understanding of how parent and
child objects interact as well as how they are referenced. To help with this under-
standing, Figure 1.3 gives a graphical representation of the basic client-side
JavaScript hierarchy.
03 0672321416 CH01 7/24/01 11:47 AM Page 12
As depicted in this diagram, all client-side objects are derived from either the Window
or navigator objects. Considering that this is an object-based language, this structure
makes complete sense. All objects on a given page are constructed within the browser’s
displaying window, hence all these objects are descendants of the Window object. By
using the Window object, a programmer is allowed to access the various frames, docu-
ments, layers, and forms on a page, as well as many other objects and properties.
Arguments
Java Class
Java Object
Java Package
JSException
JSObject
Packages
Microsoft ActiveX
Automation
Enumerator
VBArray
Figure 1.2
Core object hierarchy for Microsoft and Netscape environments.
The navigator object pertains to elements that are part of the browser itself. This
specifically refers to the plug-ins installed and the MIME (Multipart Internet Mail
Extension) types with which the browser is associated. Using the navigator object
allows checking of the browser version, determining the plug-ins installed, and what
programs are associated with the various MIME types registered on the system. There
is also the ability to access other properties of the browser.
In addition to these client-side objects, browsers starting with Internet Explorer 5 and
Netscape 6 have implemented features to support the Document Object Model (DOM).
The DOM is a method in which documents can be referenced. We talk more about the
DOM in Chapter 4, “Client-Side Scripting,” but wanted to include Figure 1.4 to show
you the objects that make up this model.
03 0672321416 CH01 7/24/01 11:48 AM Page 13
Object-Oriented Programming 13
Window navigator
Text MimeType
Frame
Layer FileUpload
Link Password
Area Submit
Anchor Reset
Location
Applet Radio
Plugin Checkbox
Figure 1.3
Client-side JavaScript object hierarchy.
Server-Side
Similar to client-side, server-side JavaScript has several objects from which all other
objects are derived. The root objects are the DbPool and database objects, for the
Netscape and iPlanet implementations, from which you can create connections to a
database, as well as access cursors, stored procedures, and the resultsets you generate.
Within the Microsoft ASP environment, you have access to several other objects, such
as Response, Session, and Request. Figure 1.5 shows the server-side objecthierarchy.
NOTE
Programmers familiar with Java will find this very similar to the Java language.
There are not as many objects/classes in the JavaScript language, but the structure
and manner in which you access them are similar.
03 0672321416 CH01 7/24/01 11:48 AM Page 14
DOM
Core HTML
HTMLLabelElement HTMLTableCellElement
HTMLFieldSetElement HTMLFrameSetElement
HTMLLegendElement HTMLFrameElement
HTMLUListElement HTMLIFrameElement
HTMLOListElement
HTMLDListElement
HTMLDirectoryElement
HTMLMenuElement
HTMLLIElement
HTMLBlockquoteElement
HTMLDivElement
HTMLParagraphElement
HTMLHeadingElement
HTMLQuoteElement
Figure 1.4
DOM object hierarchy.
03 0672321416 CH01 7/24/01 11:48 AM Page 15
Object-Oriented Programming 15
ASPError
Netscape/iPlanet ObjectContext
Request
Cursor Response
Cursor
database
Stproc Resultset
Figure 1.5
Server-side object hierarchy.
JScript Runtime
As with about every other language that Microsoft has put its hands on, its JScript
implementation contains objects that are specific to their runtime environment.
Because their JScript engine is used within several of their applications and is a very
important part of their .NET initiative, you will notice that many of the additional
objects are familiar if you have ever worked with COM. Figure 1.6 illustrates the
objects that are specific to the JScript implementation.
Dictionary
Drive
Drives
Files
Folder
Folders
Text Stream
Figure 1.6
JScript RunTime object hierarchy.
03 0672321416 CH01 7/24/01 11:48 AM Page 16
WshUnnamed
WshNetwork
WshShell WshShortcut
WshUrlShortcut
WshEnvironment
WshSpecial Folders
WshScript Exec
Figure 1.7
Windows Script Host object hierarchy.
Object Access
Because of this object hierarchy, accessing the various objects and elements on a page
is accomplished by using the hierarchy itself. If you wanted to access a specific text
field in a form on a page, you would do so using the following syntax:
window.document.formName.textboxName.value
TIP
With JavaScript, programmers have the ability to create their own objects or
extend the core ones defined by the language. The explanation of how to create
your own objects—and some examples—is covered in the section on functions in
Chapter 2, “Details of the Language.” If you want to learn more about extending
the functionality of the existing objects, look up objects with the prototype prop-
erty in the reference section of this book.
Object-Oriented Programming 17
you are able to better maintain the code with which you are working. You will be cre-
ating code that can be reused in other programs, locations, and instances. Why write
virtually the same code twice (or many times), when you can create it once and pass
the characteristics that differentiate it from other, similar objects?
Modular Programming
To program in a modular fashion in JavaScript really involves three key things. Using
these items in your programming will allow you to create code that can be reused from
project to project. These are
• Creating your own objects
• Defining general functions to handle common tasks
• Placing reusable code in external JavaScript source files (commonly *.js files)
NOTE
As with any other language, remember that good comments within your code and
documentation are often the most beneficial aspects of programming.
Because creating your own objects is discussed in Chapter 2, let’s take a look at defin-
ing functions to handle common tasks. As with other programming languages, there are
instances in which you have to perform certain processes over and over. Many times
this might involve a different value of parameters passed, but the processes you go
through are the same.
As an example, think of verifying a date entered by a user. This user is supposed to
enter the month, date, and year in a form that will be submitted to your Web server for
further processing. One of the concerns of the programmer is that he needs to have the
date in a MM/DD/YYYY format, where the month and date need to be two characters
and the year should be four.
To accomplish this task, you can create a single function that prepends a 0 in front of
any single digit passed. This function could simply check to see if the value passed was
less than the number 10, and, if so, it would perform the prepend. By defining this
process in a function, a programmer will be able to use the same function for both the
month and date verification. This avoids the trouble of writing a function for each.
Even though this is a simple example, it illustrates the benefits of function and code
reuse.
Programmers can also modularize their programming techniques by including their
code in external JavaScript source files. This allows them to write code once, store it
in a single location, and include it on many pages by simply referencing the location
of the source file. If the function needs to change, they only have to change it in a sin-
gle file and not every file that uses it. It is simple things such as these that save Web
programmers hours or days of work time.
03 0672321416 CH01 7/24/01 11:48 AM Page 18
TIP
Do you serve ads on your Web site? If so, you might want to consider placing your
ad tags in an external JavaScript source file. This will allow you to change the tags
across your entire site if need be. There might be some browser issues with older
versions, so if you make this decision, be sure you at least cover the browsers you
wish to support.
Security
One of the biggest issues facing Internet development today is security. It is not possi-
ble to successfully develop any kind of application, whether it’s Web based or based on
the Web, and not have to implement some kind of security features. A program’s secu-
rity measures can ultimately determine how valuable the overall application is to a user.
If the code can be tampered with or is subject to destruction from another program, the
program will be subject to scrutiny and denial of use.
Because JavaScript is interpreted most often within a browser’s environment, a user
can be subject to malicious code. Browser’s run off the operating system itself, mean-
ing that it has access to a user’s file system. This makes it feasible that a JavaScript pro-
gram could take advantage of a hole in the browser’s security measures to access the
file system. After a programmer has accomplished this, many things are possible—
even access to private documents or the ability to delete them altogether. This leaves a
user at the mercy of a hacker.
Providing security for JavaScript scripts is actually twofold. One is that of responsibil-
ity, which lies with the programmer. A programmer must ensure that the script the user
executes is not malicious. The second responsibility falls to the users themselves. Users
should make the ultimate decision whether to run a script on their systems—this is
something that must be implemented in the browser’s functionality.
Because of these potentially destructive situations, there are various levels of security
that users and programmers can rely on when programming in JavaScript. As dis-
cussed, some are the responsibility of the programmer, whereas others involve mea-
sures put in place by the browser that allow the user to control what is executed on his
system.
Security 19
security. Leave it to the experts to protect the users. However, where there is a will
there is a way, and the first misuses of JavaScript began to surface.
One of the first items that seemed to be a potential problem occurred when frames were
used on a Web site. Because frames load separate documents in each of the predefined
areas, it is possible to load documents from several different domains and servers to
make up the content displayed to the user. The problem arose when a document’s
JavaScript variables from one server were available for examination and modification
on another. But this was only the start of the potential security holes that would follow.
To help protect users from the frame problem, Navigator 2, Internet Explorer 3, and
Opera 3 implemented the Same Origin Policy. This policy prevented JavaScript code
sent from one server from accessing properties of a document sent from another server,
port, or protocol and returning that information to its original server.
Obviously, this policy does not affect all the elements of a given document, but it does
include a core set. At the time of this printing, the document properties that must pass
this origin check are in Table 1.1.
Because it might be desirable for a script to access variables located on a page served
from another server within the same domain, there is an exception to this security
model. By definition, it would not be possible to access and upload document proper-
ties in a frame served from http://myscripts.purejavascript.com from another
frame that was delivered from http://mydocs.purejavascript.com. Even though the
domain is the same, the complete URL is not.
To get around this minor situation, programmers can set the document.domain prop-
erty to the suffix of the current domain. This will allow them to access JavaScript prop-
erties on pages served from other servers within their domain. Following the example
in the last paragraph, using the following line in the code can enable this feature:
document.domain = “purejavascript.com”;
Setting this property will allow you to access the other sub-domains within your
domain.
03 0672321416 CH01 7/24/01 11:48 AM Page 20
Data Tainting
When JavaScript 1.1 was released in Navigator 3.0, Netscape furthered its security
implementation by using what is referred to as data tainting. In addition to the security
model in the first generation JavaScript browsers, data tainting allowed the user and
programmer to specify if they wanted scripts to access properties in other documents
from other servers. When data tainting is not enabled, which is the default, the user will
get a message saying that accessing document properties from other servers is not
allowed.
NOTE
Data tainting was only implemented in JavaScript 1.1, and because the majority of
users are now using browsers that support language versions higher than this, it is
recommended not to use this security approach. However, this section is relative to
understand some of the history of security within JavaScript, as well as answer
some questions for anyone having to create code for Navigator 3 browsers.
Users can enable tainting if they want scripts on a page to have global access to other
scripts and document properties. This is a security risk, but might be necessary within
an enterprise environment in which other security measures are in place. To enable data
tainting, environment variables must be set for the browser running the scripts. Table
1.2 shows how this can be accomplished on the various operating systems.
Table 1.2 How to Enable Data Tainting for Your Navigator Browser
Operating Environment Variable Notes
System
Windows NS_ENABLE_TAINT=1 Set this in the autoexec.bat for all
Windows systems.
UNIX NS_ENABLE_TAINT=1 Depending on which shell you are
in, you will use some form of set
env or env to set this variable.
Macintosh Remove the two This can be found by
ASCII slash (//) editing the resource with
comments before type Envi and number 128
the NS_ENABLE_TAINT in the Navigator
application itself. It
should be near the end.
OS/2 NS_ENABLE_TAINT=1 Set this in the config.sys.
After this variable is set, a number of document properties are affected. Table 1.3 shows
a list of the document objects that are tainted by default.
03 0672321416 CH01 7/24/01 11:48 AM Page 21
Security 21
TIP
As a programmer, you can test to see if the Navigator 3 user has tainting enabled
by using the navigator.taintEnabled() method. See this entry in Chapter 8,
“Client-Side” for an example of using this method.
In addition to the user having the ability to specify how he wants to handle tainting, a
programmer can specify, or taint, objects or information that cannot be passed from
one script to the next without the user’s permission. When this occurs, the browser will
pop up a dialog box that allows the user to decide whether the information can be
passed.
NOTE
For more information on data tainting, see the Client-Side JavaScript Guide on
Netscape’s DevEdge (http://developer.netscape.com) site. There is an entire
section (“Using Data Tainting in JavaScript 1.1”) in the “JavaScript Security” chap-
ter devoted to security and the concepts of data tainting.
Because data tainting did not provide the true security model JavaScript needed,
Netscape deprecated its functionality in JavaScript 1.2 and replaced it with Signed
Scripts. This is the current and most complete model that has been implemented, and
should be used by JavaScript developer’s moving forward.
Signed Scripts
Signed scripts allow a programmer the ability to gain access, after user authorization,
to restricted information. This model, which was based on the signed objects model in
03 0672321416 CH01 7/24/01 11:48 AM Page 22
Java, uses LiveConnect and the Java Capabilities API to execute its functionality. Using
this model gives programmers very defined control over what they can and cannot do
on a user’s machine.
TIP
More information on the Java Capabilities API can be found on Netscape’s
DevEdge site at http://developer.netscape.com/docs/manuals/
signedobj/capabilities.
When using this model, you have the ability to sign external JavaScript source files
(called through the src attribute of the <script> tag), event handlers, and code that is
included inline on the page. The actual signing of these scripts is implemented by using
Netscape’s Page Signer tool, which is available at http://developer.netscape.com.
This Page Signer tool allows you to build a JAR (Java Archive) file that includes the
programmer’s security certificate and code. When the browser encounters a <script>
tag that has an archive attribute set, it will go through the proper verification process
before the script is executed. This process involves popping up a Java Security dialog
box that gives the user the ability to grant or deny the rights to the script. The follow-
ing is an example of syntax used on a page that includes a signed script:
<script src=”myScripts.js” archive=”sample.jar”></script>
If the code is inline, the JAR file will contain only the programmer’s certificate. Calling
the appropriate JAR file would then resemble the following, which does not have the
src attribute, and it would have the code between the beginning and ending <script>
tags.
<script archive=”sample.jar” id=”purejs”>
// Your code here
</script>
Even though signed scripts are based on a Java model, there are enough differences in
the languages that make it a bit harder to secure JavaScript code. Unlike JavaScript, a
Java programmer can protect, make private, or make final variables and methods in
their code. This inherently protects them from hackers because these elements cannot
be accessed or changed—the Java language defines them as such.
Some expanded privileges can be accessed through the netscape.
security.PrivilegeManager.enablePrivilege() method, which gives more control
in scripting. This Java method allows a programmer to try to enable one of a set of priv-
ileges by asking the user to accept or reject his access. As with other signed scripts, this
will prompt the user to grant or deny a programmer’s request. The following list shows
the privileges that a programmer can attempt to access for these purposes:
• UniversalBrowserAccess—Allows both reading and writing of privileged data
in browser.
03 0672321416 CH01 7/24/01 11:48 AM Page 23
Advantages of JavaScript 23
Advantages of JavaScript
Up to this point, you might not have seen any big reasons where and why JavaScript
can help you. It is object based, can be interpreted within a browser, and there are secu-
rity measures in place—but the same can be said for Java. Now that browsers support
plug-ins and ActiveX controls, it is possible to design client-side functionality with
more common languages such as C++ or Visual Basic. So what does JavaScript really
give you?
For starters, it is platform independent. This is a major advantage over ActiveX con-
trols and plug-ins because they have to be recompiled and potentially rewritten for the
various platforms out there today. Previous versions of Navigator and the new Netscape
6, for example, run on many different platforms, and even though most of these are var-
ious flavors of Unix, at its core, you would still have to build a control or plug-in for
Windows 16- and 32-bit systems, MacOS, Unix, BeOS, OS/2, and the list goes on.
Also note that flavors of Unix and Linux can run on several types of processors (MIPS,
Intel, PowerPC, and so on), and Windows NT runs on Intel and Alpha machines. This
becomes quite an extensive list of components to maintain if you develop in a platform-
dependant language.
03 0672321416 CH01 7/24/01 11:48 AM Page 24
Another advantage of JavaScript is that both Netscape and Microsoft Web servers have
built-in interpreters. Both of these companies have implemented this in a different fash-
ion, but, as a Web developer, you still have the ability to use the same language on the
server-side that you do on the client-side. The only real competitor to JavaScript in this
aspect is Java with its Java applet and servlet technology.
Platform Independence
Platform independence is probably the number one reason to use JavaScript within
your applications. True, some environments interpret JavaScript a bit differently, but
the majority of the language is processed the same. The code is interpreted so that you
can write it once and let the execution environment interpret it.
This is a simple concept, but can be a big factor in deciding how to implement an appli-
cation solution. As a programmer, you do not want to have to modify code to work on
different operating systems or recompile for different microprocessors. You want to
write the code once and be done with it. You want to be able to make changes easily
and quickly without having to recompile 10 or 15 times. Let’s face it; you want and
need JavaScript.
NOTE
Remember that JScript is Microsoft’s equivalent to JavaScript.
03 0672321416 CH01 7/24/01 11:48 AM Page 25
Because of the functionality of these pages, ASP has given developers the ability to use
JScript to call server-side components (such as ActiveX controls), pass the necessary
parameters, and write the results to the screen. This allows a Web site to modularize all
the functionality of building pages with individual components that are responsible for
their specific tasks. JScript is used to handle the requests and results to and from these
modules, and then write the results to the page.
TIP
Writing the date and time to a page is a perfect item to modularize. If the code is
written as a function, it can be included easily on all your pages and called when
needed. If you are using some kind of browser intelligence on the server side, it
is possible to include this function based on the browser that is requesting the
page. If it can interpret JavaScript, make it part of the page. If it cannot, do not
include it.
A final example of using JavaScript to enhance Web pages is to produce rollover but-
tons. This usually occurs on pages in which the linked images change when a user rolls
over them. It is also possible to program in a down state when a user clicks and holds
their mouse button down on the image. Even though this is a simple enhancement, it
makes a page look and feel more professional. This effect allows a Web site to give the
user the same experience as using his favorite application, be it a Web browser, a word
processor, or a money manager.
These three implementations of JavaScript to enhance Web pages are pretty simple, but
are by no means the limit of what can be done. Many sites have used JavaScript for
advertisements, pop-up navigation windows, page redirects, and validating forms.
Because the language is executed within the browser’s environment and is often used
to complement HTML publishing, there is virtually no limit to what can be done.
TIP
If you want to use JavaScript to enhance your Web pages, don’t make the mistake
of trying to think of something cool you can do with the language. You should try
to reverse engineer it. Think of something cool for your site, and then figure out
how to implement it in JavaScript.
Interactive E-Mail
Interactive e-mail is something that has come about within e-mail applications. It
wasn’t long ago that many of these programs were only able to read text e-mails. These
programs now have the capability to render HTML e-mail within their interface, which
03 0672321416 CH01 7/24/01 11:48 AM Page 27
extends the formatting options a user can exploit. This not only improves the look and
feel of the e-mail, but it also improves the readability of it. If a user wants something
in italic, you can put it in italic.
Because HTML e-mail has become widely used in the Internet community, more and
more e-mail applications are supporting it. In addition to HTML, Netscape and
Microsoft’s most recent e-mail applications support JavaScript within the body of an
e-mail message (assuming that the user has it enabled). This makes it possible for a
user to send HTML e-mails containing JavaScript that is interpreted when the recipi-
ent reads the message.
As a programmer, you need to keep in mind that an e-mail application is not a browser.
Users are very particular about what they experience in their messages, and overuse of
JavaScript could lead to annoying your recipients. JavaScript should be used sparingly
in e-mails. It should be reserved for simple page enhancements such as image and link
rollovers or calling ads within your message. Anything beyond this could cause prob-
lems when the application interprets your scripts.
Web-Based Applications
Web-based applications are probably the most useful instances of JavaScript. They
allow a programmer to set user browser requirements, which in turn gives them a head
start on the version of JavaScript they have at their disposal. This also results in limited
exposure to browser bugs because programmers can define which browsers they sup-
port.
One of the most common uses of JavaScript within Web-based applications seems to
be in controlling forms on a page. This can be anything from checking a user’s values
before submission to dynamically adjusting the values based on user-selected data. By
implementing JavaScript at this level, a programmer is able to reduce the amount of
user error when submitting forms. No more invalid credit card numbers because one
digit too many was entered. No more usernames and passwords submitted as e-mail
addresses, and no more incomplete forms.
JavaScript is also used in more full-blown Web-based applications. These applications
are not necessarily for the common Internet user to experience, but rather are interfaces
to enterprise level applications a company might have purchased. Some of the more
common applications are used for reporting or ad delivery and management. Because
the content on the application’s pages is dynamic and always changing, a developer
usually interfaces the application with a database or system process to build the pages
on-the-fly. Using JavaScript allows developers to verify items before requests are
made, as well as add an appealing look and feel to the application.
Windows Scripting
Microsoft’s Windows Script Host comes with Windows 98, including Windows 2000,
and can be installed in Windows 95 and NT 4 systems. This scripting host is language
independent for ActiveX scripting on Windows 32-bit systems. Language independent
means that a variety of programming languages can be used in conjunction with the
03 0672321416 CH01 7/24/01 11:48 AM Page 28
host. The reason it’s mentioned in this book is that it natively supports JScript—
Microsoft’s implementation of ECMAScript.
NOTE
In addition to the JScript language, this scripting host also supports Visual Basic
Script (VBScript) as well as other third-party languages such as Perl, REXX, TCL,
and Python.
Using JScript in the scripting host allows an administrator or user to create scripts that
perform various tasks on the operating system. These can be as simple as logon scripts
or can be used to call ActiveX controls to perform more complex tasks. If you work in
the Microsoft Windows environment, you will find this implementation of JScript can
be very helpful.
TIP
For more information on the Windows Script Host, check out Microsoft’s
Developer Network site at http://msdn.microsoft.com/scripting and click
the link to Windows Script Host.
JavaScript Resources
When you program a lot in a particular language, especially one that’s Internet related,
you come across many resources. Additionally, when you program a lot in a particular
language, especially one that’s Internet related, you need many resources. So to con-
clude this introductory chapter, we have included some resources for you. There’s
everything from general information to core documentation and references to news-
groups—all on the JavaScript language and all online.
General Information
One of the most important types of resources in any given language is the general
resource. Even if a book carries comprehensive coverage of a topic, it might not have
conveyed the subject matter in a form that you understood. For this reason, you might
want to study the same topic from a different person’s perspective. Table 1.4 lists some
resources that will allow you to do this.
JavaScript Resources 29
Resource URL
JavaScript.com http://www.javascript.com
Developer.com http://developer.earthweb.com/dlink.
index-jhtml.72.1313.-.0.jhtml
Doc JavaScript http://www.webreference.com/js
The JavaScript http://www.starlingtech.com/books/
Workshop javascript
JavaScript World http://www.jsworld.com
Java/JavaScript http://www.dezines.com/dezines/
Resources on the javalinks.html
Internet
Microsoft Developer’s http://msdn.microsoft.com/scripting
Network
Timothy’s JavaScript http://www.essex1.com/people/timothy/
Examples js-index.htm
Using JavaScript and http://www.javaworld.com/javaworld/
Graphics jw-08-1996/jw-08-javascript.html
Using JavaScript’s http://www.javaworld.com/javaworld/
Built-In Objects jw-05-1996/jw-05-javascript.html
Voodoo’s Introduction http://rummelplatz.uni-mannheim.de/
to JavaScript ~skoch/js/script.htm
WebCoder.COM http://webcoder.com
Yahoo! Computers and http://dir.yahoo.com/computers_and_
Internet, Programming internet/programming_languages/
Languages, JavaScript javascript
Open Directory Top, http://dmoz.org/Computers/
Computers, Programming, Programming/Languages/JavaScript
Languages, JavaScript
Reference
Another important resource for any programmer is true reference documentation. This
documentation represents information about that language as defined by standards or
by companies who have built or implemented the language. Table 1.5 includes a list of
online resources for the various reference documents out there today.
Resource URL
Mozilla.org http://www.mozilla.org/js
Netscape’s Core http://developer.netscape.com/docs/
JavaScript 1.4 manuals/js/core/jsref/index.htm
Reference
Netscape’s Server- http://developer.netscape.com/docs/
Side JavaScript 1.2 manuals/js/server/jsref/index.htm
Reference
Netscape’s Client- http://developer. netscape.com/docs/
Side JavaScript 1.3 manuals/js/client/jsref/index.htm
Reference
Newsgroups
The final resource that we are going to discuss is the old standby—Usenet, or
Newsgroups. Newsgroups are often a very good forum to post questions about prob-
lems and see responses to issues that others are having. It’s global collaboration at its
best and often is an overlooked resource. Table 1.6 lists some of our favorites, so be
sure to check them out before giving up on any project.
Moving On
This chapter covers the overview of the JavaScript language. As you can see, JavaScript
is actually a very powerful scripting language that has many advantages. Security fea-
tures are in place, and other implementations of the language make it worth any pro-
grammer’s time to learn.
In the next chapter, you will take a look at the details of the language. Details that will
give you, the programmer, an understanding of how the language deals with operators,
data types, variables, functions, loops, conditionals, as well as how to correctly imple-
ment JavaScript within the body of an HTML document.
04 0672321416 CH02 7/24/01 11:49 AM Page 31
The Semicolon
If you have done any programming in C, C++, or Java, even as
simple as a Hello World program, you already know 75% of all
there is to know about the JavaScript semicolon (;). Just the
same as C and C++, the semicolon is placed at the end of a
JavaScript statement to signify that the code between the
beginning of the line and the semicolon should be executed
04 0672321416 CH02 7/24/01 11:49 AM Page 32
before moving to the next portion of code. If you forget a semicolon at the end of a line
in C++, you get compile errors, but JavaScript doesn’t complain. Because JavaScript is
a loosely typed language, forgetting a semicolon tells JavaScript to assume that you
intended for one to appear at the end of the line, and it executes your code accordingly.
This does not mean that you should not use semicolons! It is good programming prac-
tice to always include semicolons at the end of a line of code except when dealing with
statements such as for, while, and if.
Although it is good programming practice to have only one functional piece of code
per line, there are times when it is advantageous to put two independent pieces of code
on one line. When this case arises, you must use a semicolon to separate the two pieces
of code. In Listing 2.1, a semicolon is used to separate two independent pieces of vari-
able declaration code that are placed on one line. Notice that semicolons were placed
at the end of each line although JavaScript would do it for you. The result of executing
the code is the phrase, “The sales tax on $5 is $.3”, being displayed in the
browser.
//-->
</script>
</html>
D a t a Ty p e s a n d V a r i a b l e s 3 3
type attribute be set any time the <script> tag is used. To set the content type to the
most current version of JavaScript supported by the browser, use the format <script
type=”text/javascript”>. It is also possible to force the interpreter to use older ver-
sions of JavaScript (<script type=”text/javascript1.2”>, for example) as well as
other languages such as Microsoft’s JScript (type=”text/jscript”).
NOTE
Before HTML 4, the language attribute of the <script> tag was the only way to
set the scripting language. But as of HTML 4, the language attribute was depre-
cated in favor of the content type attribute discussed above. In order to ensure
backward compatibility, both attributes are specified in the <script> tags
throughout all the code examples in this book.
Comments
JavaScript is very generous with its commenting options by providing the /* */ com-
ment tags from C, the // comment tag from C++, and the <!-- --> tags from HTML.
Just as in C and C++, the /* */ enables comments to span multiple lines by just plac-
ing comments between the two tags. The // comment tag enables comments to be
placed between the // and the end of the line. As mentioned earlier, JavaScript pro-
vides one other comment tag that might not be familiar to you, the HTML <!-- com-
ment. JavaScript interprets this comment the same way it interprets the // characters.
You are probably asking yourself, “Why use two different comment tags that do the
same thing?” Some older browsers that did not understand the <script> tags would
display all the code between the <script> tags as standard HTML text. To prevent this
with non-JavaScript–enabled browsers, <!-- is placed on the line directly below the
<script> tag, and //--> is placed on the line directly above the closing </script> tag.
This causes non-JavaScript–enabled browsers to treat the code between the tags as
HTML comments, but allows browsers with JavaScript interpreters to execute the code.
Examples of this style of commenting can be seen in the examples throughout the
book.
NOTE
The // comment characters have to be placed in front of the HTML --> comment
closer because JavaScript will misinterpret --> as a pre-decrement operator.
Numbers
JavaScript’s approach to numbers is different from other languages because every num-
ber is treated as a floating-point number. JavaScript does support integers, octals, and
hexadecimals from a formatting perspective, but, at the lowest level, JavaScript sees
numbers as floating-point numbers. The following sections discuss different formats
that numbers can have at the higher level.
Integers
Integers are numbers that contain no fractional parts, can be positive or negative, and
can be formatted as a decimal, octal, or hexadecimal in JavaScript. Because integers
are actually floating-point numbers in JavaScript, it is possible for the numbers to be
very large.
• Decimal integers, also referred to as base 10, are probably the most common
numerical values programmers use in their code. This type of integer is made
up of numbers from 0 to 9 and cannot begin with leading zeros.
• Octal integers, also referred to as base 8, are a little different from decimal inte-
gers in that they must begin with a leading zero. Each digit following the lead-
ing zero can be 0 to 7.
• Hexadecimal integers, also referred to as base 16, must begin with 0x or 0X.
Each digit following the leading zero can be 0 through 15, but 10 through 15
are represented by the letters a (or A) through f (or F).
Floating-Point Numbers
Unlike the integer, floating-point numbers can contain fractional parts and can use
exponential notation for added precision. Floating-point numbers are made up of a dec-
imal integer followed by a period (.) and the fractional portion of the number.
Exponential notation can be used by adding an e or E to the end of a floating-point
number followed by a decimal integer that does not exceed three digits. This tells
JavaScript to multiply the floating-point number by 10 to the exponent of the number
following the e.
Built-in Values
Because computer programs are often used to solve scientific problems, the programs
must know many of the numerical constants that are used in math and science. To make
programming easier for you, JavaScript has included some of the more commonly used
numerical constants in the Math object, which are shown in Table 2.1.
D a t a Ty p e s a n d V a r i a b l e s 3 5
Special Values
JavaScript also provides some special values that are common in the mathematical
world but not so common in the computer world. These special values are available
through the Number object, as shown in Table 2.2.
Strings
Strings provide programs a voice with which to communicate. It would be inconceiv-
able to create a programming language today that did not use strings because they are
so important.
JavaScript Strings
In the world of C and C++, dealing with strings is like having to go to the dentist—
dreaded! Dealing with strings in JavaScript is like going to a big candy store. A string
is made up of any number of characters or a lack of characters. Strings are declared by
placing the characters that make up the string between a pair of double quotes (“ “) or
single quotes (‘ ‘). What if a string contains double quotes or single quotes? No prob-
lem. JavaScript interprets single quotes as part of the string if the single quotes are
inside a pair of double quotes. Likewise, double quotes are considered part of the string
if they appear between a pair of single quotes. If single quotes are your only option for
declaring a string that contains single quotes, or if double quotes must be used to
declare a string that contains double quotes, you will you need to use escape sequences
(see the next section, “Special Characters”).
Special Characters
Just as in C and C++, escape sequences, which are noted by a backslash character (\),
allow special characters that cannot normally be stored in a string to be declared. Table
2.3 lists all the possible escape characters.
04 0672321416 CH02 7/24/01 11:49 AM Page 36
Boolean
The Boolean data type is much simpler than any of the other data types because it has
only two possible values: true and false. Sometimes it is easier to think of true as on
or yes and false as off or no when working with some expressions that use the Boolean
data type. In JavaScript, true and false are often represented by 1 (true) and 0
(false).
null
JavaScript provides the keyword null for representing a condition in which there is no
value. In some languages, null and 0 are considered the same value, but JavaScript
sees null and 0 as two completely different values.
Undefined Values
At this point, you might be thinking that undefined and null are essentially the same,
but this is not true. In fact, undefined is a concept rather than a keyword like the null
data type. Undefined is equivalent to NaN for numbers, the string undefined for strings,
and false when dealing with Boolean values.
D a t a Ty p e s a n d V a r i a b l e s 3 7
program. Some languages, such as C and C++, impose many restrictions on how vari-
ables are used, but JavaScript keeps variables simple and easy to use.
Naming Variables
One of the keys to writing great code is to use variable names that help you, and pro-
grammers that modify your code, remember what data is stored in the variable. Before
beginning to think of great variable names, remember the following guidelines
imposed on variable names by JavaScript:
• The first character of the name must be a letter or an underscore (_).
• All characters following the first character can be letters, underscore, or digits.
• Letters can be either upper- or lowercase. JavaScript does distinguish between
the two cases. For example, a variable called jobTitle is different from a vari-
able called JOBtitle.
Assigning Values
When the perfect variable name has been derived, it is time to declare that variable and
assign it a value. To declare a variable, use the keyword var followed by the variable
name. Some programmers prefer to keep their code compact by declaring multiple
variables using the same var statement. When this is the case, the variable names are
separated by commas. At this point, the variable is undefined because no value has
been assigned to it. Keep in mind that undefined is a special JavaScript value.
Now that the variable is declared, a value can be assigned to it using the assignment
operator (=). In many cases, the declaration and assignment steps are performed in one
step. If a value is assigned to a variable that has not been declared using the var key-
word, JavaScript will automatically create a global variable. Listing 2.2 demonstrates
the ways variable declaration and assignment can be performed. The code displays the
sentence “James is 49 and 6 feet tall.” in the browser window.
TIP
Always use the var keyword to declare all variables to prevent variable scope prob-
lems.
Scope
A variable can be either global or local in JavaScript. All variables are global unless
they are declared in a function; in which case the variable is local to that function. It is
possible for two variables with the same name to exist if one is global and the other is
local to a function. When accessing the variable from within the function, you are
accessing the local variable. If the variable is accessed outside the function, the global
variable is used (see Listing 2.3).
CAUTION
Always use the var keyword to declare local variables in functions. Without var,
JavaScript will create a global variable.
D a t a Ty p e s a n d V a r i a b l e s 3 9
//-->
</script>
</html>
The results of running this script within the body of an HTML document can be seen
in Figure 2.1. The code begins by declaring two global variables, color and size. The
monitorSpecs() function creates a new variable called size that only exists within the
scope of the function. Because the function did not specify var, the global variable
color was changed from green to purple. In addition, a new global variable, price,
was declared within the function because the word var was not used.
Figure 2.1
The 17-inch monitor has the same color price due to the use of global variables.
Type Conversion
In languages such as C and C++, type conversion is very important and complicated,
but, in JavaScript, type conversion is effortless. Unlike other languages, JavaScript
allows a variable to hold any data type at any time. This means that a variable can be
assigned a string initially, but then could later contain a integer. JavaScript also
attempts to perform all necessary type conversions for you, such as strings to numbers
and numbers to strings.
Arrays
Arrays enable programmers to store multiple data, based on a numbered position
called an index, into one storage structure. The numbering of the index always starts at
0 and goes up. Also, JavaScript supports having arrays within arrays, called multi-
dimensional arrays.
The implementation of arrays in JavaScript has been changing ever since JavaScript
was introduced. The original implementation of arrays in JavaScript 1.0 was not really
an array at all but rather JavaScript objects with multiple property settings. A true
Array object was added in JavaScript 1.1, and additional features added in following
versions. Today, arrays are very robust and full featured, but, because of their chang-
ing past, you should spend some time digging into the history of arrays as they apply
to JavaScript versions. You will begin by understanding how arrays work in the latest
04 0672321416 CH02 7/24/01 11:50 AM Page 40
versions of JavaScript and then go back and learn how arrays were created in.
JavaScript 1.1
One-Dimensional
To create an instance of an array, you must use the new operator along with the Array
object. There are four ways to declare an array. First, an empty array that contains no
elements can be created by leaving the constructor parameters empty as shown in the
following JavaScript statement:
var x = new Array();
The second way to create an array is to fill in the constructor parameters with the array
elements. One of the nice things about JavaScript arrays is that an array can contain
elements of various types. For example, the following JavaScript statement creates an
array that contains three strings, “red”, “yellow”, and “green”, as well as the integers
1, 5, and 8:
The third way to create an array is to fill in the constructor parameter with just the size
of the array. This causes the array to be initialized to hold the number of elements spec-
ified, but does not specify the actual elements. For example, the following JavaScript
statement creates an array that can hold 6 elements.
var x = new Array(6);
NOTE
The var x = new Array(n); format, described previously, is not recognized by
JavaScript 1.2, so the number specified in the constructor parameter is stored as
an element in position 0.
The fourth, and quickest, way to create an array is to use the standard array square
brackets to fill in the array elements directly:
var x = [“red”,”yellow”,”green”,1,5,8];
After an array has been created, it can be written to and read from using the [] opera-
tor. By placing a position number in this operator, the data stored at this index can be
accessed and even overwritten.
String Indexes
So far, you have only accessed elements in arrays via the numerical index, but it is
possible to index arrays using strings. To access an element, a string index value is
placed into the [] operator. Listing 2.4 demonstrates the use of strings as indexes for a
clothing store’s product quantity array. Figure 2.2 displays the clothing store’s current
inventory of products.
04 0672321416 CH02 7/24/01 11:50 AM Page 41
D a t a Ty p e s a n d V a r i a b l e s 4 1
//-->
</script>
</html>
Figure 2.2
The clothing store’s current inventory of products is displayed using string indexes to
access arrays.
04 0672321416 CH02 7/24/01 11:50 AM Page 42
Length
Unlike arrays in C and C++, JavaScript allows the size of an array to change dynami-
cally at any time. For example, it is possible to write directly to a position that was not
even declared using the [] operator. The length of the array can also be changed by
altering the length attribute of the Array object. If the length of an array is originally
10 and is reduced to 5 by changing the value stored in the length attribute, the ele-
ments in position 5 through 9 are lost.
One of the advantages to using the Array object is the methods it provides to manipu-
late and access itself. Table 2.4 lists some of the methods that are currently available in
the Array object. Details of these methods can be found in Chapter 7, “Core
Language,” in the “Array” section.
Multidimensional
To create multidimensional arrays in JavaScript, the element of an array must be
another array. The inner array can be accessed by putting two [] operators back to
back. Listing 2.5 uses a multidimensional array to hold an inventory list of brake parts.
As seen in Figure 2.3, the brake parts list is accessed by using double [] operators and
displayed in a table.
D a t a Ty p e s a n d V a r i a b l e s 4 3
//-->
</script>
</html>
Figure 2.3
Using a multidimensional array to display the inventory list of brake parts.
Arrays as Objects
Because arrays are essentially JavaScript objects, it is possible to access the elements
of arrays as properties if a string index is used. Dot notation is used, rather than the []
operators. For example, the clothing store example, in Listing 2.4, could have been
04 0672321416 CH02 7/24/01 11:50 AM Page 44
created using properties as shown in Listing 2.6. Notice how the [] operators and dot
notation are used interchangeably when accessing the contents of the array. The result
of executing the code is the same as previously shown in Figure 2.2.
//-->
</script>
</html>
Operators 45
Because this is just a basic object, the programmer is responsible for keeping track of
the length of the array. The easiest way to remember the length is to create a property
called length. Unfortunately, properties use the same positions that are accessed by the
[] operator, so the length property would actually be array position 0.
Listing 2.7 demonstrates how to create an array representing a toolbox using the
Object() constructor. The code displays the sentence “The toolbox holds: hammer
wrench nails” in the browser window.
//-->
</script>
</html>
Operators
JavaScript provides most of the common operators that can be found in other pro-
gramming languages. Because of JavaScript’s way of handling strings, some of these
operators are a bit easier to use than in other languages.
Arithmetic
Just the same as other programming languages, JavaScript allows many arithmetic
operations. These operations include the common addition and subtraction that all pro-
grammers use as well as the less common modulus and incremental.
NOTE
All the common arithmetic operators will attempt to convert strings to numbers
when applicable. If a string cannot beconverted to a number, NaN (Not A
Number) will be returned.
04 0672321416 CH02 7/24/01 11:50 AM Page 46
Those who have programmed in other languages will find that JavaScript is very robust
in its support of operators and mathematical functions. This is not only because of the
built-in operators, but also because of the access to advanced mathematical operations
that are provided through the Math object. The functions of this object are shown in
Table 2.5 and are covered in Chapter 7.
Addition
The addition operator (+) is, of course, one of the most widely used and common oper-
ators. If the values on either side are numerical values, the values are added together.
When the values are strings, they are concatenated together. The following line of code
var resultOfAdd = 34 + 12;
would set the variable resultOfAdd equal to 46, whereas this line of code
var resultOfAdd = “a” + “corn”;
Subtraction
The subtraction operator (-) subtracts the number to the right of the operator from the
number on the left. When either of the operands are strings, an attempt is made to con-
vert the strings to numbers. For example, the following lines of code
04 0672321416 CH02 7/24/01 11:50 AM Page 47
Operators 47
convert the string stored in aNum to a number before performing the subtraction opera-
tion. The result of the subtraction (-77) is then stored in the variable resultOfSub.
Multiplication
The multiplication operator (*) works the same as it would in any other language by
multiplying the left operand by the right operand. The multiplication operator is no dif-
ferent from subtraction in its efforts to handle strings. If either of the values is a string,
an attempt is made to convert the string to a number. For example, the following lines
of code
var aNum = String(“7”);
var resultOfMult = 5 * aNum;
convert the string stored in aNum to a number before performing the multiplication
operation. The result of the multiplication (35) is then stored in the variable
resultOfMult.
Division
The division operator (/) is the operator that, although simple, can be confusing when
you have been writing code all day and your senses are dulled. You ask yourself,
“Which number divides into the other?” Reading the expression from left to right, the
left value is divided by the right value. As before, if either of the operands is a string,
an attempt is made to convert the string to a number. For example, the following lines
of code
var aNum = String(“7”);
var resultOfDiv = 42 / aNum;
convert the string stored in aNum to a number before performing the division operation.
The result of the division (6) is then stored in the variable resultOfDiv.
Modulus
Although the modulus operator (%) is not used as often as some of the other operators,
I am always excited when I do get to use it because it usually means I am performing
a neat math trick. This operator starts similar to the division operator, by dividing the
left value by the right, but, instead of returning the normal result of division, only the
remainder is returned by the operation. Once again, if either value is a string, an
attempt is made to convert the string to a number. For example, the following lines of
code
var aNum = String(“3”);
var resultOfMod = 26 % 3;
convert the string stored in aNum to a number before performing the modulus operation.
The remainder of 2 is then stored in the variable resultOfMod.
04 0672321416 CH02 7/24/01 11:50 AM Page 48
Pre-Increment
The pre-increment operator (++) combines two very common steps that programmers
use over and over again into one, thus making code more concise and readable. This
operator is especially handy when working with for loops. In your code, the pre-
increment operator is placed directly before the variable to be incremented. The oper-
ation begins by incrementing the variable by 1. The new incremented value is returned
by the operation to be used in another expression. If the variable is a string, it is con-
verted to a number. For example, the following segment of code
//The price is $5.00 dollars
var price = String(“5”);
//Add the shipping rate ($3.00 dollars) to the price after incrementing price
var pricePlusShipping = (++price) + 3;
converts the string stored in price to a number before performing the pre-increment
operation. The pre-increment operation results in the variable price being changed
from 5 to 6 dollars, and the value of 9 dollars is stored in the variable
pricePlusShipping.
Post-Increment
The post-increment operator (++) has the same operator as the pre-increment operator
but it behaves differently based on its position. First, the post-increment operator
appears directly after the variable that is to be incremented. Unlike the pre-increment
operator, the post-increment operator returns the original value before it is incremented
by 1. If either of the values is a string, an attempt is made to convert the string to a
number. For example, the following segment of code
//The price is $5.00 dollars
var price = String(“5”);
//Add the shipping rate ($3.00 dollars) to the price before incrementing price
var pricePlusShipping = (price++) + 3;
converts the string stored in price to a number before performing the post-increment
operation. The post-increment operation causes the variable price to be changed from
5 to 6 dollars but the original price of 5 dollars is added to the shipping rate resulting
in the value of 8 dollars being stored in the variable pricePlusShipping.
Pre-Decrement
The pre-decrement operator (--) is very similar to the pre-increment operator in its
placement to the left of a variable and its order of execution. But there is one key dif-
ference between the operators: the pre-decrement operator decrements the value by 1.
Once again, if the variable is a string, it is converted to a number. For example, the fol-
lowing segment of code
//The price is $20.00 dollars
var price = String(“20”);
04 0672321416 CH02 7/24/01 11:50 AM Page 49
Operators 49
//Subtracted discount ($6.00 dollars) from the price after decrementing price
var priceMinusDiscount = (--price) - 6;
converts the string stored in price to a number before performing the pre-decrement
operation. The pre-decrement operation would result in the variable price being
changed from 20 to 19 dollars, and the value of 13 dollars being stored in the variable
priceMinusDiscount.
Post-Decrement
The post-decrement operator (--) is very similar to the post-increment operator in its
placement to the right of a variable and its order of execution. But, as the name implies,
the post-decrement operator decrements the value by 1. If the variable is a string, it is
converted to a number. The following segment of code
//The price is $20.00 dollars
var price = 20
//Subtract the discount ($6.00 dollars) from the price before decrementing
price
var priceMinusDiscount = (price--) - 6;
converts the string stored in price to a number before performing the post-decrement
operation. The post-decrement operation causes the variable price to be changed from
20 to 19 dollars but the original price of 20 dollars is used to calculate the value of 14
dollars that is stored in the variable priceMinusDiscount.
Unary Negation
The unary negation operator (-) is usually used when performing a mathematical equa-
tion in which a number needs to be changed from positive to negative or vice versa.
When negating a variable, keep in mind that the contents of the variable do not change,
only the value returned is negated. As with all the other operators, if the value is a
string, an attempt is made to convert the string to a number. For example, the follow-
ing segment of code
var aNumber = String(“67”);
var resultOfNeg = -aNumber;
converts the string stored in aNumber to a number before performing the negation oper-
ation. The result of negation on the number results in the value of -67 being stored in
the variable resultOfNeg.
String
The addition operator (+) has a special purpose when dealing with strings. If the values
on either side of the addition operator are strings, the strings are concatenated together.
If only one of the values is a string, the other value is converted to a string and con-
catenated with the first value. To help understand these various combinations of apply-
ing the addition operator to numeric and string values, see Listing 2.8.
04 0672321416 CH02 7/24/01 11:50 AM Page 50
Listing 2.8 Using the Addition Operator on Numeric and String Values
<html>
<script type=”text/javascript” language=”JavaScript”>
<!--
//-->
</script>
</html>
The results of running this script within the body of an HTML document can be seen
in Figure 2.4. As the figure shows, when the addition operator is applied to two strings
or a string and a numeric value, a string concatenation occurs. As expected, when
applying this operator to the two numeric values, the numbers are added.
Figure 2.4
Using the addition operator to add numbers and concatenate strings.
Assignment
What good are variables if data cannot be assigned to them? Similar to all languages,
JavaScript provides assignment operators to allow data to be stored in variables. The
basic format of the assignment operator is shown in the following example, where a
value of 6 is assigned to the variable x:
x = 6;
04 0672321416 CH02 7/24/01 11:50 AM Page 51
Operators 51
In addition to this one-to-one assignment, this operator can also be stacked to create
simultaneous assignments. Simultaneous means that several variables can be assigned
at once. This is demonstrated in the following example, where variables x, y, and z all
contain the value of 6:
x = y = z = 6;
Anytime multiple assignment operators occur in the same expression, they are evalu-
ated from right to left. So in the previous example, z would be assigned the value 6
first. After the assignment has been made, y would be assigned the value stored in z
and, finally, x would be assigned the value stored in y. The overall effect is that all three
variables would be assigned a value of 6.
Because the assignment operator is an operator, similar to addition (+) or subtraction
(-), it can be used within an expression. This enables a programmer to perform an
assignment and evaluate a mathematical expression all in one step.
y = (x = 3) + 4;
In the preceding example, the value 3 is assigned to the variable x, which is then added
to the value 4 and assigned to the variable y. After the expression is fully evaluated, y
will contain the value 7. This enables programmers to accomplish three operations at
once. They are able to assign a value to the x variable, perform addition, and assign the
result to the y variable. Features such as this help make JavaScript very versatile and
easy to use.
Now that you have looked at how the assignment operator works, look at a more
detailed example—one that performs each of the assignments discussed, as well as
some more complex ones. Listing 2.9 contains such an example, and Figure 2.5 shows
the result.
//-->
</script>
</html>
Figure 2.5
The result of various assignment operations.
Operators 53
All the advanced assignment operators, except for +=, will attempt to convert strings to
numbers before performing the operation. If strings are used with the += operator, the
left operand is concatenated to the end of the right operand. For example, in Listing
2.10, the string “lighthouse” would be assigned to the variable y and the phrase “y=
lighthouse” is written to the browser.
// Declare a string
y = “light”;
//-->
</script>
</html>
So far, you have only considered assignment of values to variables, but what about
assigning a reference to a variable? When the assignment operator works on primitive
values (numbers, strings, Boolean, null, and undefined), a copy of the value is made.
When the assignment operator works on JavaScript objects, references to the objects
are copied. To demonstrate this difference, Listing 2.11 creates a variable and an array
to hold numbers. The variable is then copied by value to another variable, and the array
is copied by reference to another array. To show the difference, the value stored in one
of the variables and one of the arrays is changed, and then all the values are displayed
in the browser as seen in Figure 2.6.
04 0672321416 CH02 7/24/01 11:50 AM Page 54
//Assign by value
var number2 = number1;
//Assign by reference
var arrayOfNum2 = arrayOfNum1;
//-->
</script>
</html>
Figure 2.6
The variables number1 and number2 are assigned values by value, whereas the arrays
arrayOfNum1 and arrayOfNum2 are assigned values by reference.
Logical
JavaScript provides three logical operators. Without these operators, programs would
be very long and complex. At first glance, most programmers might think that they
04 0672321416 CH02 7/24/01 11:50 AM Page 55
Operators 55
already know how these operators work, but it is important to dig a little deeper. Not
knowing how the logical operators work can lead to what would appear to be random
errors that are impossible to locate and correct. So take the time to read the description
of each of the logical operators.
NOTE
JavaScript defines true as anything other than 0 (zero), “” (empty string), null,
undefined, or, of course, false.
Logical AND
The logical AND operator (&&) returns true if the expression to the left and the expres-
sion to the right of the operator evaluate to true. If either the left, right, or both expres-
sions evaluate to false, the result of the operation is false.
Unfortunately, the implementation of the logical AND operator in JavaScript is more
complex than what was just mentioned. The AND operation begins by evaluating the left
operand. If the left operand evaluates false, the basic logic of the AND operator is com-
plete, so the right operand is never evaluated. But if the left operand evaluates true, the
right operand must be evaluated to determine the final result of the AND operation. In
either case, the final result returned by the AND operation is actually the result of the last
operand to be evaluated.
Logical OR
The logical OR operator (||) returns true if the expression to the left or the expression
to the right of the operator evaluates to true. If both the left and the right expressions
evaluate to false, the result of the operation is false.
Similar to the logical AND operator, it is important that you understand how JavaScript
actually evaluates the logical OR operator. The OR operation begins by evaluating the left
operand. If the left operand evaluates true, the basic logic of the OR operator is com-
plete, so the right operand is never evaluated. But if the left operand evaluates false,
the right operand must be evaluated to determine the final result of the OR operation. In
either case, the final result returned by the OR operation is actually the result of the last
operand to be evaluated.
Logical NOT
The logical NOT operator (!) is not as complex as the comparison operators. The result
of the expression following the operator is inverted. If the expression evaluates to true,
the result of the operation is false. If the expression evaluates to false, the result is
true. When the expression evaluates to a non-Boolean value, it is converted to true or
false before performing the inversion.
Comparison
JavaScript provides the usual comparison operators found in most languages plus a
couple of more unusual ones. JavaScript had some inconsistencies in the operator
04 0672321416 CH02 7/24/01 11:50 AM Page 56
department during its early years, which resulted in the addition of some unconven-
tional comparison operators. For this reason, it is important to understand how these
operators work.
Equal
The equal operator (==) compares the value on the left of the operator to the value on
the right of the operator. If the values are equal, true is returned from the operation. If
the values are not equal, false is returned from the operation.
Originally, JavaScript attempted to convert the operands of the equality operator to the
same type before performing a comparison. For example, if the left operand of an equal
operator is a number and the right operand is a string, JavaScript would attempt to con-
vert the string to a number so that two numbers are compared. In an attempt to guess
what would be in the then unreleased ECMAScript standard, the decision was made not
to do type conversion on the operands of the equality operator in JavaScript 1.2. When
the ECMAScript standard was released, it supported type conversion, so JavaScript 1.3
came full circle by once again attempting to convert the operands of the equality oper-
ator to the same type before performing a comparison.
JavaScript determines which behavior should be used by the <script> tag. By setting
the language attribute of the <script> tag equal to JavaScript, type conversion will
be used. If the language attribute is set to “JavaScript1.2”, no type conversion will
be used. An example of this behavior is demonstrated in the Listing 2.12.
Operators 57
TIP
Avoid setting the language attribute to “JavaScript1.2” in your code because
the industry standard is for type conversion to be used on the operands of the
equality operator.
So far you’ve seen when type conversion is used with the equality operator, but you
haven’t seen how the type conversion operates. Understanding how type conversions
work for the equality operators will again save time when trying to find bugs. Type con-
version adheres to the following rules:
• True is converted to the number 1, and false is converted to zero before being
compared.
• If either of the operands are NaN, the equality operator returns false.
• null and undefined are equal.
• null and undefined are not equal to 0 (zero), “”, or false.
• If a string and a number are compared, attempt to convert the string to a num-
ber and then check for equality.
• If an object and a string are compared, attempt to convert the object to a string
and then check for equality.
• If an object and a number are compared, attempt to convert the object to a
number and then check for equality.
• If both operands of an equality operation are objects, the addresses of the two
objects are checked for equality.
Not Equal
The not equal operator (!=) compares the value on the left of the operator to the value
on the right. If the values are not equal, true is returned from operation. If they are
equal, false is returned. The != operator is victim to the same type-conversion bug as
the == operator. As with the == operator, use the language attribute of the <script> tag
to force the desired behavior.
Greater Than
The greater than operator (>) compares the value on the left of the operator to the value
on the right. If the value on the left is greater than the value on the right, true is
returned from operation. If the value on the left of the operator is less than or equal to
the value on the right, false is returned. If either of the values is a string, it is converted
to a number before the comparison takes place.
Less Than
The less than operator (<) compares the value on the left of the operator to the value on
the right. If the value on the left is less than the value on the right, true is returned from
operation. If the value on the left of the operator is greater than or equal to the value on
04 0672321416 CH02 7/24/01 11:50 AM Page 58
the right, false is returned. If either of the values is a string, it is converted to a num-
ber before the comparison takes place.
Identity
The identity operator (===), also referred to as strict equal, compares the value on the
left of the operator to the value on the right. If the value on the left is equal to the value
on the right side of the operator, true is returned from operation. If the values are not
equal, false is returned. No type conversion is performed on the operands before the
comparison.
Non-Identity
The non-identity operator (!==), also referred to as strict does-not-equal, compares the
value on the left of the operator to the value on the right. If the value on the left is not
equal to the value on the right side of the operator, true is returned from operation. If
the values are equal, false is returned. No type conversion is performed on the
operands before the comparison is made.
NOTE
The identity and non-identity operators are only available in JavaScript 1.3 and
later.
Conditional
Many programmers are not familiar with the conditional operator (?:), even though it
exists in numerous languages. Most individuals will use the standard if statement
rather than the conditional operator, even though they do the same thing. The condi-
tional operator is a little harder to read than the standard if statement, but it is much
more compact, which is important when download time is a consideration.
The format of the conditional operator can be a bit confusing. An expression that eval-
uates to a Boolean is always placed to the left of the question mark (?). If the expres-
sion evaluates to true, the value between the question mark and the colon (:) is
04 0672321416 CH02 7/24/01 11:50 AM Page 59
Operators 59
returned from the operation. If the expression evaluates to false, the value following
the colon is returned. In Listing 2.13, a standard if statement is shown, along with
same functionality produced by using the conditional operator. Figure 2.7 shows
that the same functionality is produced from both the if statement and the conditional
operator.
//Standard if statement
if (mailFlag == “YES”)
message1 = “You have email!”;
else
message1 = “No email.”;
//-->
</script>
</html>
Figure 2.7
The result of using the if statement is the same as using the conditional operator.
Bitwise
The bitwise operators look similar to the comparison operators, but their functionality
is very different. If you have ever worked with truth tables, you might recognize the
operators in this section. Bitwise operators in JavaScript only work with integers that
04 0672321416 CH02 7/24/01 11:50 AM Page 60
are 32 bits in length. If an integer is not 32 bits, it is turned into a one because the bit-
wise operators evaluate numbers at the binary level where everything is ones and zeros.
Bitwise operations are not used often in programming, but there are times when the
operators are indispensable.
Bitwise AND
The bitwise AND operator (&) looks at the integer numbers on both sides of the operator
as 32-bit binary numbers. Then the logical AND (&&) operator, discussed earlier in the
chapter, individually evaluates each of the 32 bits representing the number to the left
of the operator to the corresponding bit of the number to the right of the operator. The
32-bit binary result of logical AND operation is converted to an integer value and
returned from the bitwise AND operation.
Bitwise OR
The bitwise OR operator (|) looks at the integer numbers on both sides of the operator
as 32-bit binary numbers. Then the logical OR (||) operator, discussed earlier in the
chapter, individually evaluates each of the 32 bits representing the number to the left
of the operator to the corresponding bit of the number to the right of the operator. The
32-bit binary result of logical OR operation is converted to an integer value and returned
from the bitwise OR operation.
NOTE
An exclusive OR operation returns true if either the value to the left or the value
to the right of the operator is true, but not both. If both values are false or both
values are true, the result of the operation is false.
The exclusive OR individually evaluates each of the 32 bits representing the number to
the left of the bitwise XOR operator to the corresponding bit of the number to the right
of the operator. The 32-bit binary result of exclusive OR operation is converted to an
integer value and returned from the bitwise XOR operation.
Bitwise NOT
The bitwise NOT operator (~) is simpler than the bitwise AND, OR, and XOR operators. The
bitwise NOT operator begins by looking at the number to the right of the operator as a
32-bit binary number. Each bit of the given number is reversed so that all ones become
zeros and all zeros become ones. The 32-bit binary result is converted to an integer
value and returned from the bitwise NOT operation.
04 0672321416 CH02 7/24/01 11:50 AM Page 61
Operators 61
Shift Left
The shift left operator (<<) looks at the integer to the left of the operator as a 32-bit
binary number. All the bits in this number are shifted to the left by the number of posi-
tions specified by the integer to the right of the operator. As the bits are shifted to the
left, zeros are filled in on the right. Because the number can only be 32 bits long, the
extra bits on the left are lost. The 32-bit binary result of shifting operation is converted
to an integer value and returned from the shift left operation.
Precedence
JavaScript, similar to other languages, enables numerous operators to be used in one
expression. Because operators can appear just about anywhere within an expression,
JavaScript follows guidelines that determine which operator is evaluated first, second,
third, and so on. Table 2.7 shows the precedence of all the JavaScript operators. The
Read From… column tells what order (left-to-right or right-to-left) operators of equal
precedence are evaluated. It is possible to override the precedence of operators by using
parentheses.
TIP
Use parentheses to ensure that your code operates like you expect and to make
your code more readable.
L to R *, /, % Multiplication, divi-
sion, modulus
L to R +, - Addition, Subtraction
L to R <<, >>, >>> Bitwise shift
L to R <, <=, >, >= Relational operations
L to R ==, !=, Equality operations
===, !==
L to R & Bitwise AND
L to R ^ Bitwise XOR
L to R | Bitwise OR
L to R && Logical AND
L to R || Logical OR
R to L ?: Conditional
R to L =, *=, /=, Assignment operation
%=, +=, -=,
<<=, >>=,
>>>=, &=,
^=, |=
Lowest L to R , Multiple evaluation
Conditionals
Conditional statements enable programs to make decisions based on preset conditions
that use the operators discussed earlier in the chapter.
if
The if statement is by far the most common conditional statement simply because it is
simple and easy to use. The format of a simple if statement looks as follows:
if (expression)
statement;
the if expression, but the code is usually easier to read if the statement appears on the
next line as shown in the preceding pseudo code. If two or more lines of code are to be
executed, curly braces {} must be used to designate what code belongs in the if state-
ment.
Use the keyword else to extend the functionality of the basic if statement to provide
other alternatives if the initial statement should fail. The format of an if...else com-
bination resembles the following:
if (expression)
statement1;
else
statement2;
//Declare variables
var emptyRooms = 2; //Two people per room
var numberOfGuests = 5;
if (emptyRooms == 0)
document.write(“There are no rooms available.”);
else
{
if ((emptyRooms*2) >= numberOfGuests)
document.write(“There are enough rooms for “,numberOfGuests,” guests.”);
else
document.write(“There are not enough rooms for “);
document.write(numberOfGuests,” guests.”);
}
}
//-->
</script>
</html>
Notice how Listing 2.14 used curly brackets {} to nest an if...else structure inside
another if...else structure. Nesting gives programs more decision-making power,
but this power comes at the cost of readability.
04 0672321416 CH02 7/24/01 11:50 AM Page 64
else...if
The else...if phrase is used in place of nested if...else structures to make code
more readable. Each else...if phrase is followed by an expression enclosed in paren-
theses. Use as many else...if statements as needed. Use a final else statement to
execute code when all other conditionals evaluate to false. Listing 2.15 has the same
functionality as the code in Listing 2.14, but it uses the else...if structure. This code
displays the phrase, “There are not enough rooms for 5 guests.”.
//Declare variables
var emptyRooms = 2; //Two people per room
var numberOfGuests = 5;
if (emptyRooms == 0)
document.write(“There are no rooms available.”);
else if ((emptyRooms*2) >= numberOfGuests)
document.write(“There are enough rooms for “,numberOfGuests,” guests.”);
else
document.write(“There are not enough rooms for “,numberOfGuests,” guests.”);
//-->
</script>
</html>
switch
JavaScript offers the switch statement as an alternative to using the if...else struc-
ture. The switch statement is especially useful when testing all the possible results of
an expression. The format of a switch structure resembles the following:
switch (expression)
{
case label1:
statement1;
break;
case label2:
statement2;
break;
default:
statement3;
}
04 0672321416 CH02 7/24/01 11:50 AM Page 65
//Declare variables
var color = “green”;
//-->
switch
</script>
</html>
There are a few key points to note about the format of the switch structure in Listing
2.16. First, notice that a colon (:) always follows a label. Second, curly brackets {} are
used to hold all the case structures together, but they are not used within a case struc-
ture, even when multiple statements are to be executed. Finally, the keyword break is
used to break out of the entire switch statement after a match is found, thus prevent-
ing the default structure from being executed accidentally. The result of executing the
code in Listing 2.16 is the string “The car is green.” being displayed.
Loops
There are times when the same portion of code needs to be executed many times with
slightly different values. Use loops that run until a condition is met to create this func-
tionality.
04 0672321416 CH02 7/24/01 11:50 AM Page 66
for
The for loop is a structure that loops for a preset number of times. JavaScript uses the
C and C++ for loop structure. This particular structure is flexible, which makes this
type of loop very useful.
From a very high level, the for loop is made up of two parts: condition and statement.
The condition portion of the structure determines how many times the loop repeats,
whereas the statement executes every time the loop occurs.
The condition structure is contained within parentheses and is made up of three parts,
each separated by a semicolon (;). The first part of the condition structure initializes a
variable to a starting value. In most cases, the variable is declared within this section
as well as initialized. The second part is the actual conditional statement that deter-
mines how many times the loop will be iterated. The third and final part determines
how the variable, which was initialized in the first part, should be changed each time
the loop is iterated. This third part gives the for loop its flexibility by causing the vari-
able to be incremented, decremented, factored, or any other adjustment trick you can
devise. The format of the for loop appears as follows:
for (initialize; condition; adjust)
{
statement;
}
It is important to take time to think about how to implement for loops because it is easy
to accidentally create an infinite loop. Specifically, make sure that the conditional will
catch the adjusted variable at some point. In many cases, it is advantageous to use the
variable in the statement portion of the for loop, but take care not to adjust the vari-
able in such a way that an infinite loop is created. Listing 2.17 makes use of the for
loop to create a multiplication table as shown in Figure 2.8.
//-->
</script>
</html>
04 0672321416 CH02 7/24/01 11:50 AM Page 67
Figure 2.8
The multiplication table is created using a for loop.
while
When the for loop is too restrictive for a particular piece of code, consider using the
while loop. The while loop can do everything that the for loop can do, but not as
cleanly. So why even use the while loop? The while loop goes beyond the for loop’s
capabilities by not restricting the number of times the loop will execute.
The while loop is easy to understand if the phrase “While true, loop” is remembered.
This phrase means that while the expression in parentheses evaluates to true, execute
the statements in the loop. After the last statement in the loop is executed, go back to
the top of the loop and evaluate the expression again. When the expression evaluates to
false, the next line of code following the while loop structure is executed. To keep the
loop from executing indefinitely, a statement must be included in the loop that modi-
fies a variable in the expression. The format of the while loop resembles the follow-
ing:
while (expression)
{
statement;
}
Because the expression is evaluated before the loop, it is possible the loop will never
be executed if the expression should evaluate to false the first time. Listing 2.18 sim-
ulates an automated traffic light using the while loop.
//Declare variables
var light = “red”; //traffic light
04 0672321416 CH02 7/24/01 11:50 AM Page 68
//-->
</script>
</html>
Listing 2.18 uses two while loops to simulate an automated traffic light. The first
while loop could have just as easily been created using a for loop, but the second
while loop would have been nearly impossible to implement using a for loop. The
while loop handles this type of conditional loop with ease. In Figure 2.9, you see that
the traffic light automatically turns green when two cars are in line at the intersection.
After the two cars go through the intersection, the light turns red.
do...while
The do...while loop is simply a variation of the basic while loop that was just dis-
cussed. Other than syntax, the only difference between the do...while loop and the
while loop is that the do...while loop always executes the loop once before evaluat-
ing the expression for the first time. This difference is seen in the following format:
04 0672321416 CH02 7/24/01 11:50 AM Page 69
do
{
statement;
}
while (expression);
Figure 2.9
Simulating a traffic light using two while loops.
After the loop has executed for the first time, the expression in parentheses is evalu-
ated. If true, the loop is executed again. When the expression evaluates to false, the
next line of code following the while structure is executed. As was the case with the
while loop, a statement must be included in the loop that modifies a variable in the
expression to prevent an infinite loop. Also, notice that a semicolon (;) must be placed
after the rightmost parenthesis. Listing 2.19 is the same automated traffic light simu-
lator as shown in Listing 2.18, except do...while loops are used instead of while
loops.
//Declare variables
var light = “red”; //traffic light
var counter = 1; //create car traffic
var carsInLine = new Array(); //cars in line
//Make 5 cars go through intersection
while (counter <= 5)
{
document.write(“Car “,counter,” approaches intersection.<br>”);
carsInLine[carsInLine.length++] = counter;
04 0672321416 CH02 7/24/01 11:50 AM Page 70
//-->
</script>
</html>
The output generated from running Listing 2.19 is exactly the same as executing
Listing 2.18.
for...in
The for...in loop should not be confused with the for loop because they are quite
different. The only similarity is that both iterate through the loop a set number of times,
but this is as far as the similarity goes. The for...in loop is a special looping construct
found only in JavaScript to provide access to all the enumerated properties of a
JavaScript object. This includes elements of the Array object because they are stored
the same way that property names are stored in JavaScript object. The statement(s) in
the loop are executed for each property of an object until every property has been
04 0672321416 CH02 7/24/01 11:50 AM Page 71
accessed. Any parts of an object—such as methods and some properties—that are not
enumerated are not accessed by this looping structure. The format of the for...in loop
appears as follows:
for (variable in object)
{
statement;
}
Before the statements in the loop are executed, a property name of the object specified
to the right of the keyword in is assigned to the variable on the left side of the keyword
in. The variable would then be used within the loop code. This process will continue
until all the properties have been accessed. Unfortunately, the order in which the prop-
erties are accessed can vary, so do not assume a particular order. Listing 2.20 shows the
properties of a simple HTML button.
var aProperty;
for (aProperty in document.aForm.Big_Button)
{
document.write(aProperty,”<br>”);
}
//-->
</script>
</html>
Notice that in Figure 2.10, the name of the properties in the Big Button object, rather
than the values stored in those properties, was returned.
break
The keyword break provides a way for JavaScript to exit out of loop structures and
switch conditionals prematurely. Most of the time, the word break appears on a line
by itself, but there are times when a label will follow the keyword. When a label is
used, JavaScript completely breaks out of the area designated by label and proceeds
to the code that follows the area.
04 0672321416 CH02 7/24/01 11:50 AM Page 72
Figure 2.10
The properties of the Big Button object.
//Create outerloop
forLoop1:
for (var counter1 = 1; counter1 <= 5; counter1++)
{
//Create innerloop
for (var counter2 = 1; counter2 <= 5; counter2++)
{
//Display values in counters for both loops
document.write(“Counter1=”,counter1);
document.write(“ Counter2=”,counter2,”<br>”);
document.write(“All done!”);
//-->
</script>
</html>
Notice how the break statement with no label (see Figure 2.11) breaks out of just the
inner loop. When the break statement is used with a label, JavaScript knows at which
level to break.
Figure 2.11
Result of using labels and nested loops.
continue
Unlike the JavaScript break structure, the continue statement forces the execution of
the code to continue at the beginning of the loop. Similar to the keyword break, the
continue keyword usually appears on a line by itself, but there are times when a label
will follow the keyword. When a label is used, JavaScript immediately jumps to the
beginning of the loop designated by a label and begins executing code.
The beginning of a loop varies depending on the type of loop structure. Table 2.8
shows where each looping structure jumps when a continue structure is encountered.
CAUTION
A bug in Navigator 4 causes the expression in parentheses following the while key-
word to not get executed when jumped to using a continue statement. Instead,
execution of code starts at the top of the loop after the continue statement.
04 0672321416 CH02 7/24/01 11:50 AM Page 74
//Create outerloop
outerLoop:
for (var counter1 = 1; counter1 <= 2; counter1++)
{
document.write(“Top of outerLoop.<br>”);
//Create innerloop
innerLoop:
for (var counter2 = 1; counter2 <= 2; counter2++)
{
//Display values stored in counters of both loops
document.write(“Top of innerLoop.<br>”);
document.write(“Counter1=”,counter1,”<br>”);
document.write(“Counter2=”,counter2,”<br>”);
document.write(“All done!”);
//-->
</script>
</html>
This example is a bit complicated, so take time to compare Listing 2.22 to the output
in Figure 2.12. Notice how the phrase “Bottom of innerLoop” was not printed after
04 0672321416 CH02 7/24/01 11:50 AM Page 75
the “Continue at top of innerLoop” because code execution jumped back to begin-
ning of the innermost loop. When a label was attached to the continue keyword, code
execution jumped back to the beginning of the loop labeled outerLoop.
CAUTION
Even though JavaScript provides labels, continue statements, and break state-
ments, be careful when using these constructs because they can lead to errors that
are hard to trace if they are used improperly.
Figure 2.12
Result of using the continue statement in nested loops.
with
The object-oriented design of JavaScript quite often requires long lines of code to
access properties and methods of objects. JavaScript provides a special with statement
to help reduce the length of code needed to access these properties and methods. The
with statement works by placing the repetitive portion of the object’s path in paren-
theses after the with keyword. Now, any properties or methods used within the with
statement will automatically have the repetitive portion of the object’s path (located in
parentheses) added to the front of the string. Listing 2.23 shows how the with state-
ment can save time when resetting text fields to their default values.
//-->
</script>
</html>
In Figure 2.13, you see that the text fields contain default data that appear initially as
well as any time the Reset button is clicked. To achieve this functionality, the Reset but-
ton is connected to a function, called ResetFields(), that assigns default values to the
text fields. To reduce repetitive code, the with statement was used in setting the default
values, as seen in Listing 2.23.
Figure 2.13
Using the with statement reduces the amount of code needed to set the default text
box values.
Functions
One of the strengths of JavaScript is that it provides support for functions, which is
uncommon among scripting languages. On the other hand, JavaScript functions are
04 0672321416 CH02 7/24/01 11:50 AM Page 77
Functions 77
not as fully developed as those found in languages such as C and C++. The function-
ality that JavaScript does provide through its functions is more than enough to make
Web pages come alive.
Syntax
The syntax of JavaScript functions is very straightforward. All function declarations
must begin with the keyword function followed by the name of the function. The
name of the function is the name that will be used to call on the function within code.
Parentheses are placed after the function name to hold arguments that are to be passed
into the function. If more than one argument is to be passed into the function, use com-
mas to separate the arguments. On the other hand, if no arguments need to be passed
into the function, leave the space between the parentheses empty. Finally, curly brack-
ets are used to contain the code related to the function. Curly brackets are not optional:
They are required in JavaScript, even if the function is only made up of one line of
code.
//Declare variables
var aString = “banana”
var aNumber = 15;
//Function declaration
function test(aString, aNumber)
{
aString = “orange”;
aNumber = 124;
//Call on function
test(aString,aNumber);
//-->
</script>
</html>
In Figure 2.14, you see that the values stored in aString and aNumber appeared to be
changed while in the function test. But after exiting the function, the values reverted
back to their initial value. What actually happened was that a local copy of the vari-
ables was made for use within the function. These new variables even have the same
name as the ones that were passed into the function. After execution of the function was
completed, the local variables no longer existed, so final values displayed were of the
original variables.
Figure 2.14
Result of using call by value.
If you need to pass in a large number of arguments but do not want to assign each one
to a variable, it is possible to access the arguments as an array. To do this, leave the
area in parentheses blank and use the arguments object and the array operator [] to
access each argument. Listing 2.25 displays the arguments passed into the function
using the arguments array as shown in Figure 2.15.
04 0672321416 CH02 7/24/01 11:50 AM Page 79
Functions 79
//-->
</script>
</html>
Figure 2.15
The arguments passed into the displayArguments() function using the arguments array.
Returning Values
What if a value needs to be passed back from a function to be used later in the code?
JavaScript provides a return statement that can be used in a function to return a value
back to the statement that called the function. The value to be returned is simply placed
after the keyword return. The undefined value is returned from a function if no value
is specified after the keyword return or if the return statement is not used at all.
A value returned from a function can be assigned to a variable or used within an
expression. In Listing 2.26, the value returned from the function is used in an expres-
sion to write the phrase “3*5=15” to the browser window.
04 0672321416 CH02 7/24/01 11:50 AM Page 80
//Function declaration
function multiplyByFive(aNumber)
{
return aNumber*5;
}
//-->
</script>
</html>
Functions as Objects
The functions that have been described so far are created statically when the Web page
is loaded, but there is also a dynamic function that is not created until it is called, which
enables functions to be objects. The syntax for this type of function is very similar to
the declaration of a variable.
var varName = new Function(argument1,...,lastArgument);
The keyword Function is used to create a new function dynamically from the argu-
ments. All the arguments must be strings, and the last argument should always contain
the functionality of the function. Listing 2.27 shows a simple example of using the
Function object. Once again the phrase “3*5=15” is written to the browser window.
document.write(“3*5=”,multiplyByFive(3));
//-->
</script>
</html>
04 0672321416 CH02 7/24/01 11:50 AM Page 81
Moving On 81
Moving On
In this chapter, you were introduced to the details of the JavaScript language that are
common across many computer languages. Armed with an understanding of JavaScript
data types, variables, operators, loops, conditionals, functions, and basic syntax, which
were covered in this chapter, you could start constructing JavaScript programs right
now. But don’t you want to learn some JavaScript specific programming techniques
that will help you tap into JavaScript’s full potential? In the next chapter, we will do
just that by diving into some JavaScript programming techniques that take JavaScript
beyond just a plain computer scripting language.
04 0672321416 CH02 7/24/01 11:50 AM Page 82
05 0672321416 Part II 7/24/01 11:52 AM Page 83
PA R T I I
PROGRAMMING IN
JAVASCRIPT
3 Programming Techniques 85
4 Client-Side Scripting 107
5 JavaScript on the Server-Side 157
6 Windows Scripting 179
05 0672321416 Part II 7/24/01 11:52 AM Page 84
06 0672321416 CH03 7/24/01 11:53 AM Page 85
Programming Techniques
CHAPTER 3
Programming Techniques
In Chapter 2, “Details of the Language,” you were given a
quick overview of the core JavaScript language to show you
differences and similarities to other computer languages. Now
it is time to go to the next level by examining some of the fea-
tures of the JavaScript language and programming techniques
that will make your JavaScript programs more powerful and
more resilient to errors and maybe even make you say, “Wow,
I didn’t know JavaScript could do that!”
In this chapter we will look at pattern matching and event han-
dling and show you how to use these two pieces of JavaScript
functionality to make your JavaScript programs more power-
ful. This chapter will also examine two programming tech-
niques that will make your JavaScript programs less error
prone. You will be introduced to the try...catch block and
shown how to use it. You will also be introduced to some free
JavaScript debugging programs and techniques.
Pattern Matching
Two of the most common uses of Web pages today are for
gathering and distributing data. These two areas, by nature, use
data manipulation to understand what the user needs and then
return information tailored to the user’s specifications. One of
the key tools for processing data is pattern matching. Some
scripting languages, such as Perl, are well suited to handle pat-
tern matching, whereas others provide very little pattern
matching capabilities. If you are familiar with Perl, you will
probably recognize JavaScript pattern matching because it was
based on Perl’s implementation of pattern matching. The
implementation of pattern matching into JavaScript greatly
aids in the processing of data for the Internet.
06 0672321416 CH03 7/24/01 11:53 AM Page 86
8 6 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
JavaScript uses the RegExp (short for Regular Expression) object to handle pattern
matching. This object holds the pattern definition, as well as provides methods for per-
forming matching. You’ll begin by learning how to define patterns and then by learn-
ing how to use the RegExp objects to test for pattern matches.
This notation creates a new RegExp object called lastName and assigns the pattern
Jones. The same functionality could have been accomplished by using a direct assign-
ment:
var lastName = /Jones/;
To differentiate this notation from that used to define strings, the forward slash char-
acter (/) is used to designate the beginning and end of the pattern. Notice that forward
slashes were not needed in the RegExp() constructor because this could be distin-
guished from the String() constructor.
Defining Patterns
The syntax used to define patterns in JavaScript could be considered a scripting lan-
guage in itself because it is so extensive. There are special characters for creating
almost any pattern one could imagine, including characters for handling groups, repe-
tition, position, and so on. Table 3.1 shows the special pattern matching characters
available in JavaScript.
Pattern Matching 87
Character Description
{x,} Matches the previous item at least x times.
{x} Matches the previous item exactly x times.
? Matches the previous item once or not at all.
+ Matches the previous item at least once.
* Matches the previous item any number of times or not at
all.
| Matches the expression to the left or the right of the |
character.
(...) Groups everything inside parentheses into a subpattern.
\x Matches the same characters that resulted from the sub-
pattern in group number x. Groups, which are designated
with parentheses, are numbered from left to right.
^ Matches the beginning of the string or beginning of a
line, in multiline matches.
$ Matches the end of the string or end of a line, in multiline
matches.
\b Matches the position between a word character and a
non-word character.
\B Matches the position that is not between a word charac-
ter and a non-word character.
These special pattern matching characters are used within the pattern to aid in defining
complex patterns. Looking at Table 3.1, you might notice that characters such as the
asterisk (*), plus sign (+), and backslash (\) hold special meanings that would keep
them from being used as a literal. For example, what if you wanted to find all the plus
signs (+) in a string? To use a literal plus sign, a backslash (\) must precede the sign.
Table 3.2 shows all the characters that require a backslash character to be taken liter-
ally within a pattern.
8 8 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
There is one final piece of syntax that JavaScript provides for creating patterns. Unlike
the syntax covered so far, these pieces of syntax appear outside the forward slashes that
define the pattern. These attributes are shown in Table 3.3.
The pattern matching methods in the RegExp object require String objects, as shown
in Table 3.5.
06 0672321416 CH03 7/24/01 11:53 AM Page 89
Listing 3.1 uses the RegExp constructor, special pattern syntax, and the String
replace() method to replace digits 3 to 5 that exist in the string with nines as seen in
Figure 3.1.
document.write(str);
document.write(“Replace digits 3 to 5 with nines.<br>”);
document.write(str.replace(span3to5,”9”));
//-->
</script>
</html>
Figure 3.1
The digits 3 to 5 are replaced with nines.
9 0 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
within your browser that you never see and never need to worry about. But there are
times when you really want to do something in your code when an event takes place.
For example, consider a Web page that provides users with an interface to change their
password on some computer system. The Web page has a text box for the username and
a text box for the new password as well as a button to submit the new password infor-
mation. Before the username and password get submitted to some other system, you
want to intercept the event that occurs when the user clicks the Submit button and ver-
ify that the password adheres to some specific password rules. A password rule might
state that passwords must be greater than three characters in length but less than 15
characters. By having access to events that take place behind the scenes of the browser,
you can cancel the submit action and alert the user to the problem with the password
she entered.
In this section you will see the types of browser events that JavaScript will let you inter-
cept and how to capture and take action based on those events.
Events
Many different types of events take place in browsers. JavaScript provides access to a
number of events that would be useful to you, such as the click event, which occurs
when the left mouse button is pressed once. Most of the events correspond to an HTML
element that a user can see and manipulate such as a button or a check box. Table 3.6
contains a list of events that can be captured by JavaScript and the JavaScript object
with which the event is associated.
Of the events covered in the previous table, the Error and Abort events deserve a lit-
tle more explanation because they are not as straightforward as the rest.
The Error event is used by the Window and Image objects to indicate that an error
occurred while either loading an HTML page or loading an image. This type of error
will result in the browser issuing a JavaScript syntax error or a runtime error.
The Abort event is used by the Image object to indicate that the loading of an image
was aborted. This type of event occurs often because users become impatient waiting
for a large image to load, so they stop the image load before it completes by clicking
the browser’s Stop button or clicking a link to another page.
06 0672321416 CH03 7/24/01 11:53 AM Page 92
9 2 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
Event Handlers
Now that you know the types of events that JavaScript provides, access to them is just
a matter of capturing those events. Events are captured using event handlers. By assign-
ing a function or a single line of JavaScript code to an object’s event handler, you can
capture an event and take action. Table 3.7 shows all the event handlers and the events
they are associated with.
Capturing Events
Event handlers can be defined in one of two ways. The first and most common way is
to define the handler inside HTML tags much in the same way HTML tag properties
are assigned. For example, to display an alert box when a button is clicked, simply
assign a JavaScript alert box to the onClick event handler inside the button’s HTML
tag as follows:
<form name=”myForm”>
<input
type=”button”
name=”myButton”
06 0672321416 CH03 7/24/01 11:53 AM Page 93
value=”Press Me”
onClick=”alert(‘myButton was pressed’)”>
</form>
Anytime myButton is clicked an alert box will be displayed that tells the user that
“myButton was pressed”. Remember that not all events are associated with every
object. To see what events and event handlers are available to a particular object, look
for the object in Chapter 8, “Client-Side.”
The second way to define event handlers is to define the handler inside JavaScript code
using dot notation. Listing 3.2 demonstrates how to assign a JavaScript alert box to the
onClick event handler using dot notation.
In listing 3.2 myButton was initially created using standard HTML tags. Directly after
creating the button JavaScript dot notation is used to access the button object and
assign an alert box to the onclick handler.
NOTE
Notice that in Listing 3.2 the onclick property was written using a lowercase c
rather than an uppercase C as was used when accessing the onClick property via
the HTML input tag. This is not a typo! When defining event handlers inside HTML,
use the uppercase characters as shown in Table 3.7. When defining event handlers
inside JavaScript code using dot notation, the event handlers must not contain any
uppercase characters.
Canceling Events
One of the most common uses of event handlers is validation of data entered through
an HTML form. For example you might want to verify that a password entered by a
user in a password change form is valid before submitting the form to the server. If the
password entered by the user is not valid, the user should be notified of the problem
and the form should not be submitted. Utilizing the material covered so far, it is easy
to capture the Click event of the form’s submit button and alert the user of the prob-
lems with the password entered. But how do you prevent the event from continuing and
06 0672321416 CH03 7/24/01 11:53 AM Page 94
9 4 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
the form from being submitted to the server? The Submit event can be canceled by sim-
ply returning false in the event handling routine. Listing 3.3 demonstrates how to can-
cel the form submission.
function validatePassword()
{
passwd = document.passwordForm.password.value;
//-->
</script>
<center>
<h1>Password Change Page</h1>
Please enter your user name and new password.<br>
(Password must be between 3 and 15 characters.)<br><br>
<form name=”passwordForm”
action=”success.html”
onSubmit=”return validatePassword()”>
Username: <input type=”text” name=”username”><br>
Password: <input type=”password” name=”password”><br>
<input type=”submit”>
</form>
</html>
Not all the event handlers allow you to stop an event from taking place, but some do.
Of the events that can be stopped, the value used to stop the event varies. Table 3.8
shows the events that acknowledge return codes and what values to return to cancel the
event.
Timers
Even though JavaScript does not directly provide an event-driven timer, we will discuss
timers in this section because timers should generally be thought of in terms of events.
Because JavaScript does not directly provide a timer, it is possible to use the Window
object’s setInterval() method to serve the same purpose.
NOTE
The setInterval() method is supported in JavaScript 1.2 and higher.
9 6 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
//-->
</script>
</html>
As mentioned earlier the setInterval() method is only available in JavaScript 1.2 and
higher. If you need to support an earlier version of JavaScript, you will have to use the
setTimeout() method.
//-->
</script>
</html>
06 0672321416 CH03 7/24/01 11:53 AM Page 97
Exceptions 97
Exceptions
As of JavaScript 1.4 exception handling has been added to allow you to capture and
handle exceptions that occur in your JavaScript programs. The syntax that was chosen
was the typical try...catch, throw, and finally statements that are found in other
languages such as Java and C++. With these statements you can now throw your own
errors, cleanly capture errors, and take the appropriate action based on the error thrown.
throw
The throw statement allows you to throw your own errors to be captured by the
try...catch statement. The actual error that you throw can be any type of object so
long as the try...catch statement knows how to handle the object. For example an
error could be a number, string, or even a user-defined object that contains a number
and an array of strings. The format of the throw statement resembles the following:
throw error
try...catch
The try...catch statement marks a block of code to try and a block of code to catch
errors if an exception should be thrown. The format of the try...catch statement
resembles the following:
try
{
code
}
catch (error)
{
code
}
The try block consists of one or more lines of code enclosed by brackets just below
the try statement, whereas the catch block consists of one or more lines of code
enclosed by brackets just below the catch statement. The catch block can also be
passed the actual error that was thrown by specifying an object to hold the error in
parentheses. This error object can then be used within the catch block. The error object
and parentheses are optional and are only needed if you intended to access the actual
error thrown from the catch block.
If an exception is thrown in the try block or within a function called by a statement in
the try block using the throw statement, the code in the catch block is executed imme-
diately to handle the error exception that was just thrown. If no exception is thrown
while the try block is executed, the catch block is skipped.
NOTE
The try...catch statement can be nested to provide even more error handling.
06 0672321416 CH03 7/24/01 11:53 AM Page 98
9 8 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
In Listing 3.6, the try...catch and throw statements are used to help validate pass-
words in a simple password validation program. If a password is less than 5 characters
in length or greater than 10, the user is presented with an error message thanks to the
try...catch block.
function ValidatePassword(password)
{
try
{
//Make sure password has at least 5 characters
if(password.length < 5 )
{
throw “SHORT”;
}
//Password ok
alert(“Password Validated!”);
}
catch(e)
{
if(e == “SHORT”)
{
alert(“Not enough characters in password!”);
}
if(e == “LONG”)
{
alert(“Password contains too many characters!”);
}
}
}
//-->
</script>
<h2>Password Validator</h2>
<form name=”myform”>
Please enter password: <input type=”password” name=”password”><br><br>
06 0672321416 CH03 7/24/01 11:53 AM Page 99
Exceptions 99
</html>
Runtime Errors
In addition to capturing user-defined errors, the try...catch block can also capture
runtime errors that JavaScript throws without the assistance of the throw statement.
You can capture these errors using the try...catch block much as you would capture
your own user-created errors. The ECMA-262 (Third edition) standard defines six
types of error objects that can be thrown by JavaScript. These errors are shown in Table
3.9 with a short description of the type of error they represent.
When a runtime error occurs, an Error object is returned. To determine the type of
error, simply access the name property. Listing 3.7 purposely creates a runtime error by
trying to use an undefined variable. The catch block determines the type error and dis-
plays an error message to the user.
1 0 0 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
finally
The finally block is an optional block of code that is executed each time an excep-
tion is thrown. This is especially useful in languages that work with files in which a file
handle must be properly closed whether or not an error occurred. In the event that no
error occurs, the code in the finally block is executed after the try...catch block but
before the code following the try...catch block is executed. When an error is thrown,
the finally block executes after the try...catch block. The format of the
try...catch block plus the finally block looks as follows:
try
{
code
}
catch (error)
{
code
}
finally
{
code
}
In Listing 3.8, the finally statement ensures that the password field is cleared whether
or not the password is valid. If the password field had been cleared below the finally
box, the field would only get cleared if the password was valid because there is a
return statement in the catch block. If the password field had been cleared inside the
catch box, the field would only get cleared if an error was thrown. Because the pass-
word field needed to be cleared regardless of errors, the finally block was used.
function ValidatePassword(password)
{
try
{
//Make sure password has at least 5 characters
if(password.length < 5 )
06 0672321416 CH03 7/24/01 11:53 AM Page 101
Debugging 101
{
throw “SHORT”;
}
//Password ok
alert(“Password Ok!”);
}
//-->
</script>
<h2>Password Validator</h2>
<form name=”myform”>
Please enter password: <input type=”password” name=”password”><br><br>
<input type=button
name=”validate”
value=”Validate!”
onClick=”ValidatePassword(myform.password.value)”>
</form>
</html>
Debugging
If you are used to doing programming in languages such as C++ and Java, you are
probably accustomed to using some type of debugging tool to help you locate and fix
06 0672321416 CH03 7/24/01 11:53 AM Page 102
1 0 2 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
problems in your code. Now that JavaScript is finding its place in the coding commu-
nity, we are finally seeing support of a native and comprehensive third-party scripting
and debugging environment that is similar to those found in mature programming lan-
guages (such as C++, Visual Basic, and Java).
JavaScript scripting and debugging tools help the developers take advantage of more
automated preventive and, to a lesser extent, corrective controls. If you do not have
access to JavaScript debugging tools, or the debugging job is very small, a simple
JavaScript alert box can work as a debugging tool. In this chapter, you will examine
two free JavaScript debugging options that are at your disposal.
Features
The following are the main features of the Microsoft Script Debugger:
• Dynamic view of HTML structure
• JavaScript, VBScript, and Java can be debugged seamlessly within the same
document.
• Code is color coded
• Ability to set breakpoints
• Can step over, through, and out of each line of code
• Call stack
• Immediate expression window
Tips
The MSSD is easy to use, but there are a few things to know that will have you debug-
ging your code quicker in MSSD.
Starting the Debugger
The only way to start MSSD is to first open Internet Explorer and load the desired
HTML source file. Then you can activate MSSD by choosing View, Source.
NOTE
If MSSD isn’t installed, viewing the source will open the source file in the Notepad
editor.
06 0672321416 CH03 7/24/01 11:53 AM Page 103
Debugging 103
To start the debugging process, choose Edit, Break at Next Statement from Internet
Explorer, or choose Debug, Break at Next Statement from MSSD, and execute the
script. This starts the debugger and stops it at the first statement in the current script.
The Break at Next Command
The Break at Next Statement command (which appears on the Script Debugger option
of the View menu of Internet Explorer and the Debug menu of MSSD) is similar to a
step command, in that the debugger executes the next statement in the script and then
breaks, except that you can also use it when you are not currently running the script.
This is an important debugging feature of MSSD because a lot of JavaScript code is
commonly declared in the header (or <head> tag) section of an HTML file, and this
command is the only way to debug that code. This is because the code in the header of
the file has already been executed by the time the HTML file is loaded. Also, any
breakpoints set after the HTML file has been loaded are lost if you reload the page.
Evaluating Expressions
An expression can be evaluated with the aid of MSSD’s immediate window and the fol-
lowing two methods:
• Debug.write(string)—This method writes a specified string, which is often
the value of a variable, to the immediate window with no intervening spaces or
characters between each string.
• Debug.writeln([string])—This method is identical to the preceding method,
except that a newline character is inserted after each string. Also, the string
argument is optional. If it’s omitted, only a newline character is written to the
immediate window.
1 0 4 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
important variables at various stages of your program’s execution. By doing so, you
can determine if your code is executing as you intended. This technique is especially
useful when you cannot get your hands on a full-featured JavaScript debugger, or you
are short on time and don’t want to fire up a JavaScript debugger to solve a simple func-
tionality problem. JavaScript has a handy method called alert() that lends itself well
to stopping the execution of your script to see a value of a variable. With a little thought
and proper placement of this method, you can quickly track down functionality prob-
lems in scripts.
Listing 3.9 contains some JavaScript code that is supposed to set the color and type of
a car. One look at the result, as seen in Figure 3.2, and you can see something went
wrong. The script was supposed to set the vehicle type to “car” with the setType()
function and the vehicle color to “red” with the setColor() function. If these two
functions had worked properly, a string would be written to the screen; otherwise, an
alert message would be displayed to let you know that one of the assignment opera-
tions failed. No alert message was displayed, but the variable representing the vehicle’s
color was never set to ”red”.
//If the vehicle type and color were not properly set alert the user.
if(setType() || setColor())
{
document.write(“The “ + vehicleType + “ is “ + vehicleColor);
}
else
alert(“The vehicle type and color could not be set”);
</script>
</html>
06 0672321416 CH03 7/24/01 11:53 AM Page 105
Debugging 105
Figure 3.2
There is a problem associated with setting the color of the car.
In Listing 3.10, alert() methods are used to debug the code. An alert() method is
placed in each of the variable-setting functions to determine if each function is being
executed. More alert() methods are placed before and after the if statement to show
how the conditional evaluates.
//Debug statement
alert(“Before if statement: type=”+vehicleType+” color=”+vehicleColor);
//If the vehicle type and color were not properly set alert the user.
if(setType() || setColor())
{
//Debug statement
alert(“After if statement: type=”+vehicleType+” color=”+vehicleColor);
1 0 6 C h a p t e r 3 : P r o g r a m m i n g Te c h n i q u e s
</script>
</html>
When Listing 3.10 is executed, the first alert box displayed shows that both variables
are undefined before the execution of the if statement. The next alert box shows that
the setType() function was executed. The final alert box shows the vehicle type set to
“car”, but the color is still undefined after the if statement, as you can see in Figure
3.3. What happened to the setColor() function? The alert() method in the
setColor() function was never executed, which lets us know that the setColor()
function was never called from within the if statement.
Figure 3.3
Debugging using the alert() method.
If the first argument in a logical OR operation evaluates to true, the second argument
is never evaluated. Because the setType() function returned true, the setColor()
function was never executed. The problem is easily corrected by simply changing the
logical OR operator to a logical AND operator.
CAUTION
After your code checks out, don’t forget to remove the alert() methods that
you added for debugging or else your program will display these alerts to those
who use your scripts.
Moving On
In this chapter, you were introduced to some programming techniques that will make
your JavaScript programs more powerful and more resilient through the use of
JavaScript pattern matching, event handling, exception handling, and debugging. Part
II, “Programming in JavaScript,” provides a look at the environments in which
JavaScript can be interpreted and into the actual use of the language.
07 0672321416 CH04 7/24/01 11:54 AM Page 107
Client-Side Scripting
CHAPTER 4
Client-Side Scripting
The first three chapters of this book introduced you to
JavaScript, exposed you to its semantics, and covered several
programming techniques to help you get started. In Part II,
“Programming in JavaScript,” we are going to cover the envi-
ronments in which JavaScript is interpreted, including the
client-side, server-side, and in the Windows Script Host envi-
ronment.
In this chapter specifically, you will look at several aspects of
the language. We’ll look at how the browsers interpret
JavaScript, how to deal with some of the issues that surround
browsers, and how they handle the scripts—issues such as
bugs and differences in functionality.
Later, you will look at how JavaScript can extend a browser’s
functionality. This is accomplished with some of its object
arrays and through the use of LiveConnect—the Java to
JavaScript bridge. We will also cover tasks that will allow you
to process form data and without having to send pages back
and forth to the server. Cookies, another key component, will
also be covered in this chapter.
The next topic we will discuss is Window manipulation.
Windows appear to be very basic on the outside, but the under-
lying JavaScript provides a lot of power for configuring and
manipulating windows to meet your design needs.
This chapter will also include coverage of the dynamic posi-
tioning of HTML and XHTML elements and their manipula-
tion using JavaScript. Finally, the chapter will take a look into
XUL—the XML-Based User Interface Language, which is a
new language created by our friends at Mozilla.org and used to
build the user interface for the Netscape 6 and Mozilla
browsers.
07 0672321416 CH04 7/24/01 11:54 AM Page 108
This chapter has a lot of material in it, so lets get started by talking about which
browsers support JavaScript and some of their issues.
NOTE
Because many users use AOL’s online service to connect to the Internet, you should
know that the AOL browser is actually an Internet Explorer browser with different
“chrome.”
For those of you familiar with Java, you know that various JVMs, or Java Virtual
Machines, can interpret the language differently. JavaScript is similar, except that the
market can often be considered more fragmented. For the most part, browsers do inter-
pret JavaScript the same—at least the core language semantics. The big distinction is
that they all have different version support as well as diverse bugs.
To give you an idea of the versions and support among these browsers, take a look at
Table 4.1. It breaks down these runtime environments by browser version and language
version.
NOTE
Opera has done an excellent job of keeping up with standards in its browsers;
however, understanding what it supports exactly can be a bit confusing. Table 4.1
is a rough idea of their support, but for more information we recommend that you
visit http://www.opera.com/opera4/specs.html#ecmascript for version 4
information and http://www.opera.com/opera5/specs.html#ecmascript for
version 5.
J AVA S C R I P T 1 . 1 I N N AV I G AT O R 2 . 0 2 F O R O S / 2 ?
If you take a second look at Table 4.1, you will notice that the 2.02 version of
Navigator for OS/2 is JavaScript 1.1–compliant. This is because the OS/2 versions of
the Navigator browsers were co-developed by engineers from both Netscape and
IBM.
The OS/2 version of Navigator was not announced or in beta until the 3.0 version
of the browser was already released. Those of you who used the 3.0 browsers
heavily might have noticed that they seemed more buggy than the 2.0 versions.
Added enhancements seemed to make the code more unstable, which prompted
the OS/2 version using the more stable 2.0 interface to be built, but included the
3.0 backend.
Because browser versions are often determined using JavaScript, an OS/2 user with
Navigator 2.02 can start the browser with the “-3” option that will tell its user
agent string to report that it is a 3.0 browser rather than a 2.02. Because it has the
capability to interpret all the JavaScript on the page, this option allows the user to
experience all the enhancements for the 3.0 browsers.
These facts are important for programmers to properly implement features in their
scripts. You can now check the Navigator 2.02 for OS/2 browser and know that it
is JavaScript 1.1–compliant—with or without the -3 option. All of this, of course,
was remedied with the release of Netscape Communicator 4.61 for OS/2, which
has support for JavaScript 1.3.
New browsers are released a couple of times a year, which forces the market to become
fragmented in terms of the JavaScript runtime environment with which users will be
accessing a site. Extra care needs to be taken in writing scripts so browsers will inter-
pret them correctly. As discussed in Chapter 2, “Details of the Language,” most of the
version control can be accomplished using the language or type attribute of the
<script> element, but not all browsers correctly implement this. As a programmer,
you will have to write in code to accommodate these browsers.
The first browser you are going to look at is Netscape’s Navigator browser. It was the
pioneering browser that first interpreted the language co-developed by Sun and
Netscape. We will also look at Internet Explorer, Opera, and HotJava as well.
07 0672321416 CH04 7/24/01 11:54 AM Page 110
Netscape Navigator
Netscape Navigator (see Netscape 6.0 in Figure 4.1) first included its support for
JavaScript in its version 2 browsers. This was a major step for JavaScript because
Navigator was by far the most widely used browser in the world. Web developers could
add scripts to their pages and feel very confident that the majority of their visitors
would be able to experience their enhancements. And things have not stopped there.
Recently, Netscape released version 6 of its browser, which was a complete rewrite and
is shown in Figure 4.1, from the ground up. This time, its support for official standards
has been relatively unmatched. It has even gone so far as to not support old elements
and tags that were implemented in Navigator 4, which provides its own problems, but
reflects Netscape’s dedication to standardization.
Figure 4.1
Netscape 6 browser.
Similar to anything else Netscape has implemented in its browsers, it has continued to
expand the language and add to it. With each major release, new functionality through
standards support have been added that keep it ahead of other browsers. Table 4.2 out-
lines the JavaScript support in these browsers and gives you some additional
information.
TIP
Netscape’s DevEdge site has more information on JavaScript bugs. It can be
accessed at http://developer.netscape.com/tech/javascript/index.html,
and then follow the link for Known Bugs.
Internet Explorer
Even though Internet Explorer (see version 5.5 in Figure 4.2) was the second browser
to follow suit in its support of JavaScript, it seems to have avoided the Navigator prob-
lems just discussed. However, JScript does have issues that inhibit its performance and
functionality as well.
Because Microsoft did not want to purchase the licensing to JavaScript from Netscape
to implement in its Internet Explorer browser, it had to reverse-engineer the scripting
language and give it a new name. This led to the birth of JScript.
In the short run, this seemed like a bad thing for JavaScript programmers. Now that two
versions of the language were on the market, how could programmers be assured that
their scripts would work in both browsers? Luckily, this version incompatibility only
lasted for version 3 of Internet Explorer. By the time version 4 of the browser came out,
the first edition of the ECMAScript standard was well on its way to adoption, and
Microsoft based its JScript 3.0 on the standard. This refocused and aligned both
JavaScript and JScript and reduced the problems of incompatibility between them.
There are, however, a few quick things to watch for in the older versions of the browser:
07 0672321416 CH04 7/24/01 11:54 AM Page 112
• Microsoft provides the ability for users to update their scripting engines with-
out updating the browser. It also distributes different engines with minor
updates to the browser.
• No support for the Image object on the Windows platform in version 3 of the
browser.
• Support for the src attribute of the <script> tag was implemented in the 3.02
maintenance release of Internet Explorer and did not fully work.
Figure 4.2
Internet Explorer 5.5 browser.
NOTE
Microsoft refers to its interpreter as a JScript Scripting Engine. This terminology
will be used in this section.
Table 4.3 breaks down the browsers that have been released by Microsoft and its
JScript support by version. The table also includes some notes that give more infor-
mation about what the release added to the language.
There is another topic that we want to discuss here, which is the user’s ability to update
his scripting engine without having to update his browser. This makes it very possible
for a user to implement an Internet Explorer 5.0 browser that has the 5.5. JScript
engine.
One good thing is that the more recent versions of the engines have functions to allow
developers to determine what version of the engine users are running. Watch out
because using some of these functions on version 3.0 engines causes errors. Luckily,
version 3 is few and far between at this point, so it puts developers at less of an impos-
sible situation.
Listing 4.1 includes the Microsoft-specific elements that a developer can use to deter-
mine the version of the scripting engine the user has.
TIP
In case you are wondering, the scripting engine for JScript is contained in the
jscript.dll. You can check the properties in this DLL file to see what version you
have on your machine.
The result of opening Listing 4.1 in Internet Explorer 5.5 on Windows is shown in
Figure 4.3. As you can see, this can be very helpful if developers need to know the spe-
cific build the user implements when executing his scripts. However, you should be
careful to avoid versions that do not support these elements.
Figure 4.3
Internet Explorer 5.5 displaying its scripting engine information.
Opera
The Opera browser (see version 5.0 in Figure 4.4) has received a lot of press because
of its support for standards, such as cascading style sheets (CSS). The developers at
Opera Software have taken on the responsibility of providing a lot of functionality to
their users without a lot of unneeded flash. Opera is mostly a pure rendering engine,
but it does have support for Navigator plug-ins and Java. This allows its users to gain
the needed support to position it as a real alternative.
The main thing you will want to watch out for in Opera browsers is the user agent
string—it has the ability for users to select the string sent. This was included to allow
the Opera browser to access pages built for Navigator 4, or perhaps Internet Explorer
5, which can make it tricky for JavaScript programmers to accurately detect the
browser version.
07 0672321416 CH04 7/24/01 11:54 AM Page 115
Figure 4.4
The Opera 5.0 browser is available at http://www.opera.com.
HotJava
The final browser that we are going to mention is Sun’s HotJava browser, which
included support for JavaScript in version 3.0. It uses the Rhino implementation
(JavaScript engine written in Java) from Mozilla.org for its interpretation and is the
only browser that was officially released that supported JavaScript 1.4. To be honest,
this browser is rarely used and has not been updated in over a year, but we did want to
mention it.
Applet Array
The applet array stores references to all the Java applets loaded on a page. This allows
a developer to retrieve the total number of applets on a page and to directly interact
with them. If the developer is using LiveConnect to interact with the applet, the applet
itself can be referenced by its indexed location. The second applet, for instance, could
have its information accessed by the following JavaScript code:
var myAppletInfo = document.applets[1];
This allows developers to store information about this applet in a variable, where they
can then parse it and process the information about the applet. The information stored
in the myAppletInfo example would contain the applet’s name, dimensions, and the
layout package used to create the applet.
With the increased use of Web-based, enterprise-level applications, it is not uncommon
for a developer not to know how many applets are on a page. Pages are built dynami-
cally depending on the type of request by the user, and the resulting page might depend
completely on the number of items the user selected to view. Because this number can
vary, a developer might have to include JavaScript code that analyzes the page to see
how many applets are on it. Listing 4.2 shows an example of this.
Listing 4.2 Checking for Java Applets with the length Property of the
Applet Array
<html>
<head>
<title>Checking for Java Applets</title>
<script language=”JavaScript1.1” type=”text/javascript”>
<!--
function checkApplets(){
<body onLoad=’checkApplets()’>
<center>
<table border=”1”>
<tr>
<td>
<applet code=”TestApplet”
codebase=”.”
width=”200”
height=”35”
name=”AppletOne”
mayscript>
This browser is not able to run Java applets
<param name=”clickurl”
value=”http://www.purejavascript.com/cgi-bin/redirect.cgi”>
</applet>
</td>
</tr>
<tr>
<td>
<applet code=”TestApplet”
codebase=”.”
width=”200”
height=”35”
name=”AppletTwo”>
This browser is not able to run Java applets
<param name=”clickurl”
value=”http://www.purejavascript.com/cgi-bin/redirect2.cgi”>
</applet>
</td>
</tr>
</table>
</center>
</body>
</html>
07 0672321416 CH04 7/24/01 11:55 AM Page 118
As you can see in Listing 4.2, after the page has fully loaded, an onLoad event handler
is called by the <body> tag. This event triggers a function that checks to see how many
applets were loaded on the page. Depending on the number of applets loaded, the
browser might be redirected to another location. If the number of applets on the page
is two, the page does not redirect to another location.
NOTE
You are only able to access properties and the results of applet methods after the
applet is fully loaded and running. To ensure this, use the onLoad event handler in
the <body> tag. Note that there are bugs in certain platforms of Navigator
browsers that incorrectly fire this event. Be sure to account for these instances.
As you can see, the applet array can be a very helpful resource in accessing the applets
on your pages. You should use it with caution, however, because not all browsers that
support JavaScript support the ability to run applets.
Plug-In Array
The plug-in array is the second array that can be used to control elements loaded by an
HTML page. Developers commonly determine whether a particular plug-in is installed
on the user’s machine by using this array. When this has been determined, the devel-
oper can then make the appropriate decisions about whether to try and load the plug-
in.
The actual plug-in array has several properties that can be used to retrieve this infor-
mation. These include items such as the name of the plug-in, the actual filename, and
a description. Listing 4.3 demonstrates the use of the plug-in array by writing the infor-
mation it can retrieve to the page. Figure 4.5 shows the result of running this in a
browser with several plug-ins installed.
NOTE
The following example only works in Netscape browsers, but Internet Explorer
does in fact support this array (or as Microsoft calls it, “collection”). For more
information on what properties and methods are supported under this collection,
visit http://msdn.microsoft.com/workshop/author/dhtml/reference/
collections/plugins_0.asp.
Figure 4.5
The result of running Listing 4.3 in a browser with several plug-ins installed.
In the script, you access the total number of plug-ins installed by using the length
property of the plug-ins array. After this has been done, determine the appropriate
header to write to the page and run through a for loop writing the plug-ins informa-
tion as well. This is a fairly simple example, but accessing these properties can be very
07 0672321416 CH04 7/24/01 11:55 AM Page 120
useful when determining what elements you want your pages to use when loaded by a
browser.
LiveConnect
LiveConnect is a Netscape-specific technology, starting with Netscape Navigator 3,
that provides a communication link among JavaScript scripts, Java, and plug-ins. It
allows JavaScript to access certain Java core functionality through the Packages object.
It can also access specific Java applets through the Applet array and plug-ins through
the Plugin array.
In this section, you’ll take a closer look at LiveConnect as it pertains to Java applets.
You’ll also step through some examples of using LiveConnect to extend the browser’s
interpretation of scripts and Java.
Why LiveConnect?
LiveConnect plays a very important role in linking JavaScript and Java together so that
each can rely and expand on the functionality the other has to offer. The ability to
dynamically change and interact with a Java applet on a page after it is loaded makes
it easy for a Web developer to harness the power of Java. This can be done in modular
fashion because it is completely possible that another developer wrote the applet.
On the flip side, LiveConnect enables an applet to access information contained in
scripts. Because information can be passed to and from the applets, developers are able
to maximize the functionality of their pages when using it. Using LiveConnect within
an enterprise gives the developer the ability to exploit these features. Netscape has
developed LiveConnect so that it fits nicely within its vision and adds to the mix of
technologies that support the “write once, run anywhere” theories.
LiveConnect Examples
The following two examples will give you a better understanding of how LiveConnect
works within Netscape’s browsers. The first example shows you how JavaScript can
access some of the Java language functionality natively (through the Packages object).
The second example shows how you can use JavaScript to interact with an applet.
Listing 4.4 uses some of Java’s native methods available via the Packages object. In
this example, a user can type some information in a form text box, and then click the
Print button to print his text to the Java Console. The onClick event is used to pass
the text information to a JavaScript function, where it then writes the information. The
result of running this example in a browser is shown in Figure 4.6.
NOTE
For this to work in Netscape 6, you must have selected the option to install the
Java runtime during your initial installation.
07 0672321416 CH04 7/24/01 11:55 AM Page 121
//This function takes the text entered in by the user and prints
//it to the Java Console.
function writeToConsole(inText){
Packages.java.lang.System.out.println(inText);
}
// -->
</script>
</head>
<body>
<form>
<input type=”text” name=”entered” width=”10”>
<input type=”button” value=”Print”
onClick=’writeToConsole(form.entered.value)’>
</form>
</body>
</html>
Figure 4.6
Using the Packages object to access the System.out.println() method in Java.
07 0672321416 CH04 7/24/01 11:55 AM Page 122
The second example is a little more complex. It takes text entered by the user and
passes it to a method within an applet to change the text the applet is displaying. To
help you get a full understanding of this example, this listing includes both the applet
code and the JavaScript code needed to perform this task. Listing 4.5 shows the Java
code necessary, whereas Listing 4.6 shows the JavaScript.
Listing 4.6 HTML Used to Load the Applet and Change the Text Within It
<html>
<head>
<title>LiveConnect Example #2</title>
</head>
<body>
<center>
<table border=”1”>
<tr>
<td align=”center”>
<applet
code=”PSLiveConnectExample.class”
07 0672321416 CH04 7/24/01 11:55 AM Page 123
codebase=”.”
name=”TextChanger”
width=”150”
height=”25”
mayscript>
</applet>
<form name=”inputForm”>
<input type=”button” value=”Change Text”
onclick=”document.TextChanger.changeString(document.inputForm.
➥inputText.value)”>
<input type=”text” size=”20” name=”inputText”>
</form>
</td>
</tr>
</table>
</center>
</body>
</html>
As you can see in Listing 4.6, the applet that displays the initial “Pure JavaScript”
text is loaded. After the page has finished loading, the user can enter text into the text
box and click the Change Text button to modify the text displayed by the applet. This
button directly accesses the changeString() method in the applet to change the text
from the default to that entered by the user. Figure 4.7 shows the result of changing this
text.
Figure 4.7
Using JavaScript to change the text in a Java applet.
07 0672321416 CH04 7/24/01 11:55 AM Page 124
Form Processing
Before JavaScript was developed, most developers used server-side programs to send
information from the Web server back to a user’s browser after a form was submitted.
When using a form, the user would enter his information and submit the form to the
server. This usually was slow, due to transmission delay back and forth to the server
and the fact that the Web server did most of the work with the form, such as parsing
information and validation.
JavaScript helps speed up this process by interacting with the form data, similar to
these server-side programs, before it is sent to the server. This saves the Web server
work and reduces the amount of time spent transmitting information. Using JavaScript
for form processing can be very useful to the developer and time-saving to the user.
NOTE
Form processing refers to the ability of Web developers to pass fields of informa-
tion from the browser to be processed by a server. When this information is passed
to the server, developers can use it as their application sees fit.
Many forms collect user information such as names, addresses, or interests. By col-
lecting this information, developers open up a whole new level of possibility in their
sites’ functionality. They are no longer placing static information out on their site for
the world to see; rather, it is a means of communication—communication between
users and their sites.
Communication between users and sites is mostly done through forms. When a user
fills out an online form and submits it, the information needs to be validated and
processed. Without client-side scripting languages, these actions can only be done on
the server-side. The validation and processing work can be broken out by using
JavaScript, which is where the language’s use of form processing really benefits devel-
opers.
Accurate processing of forms is dependent on the validity of the information given. It
is very easy to input incorrect data into a form and then submit it. When this is done,
you generally let the server handle any problems that might occur. These problems can
be avoided if JavaScript is used on the client-side to validate the data before it is sub-
mitted. JavaScript can check the data content and format before transmitting the data,
which, in turn, frees the server from encountering and dealing with these types of prob-
lems. The server’s only job now is to process the information being sent.
Keep in mind that JavaScript is not a complete substitute for server-side form process-
ing programs. It should be used more as a complement to these programs. By combin-
ing the use of JavaScript and server-side programs, a developer can create a very
effective and efficient means of processing forms.
Before programmers can use JavaScript with forms, they need to know how to get and
parse forms for information. The next section takes a look at methods of extracting
information from forms using JavaScript.
For instance, if you had a document containing three forms and you wanted to access
a property in the second form, you would reference it with the following syntax:
document.forms[1].property
In this example, the document object refers to the document in which the form is
located, and the property element refers to the property you are trying to access.
Listing 4.7 is an HTML page that contains two forms. In addition to the forms on this
page, two JavaScript functions are included in the <head> portion of the page that show
different methods of accessing forms and perform some input validation. Each of the
forms contains a text area for the user to insert text, as well as a Submit button. When
the user attempts to submit the form, an onClick event is fired and the contents of the
form are passed to a JavaScript function for processing.
Listing 4.7 Using the Forms Array to Access Multiple Forms on a Page
<html>
<head>
<title>Forms Array Example</title>
<script language=”JavaScript” type=”text/javascript”>
<!--
// Function verifyZip checks for a valid ZIP Code. If user enters invalid
// ZIP Code, then an alert box is used to inform the user. Function
// takes the length as an input parameter.
function verifyZip(length){
// Create variable and store the form value for the ZIP input.
var zipEntry = document.forms[0].zip.value;
function myName(){
// Get the form value of the name entered.
var name = document.form2.name.value;
alert(“You Entered: “ + name);
}
// -->
</script>
</head>
<body>
<p>
<center><b>Forms Example</b></center>
<br><br><br>
<table>
<form name=”form1” method=”post”>
<tr>
<td align=”right”>Enter a 5 Digit Zip Code:</td>
<td align=”left”>
<input type= “text” name=”zip” size=”15”>
<input type=”button” name=”button1”
➥value=”Verify” onclick=”verifyZip(5)”>
</td>
</tr>
</form>
<form name=”form2” action=”” method=”post”>
<tr>
<td align=”right”>Enter Your Name:</td>
<td align=”left”>
<input type=”text” name=”name” size=”15”>
<input type=”button” name=”button2” value=”Show Name”
onclick=”myName(this.form)”>
</td>
</tr>
</form>
</table>
</body>
</html>
In the first form, validation is performed on the input. The user is asked to enter a five-
digit ZIP Code. Once entered, the user can push the verify button, which calls the
verifyZip function. This function uses the forms array index number to access the user
input. Figure 4.8 shows this example of accessing the forms array.
NOTE
Remember that form indexes are zero indexed and are stored in the array in
sequential order. The first form in the document is forms[0], the second form is
forms[1], the third form is forms[2], and so on.
07 0672321416 CH04 7/24/01 11:55 AM Page 128
Figure 4.8
The output result for processing the first form.
When a script has the input, it can perform checks to make sure that it is the correct
length and that a numeric value was entered. If the correct information has been
entered, a message is displayed informing the user the input was valid. If incorrect
information was entered, an error message is displayed informing the user of an invalid
entry.
The second form takes a name as input and passes it to the showName function, which
displays the name in a window when the Show Name button is chosen. Notice that the
function accesses the form information differently than the first function. Instead of
using the forms array, it references the form by its name value.
In this example, the variable name is set using the name attribute of the <form> tag
instead of the index number of the Forms array. Either method of accessing a form ele-
ment is valid. However, if a document contains many forms, it might be easier to use
the form name instead of counting the Forms array index numbers. Accessing a form
through the name attribute also tends to make the script easier to understand.
This example demonstrates some uses of combining forms and JavaScript. Another
useful function of JavaScript and forms is information manipulation. For instance, if
the form processing program on the server-side only processes phone numbers without
the hyphen, developers can program their scripts to strip all hyphens out of phone num-
bers before submission.
instead of index number. Listing 4.8 demonstrates the two different ways of accessing
form elements.
// -->
</script>
</head>
<body>
</body>
</html>
The information entered into each text box becomes an element of the form. Using the
elements array, a script can access each individual element of the array. As you can
07 0672321416 CH04 7/24/01 11:55 AM Page 130
TIP
Referencing by the elements array can be useful if you want to keep your pro-
gram generic, but if you want better maintainability and ease of use, referencing
by name is the preferred choice.
In addition to accessing form elements, you can also write or modify form information.
This can be a very useful technique for automatic form correction. Just about any
object that carries information within a form can be modified.
Take a look at a simple example of writing information to forms. Listing 4.9 contains
a form with one text box with a question and one Submit button. The user is asked to
enter the answer to the question. If the answer is correct, an information box appears
indicating so. If it is wrong, an alert box appears informing the user that he entered the
wrong answer, and the correct answer is automatically written to the text box.
// -->
</script>
</head>
<body>
Building on the foundation of the code in Listing 4.9, it’s possible to create a JavaScript
method that creates a customized pull-down menu based on specific user input.
Form Example
Listing 4.10 presents a sample Web page that allows a user to enter his personal infor-
mation to submit. After all the information is entered and the user clicks the Submit
button, all the form data is validated on the client-side before passing the data to the
server for further processing.
else{
// Check that the ZIP and phone numbers are valid inputs.
var checkZip = checkNum(5);
var phoneInput = document.info.phone.value;
// Initialize variables.
var validPhone = false;
var validZip = false;
if(checkZip == true){
validZip = true;
}
else{
alert(“Invalid ZIP Code: “ + validZip);
}
function checkPhone(str){
var regexp = /^(\d{10}|\d{3}-\d{3}-\d{4}|\(\d{3}\)\d{3}-\d{4})$/;
return regexp.test(str);
}
if (document.info.zip.value.length == length){
if(zipNum != 0 && isNaN(zipNum) == false){
// Valid ZIP Code
return true;
}
else {
// Invalid ZIP Code
return false;
}
}
else {
//Too Many digits- Invalid
return false;
}
}
// -->
</script>
</head>
<body>
<p>
<center><b>Form Validation Example</b></center>
<p>This page demonstrates how JavaScript can do form validation on a Web page.
Using JavaScript to do validation on the client-side can greatly reduce
processing time by reducing the chance of submitting incorrect forms.
<hr>
<br>
<b>Personal Information:</b>
<form name=”info” method=”post”>
<table>
<tr>
<td align=”left”>first name:</td>
<td align=”left”>
<input type=”text” name=”fname” size=”15”>
last name:
<input type=”text” name=”lname” size=”20”>
</td>
</tr>
<br>
07 0672321416 CH04 7/24/01 11:55 AM Page 134
ZIP:
<input type=”text” name=”zip” size=”7”>
</td>
</tr>
<br>
<tr>
<td align=”left”>Phone (w/area code):</td>
<td align=”left”>
<input type=”text” name=”phone” size=20>
</td>
</tr>
07 0672321416 CH04 7/24/01 11:55 AM Page 135
<br>
<tr>
<td align=”left”>Email:</td>
<td align=”left”>
<input type=”text” name=”email” size=”20”>
</td>
</tr>
<br>
</table>
<center>
<input type=”button” value=”Submit” onclick=”validatePersonalInfo()”>
</center>
</form>
</body>
</html>
Figure 4.9
Form example using client-side validation.
The form begins by validating that all the input fields have been filled. If any of the
fields are left empty, an alert box will appear indicating that the field requires input.
Two main inputs require special validation: the ZIP Code and the phone number.
The first function called is ValidatePersonalInfo. This main function checks to see
that all the user entries are valid. If so, an alert box is returned indicating that the form
has been validated. Before the form can be completely validated, the ZIP Code and
07 0672321416 CH04 7/24/01 11:55 AM Page 136
phone number must be checked. The ZIP Code verification is performed by the sub-
function called checkNum. This function takes one parameter—the string length. For the
ZIP Code, we are restricting the string length to five digits. If this is found to be true,
the ZIP Code is validated.
The second sub-function called is checkPhone. The checkPhone function takes the
input for the phone number and checks it against three different standard phone num-
ber formats. If any are found to be valid, the function returns true. After both checks
are performed, the form is determined to contain valid information.
Cookie Handling
A cookie is a small bit of organized information that is stored by a browser in a text file
on the user’s computer. Cookies are typically used to store information pertinent to a
specific site that is currently used and can be reused in the future.
The location of cookie text file differs according to the browser being used. In
Navigator, all cookies are stored in a file named cookies.txt. In Internet Explorer,
each cookie is stored as its own individual text file in the Cookies folder, which is
located by default in the \Windows or \Winnt folder.
There are limitations to cookies. The size of a cookie is limited to 4KB. Also,
Navigator browsers only allow for 300 total cookies to be stored on the user’s com-
puter. This keeps the size of the cookies.txt file or Cookies folder to a 1200KB max-
imum. In addition, each Web server is only allowed to store a total of 20 cookies. If the
300 total cookies or 20 cookies per Web server limit is exceeded, the least recently used
cookie is deleted to accommodate any additional cookies.
Browsers let the user control how cookies are used. In Navigator, under Edit,
Preferences, there is an Advanced category. This category gives you the option to
accept all cookies, accept cookies that get sent back to the server, or disable cookies.
There is also an option to warn you before accepting a cookie. Enabling this option will
force the browser to notify you when a cookie requests to be set and inform you of what
the cookie contains. Figure 4.10 shows a picture of what a cookie warning would look
like. Similarly, Internet Explorer controls the use of cookies through its Security tab on
its Internet Options dialog box (available under the Tools menu for version 5.5 on
Windows).
NOTE
When a cookie is first set, it is stored in the browser’s memory. It isn’t until the
browser is exited that the cookie gets written to the file.
The cookie object is part of the Document object. Cookies can be created, set, and mod-
ified by setting the appropriate values of the cookie property. A cookie has four name
attributes: expires, path, domain, and secure.
07 0672321416 CH04 7/24/01 11:55 AM Page 137
Figure 4.10
Cookie warning example.
By default, a cookie lasts only during the current browsing session. When the brows-
ing session is over, the cookie is destroyed. For a cookie to last beyond the current
browsing session, the expires attribute must be set. This attribute specifies the life of
a cookie. The value of this attribute can be set to any valid date string. If the expires
attribute is set, the cookie is written to the cookie text file after the current browsing
session is over. If no expires attribute is set, the cookie will expire when the user’s
browsing session ends.
The path attribute specifies the domain associated with the cookie. The level of asso-
ciation begins at the specified path and goes down into any subfolders. For example,
suppose that http://www.purejavascript.com/examples/cookie.html was setting a
cookie and wanted the cookie to be shared across Web pages on the pure-
javascript.com domain. To do this, the cookie path attribute needs to be set to “/”.
This allows the cookie to be accessed from any page on the www.purejavascript.com
Web server. If the path was set to “/examples”, the cookie would only be valid to pages
in the examples folder and its subfolders.
NOTE
If the secure attribute is specified, the cookie will be only be transmitted over a
secure channel (HTTPS). If secure is not specified, the cookie can be transmitted
over any communications channel.
Understanding the cookie attributes is the first step in being able to read and write
cookies. Now that you do understand this, look at how to read cookies.
07 0672321416 CH04 7/24/01 11:55 AM Page 138
Reading Cookies
As stated before, cookies are part of the document object. The first thing you have to
do is to read the cookie property. This can be done with the following statement:
var cookieName = document.cookie;
This statement creates the variable cookieName and assigns it the cookie property of
the document object. When you have accessed this property, you must extract the var-
ious attributes of the cookie. The cookie property itself returns a string containing all
the cookies pertaining to the current document.
Cookies are interpreted in name/value pairs. The string returned from the cookie prop-
erty contains the list of cookie name/value pairs. To read an individual attribute, you
must parse through its string. You can use built-in JavaScript string methods to accom-
plish this.
Look at the example in Listing 4.11 to see how to read a cookie. When calling
this function in your code, you simply need to pass the name of the cookie you are
looking for.
if (end == -1){
end = cookies.length;
07 0672321416 CH04 7/24/01 11:55 AM Page 139
if(value == null){
alert(“No cookie found”);
}
else{
alert(“Cookie value is: “ + value);
}
}
// -->
</script>
Writing Cookies
Cookie values can be created, modified, and set. Remember that cookies are read as
name/value pairs. Therefore, when you write a cookie, its attributes must be written as
a name/value pair.
To set a cookie value, you first create a cookie and assign it a name. Then you must set
each individual attribute for the new cookie. Keep in mind that when you set the
expires attribute, you must have a valid date string. It is best to use the JavaScript Date
methods to create a date string, which can be assigned. Additional cookie attributes can
be set similarly. The following is an example of how this is done:
document.cookie = “name=” + form.cookie.value + “; expires=” + month;
If you want to modify a specific value in the cookie, just set its attributes again. You
can delete a cookie’s value by modifying that attribute.
Windows in Action
A window object is used in all your JavaScript programs, whether you specify it or not.
The window object is one level higher than the document object in the JavaScript object
hierarchy and provides a developer with the ability to manipulate the current window
as well as create new window instances.
The ability to create new windows allows developers to add functionality to their sites.
Some sites have advertisers create new windows to show their advertisement banners,
whereas others, such as ESPN (shown in Figure 4.11), use this as a method to play
games in windows while their users continue to browse.
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
// Function creates a new window called myChild
// with the index.html file in it.
function create(){
open(“index.html”, “myChild”);
}
// -->
</script>
</head>
<body>
<form name=”form1”>
<input type=”button” value=”Create Child” onclick=’create()’>
</form>
</body>
</html>
Figure 4.11
Pop-up window for a game.
The function create simply creates a new window that would be considered a child of
the original window. The name of the child is specified in the second parameter of the
window.open function, which is “myChild”. Any values in the child window are refer-
enced using the name of the parent window. If the child window has a child of its own,
07 0672321416 CH04 7/24/01 11:55 AM Page 141
The parent has total control of its immediate child window and any subsequent child
(grandchild) windows. If the parent window is destroyed, all control for the remaining
child windows is lost.
A child window can find out who its parent is by using the opener method. The opener
method will tell the child from which window it was created. You use the opener
method as shown in the following:
var name = window.opener.document.name;
This will return the name of the parent document to the name variable.
You can use multiple instances of opener if you have several levels of windows. If a
grandchild wanted to reference its grandparent, it could do so by simply adding another
level:
window.opener.opener.document.form1.textbox.value
For a window to refer to its own properties, you can use the window self property.
Suppose that you wanted to set a textbox value within a form document in a window.
You could refer to the value as shown in the following:
self.document.formName.textbox.value = “JavaScript is cool”;
Creating Windows
JavaScript provides a built-in method to create new instances of windows. The open
method can be used to create any primary or secondary window. The following is an
example of how open can be used.
window.open(“web.html”, “newWin”, “resizeable,menubar,toolbar”);
This creates a window that is resizable, contains a menu bar, and has a toolbar. The
“web.html” is the file that will open in the newly created window. “newWin” repre-
sents the name of the window object. Many different features can be added to a
window. This example only shows a few. Other features include, outerHeight,
outerWidth, innerHeight, innerWidth, alwaysRaised, alwaysLowered, location,
screenY, and screenX. The features are specified in the parameters of the open
function.
07 0672321416 CH04 7/24/01 11:55 AM Page 142
NOTE
Be careful not to include any spaces between window features; this will cause
errors to occur in your window creation. Refer to the windows object in Chapter 8,
“Client-Side,” for more details on other windows properties.
After you create a new window, you can manipulate it. JavaScript also provides you
with the ability to interact between multiple windows. As long as a window property is
referenced correctly, you can modify objects in other windows. Remember the parent-
child relationship when referencing window objects.
Limitations
In older versions of JavaScript, windows could only be referenced from the top down.
This meant that a parent window would know the properties of its child windows, but
not vice versa. In JavaScript version 1.2 and later, this problem is resolved. As men-
tioned earlier, using the opener property will resolve any child/parent referencing con-
flicts.
Window Example
The next example shows how you can send information between two windows. It
begins with the parent window. Figure 4.12 shows both the parent and child windows
open with the parent window on the top.
Figure 4.12
Window example showing how information can be sent between windows.
// -->
</script>
</head>
<body>
<p>
<center>
<b>Window Example - Parent Window</b>
<br><br><br>
</center>
<form name=”parentForm”>
Click on the Button below to open a Child window:
<br><br>
<input type=”button” name=”submit” value=”Open Child Window”
onclick=”openWin()”>
<br><br><br>
<table>
<tr>
<td align=”left”>
<input type=”text” name=”parenttext” size=”45”>
</td>
<td align=”left”>
<input type=”button” name=”submit” value=”Send To Child”
onclick=”sendToChild()”>
</td>
</tr>
<tr>
07 0672321416 CH04 7/24/01 11:55 AM Page 144
This parent window has a button, which, when clicked, opens a child window. It also
has two text fields, one for sending text to the child and one for receiving text from the
child. The user will first click the button to create a new window. This is the child win-
dow. When the user enters text into the first text box and clicks the Send Text button,
the input is sent to the child and appears in its appropriate text box. Take a look now at
what the child window looks like in Listing 4.13.
// Function sends a value from the child window to the parent window.
function sendToParent(){
window.opener.document.parentForm.received.value =
➥document.childForm.sendText.value;
}
// -->
</script>
</head>
<body>
<p>
<center>
<b>Window Example - Child window</b>
<br><br><br>
</center>
<form name=”childForm”>
<table>
<tr>
<td align=”left”>
07 0672321416 CH04 7/24/01 11:55 AM Page 145
The child window is similar to the parent except that there is no option to open another
window. The child window has one text field for sending text to the parent window and
one text field for receiving text from the parent. In the JavaScript code, you can see the
use of the opener property to reference its parent. Remember, you cannot reference
windows directly upward. The parent can call a child by name, but a child cannot call
the parent by its name.
Manipulating windows provides you with the ability to greatly expand your site’s func-
tionality. Many window properties can be specified or modified to your individual
needs. Do be careful on how you implement these windows, however, because often
times too many (or any for that matter) pop-up windows can be annoying. Be sure that
you really need it.
Dynamic Documents
As Web sites became more advanced, the need for dynamic content grew. In the begin-
ning, the only type of presentation technologies available was plain HTML. It allowed
various type of formatting so content could be displayed in a pleasant manner, but soon
more was needed—enter scripting languages. The combination of JavaScript and
HTML was a big step, and that coupled with support for CSS meant that a developer
could create static content with HTML and then have control over it with JavaScript
and CSS.
The Web has come a long way in a very short period. The first generation was called
Dynamic HTML or DHTML for short. As we just mentioned, DHTML wasn’t one spe-
cific technology, but a core set of three technologies working together to provide a
toolset for developers to create dynamic content. But things have moved on even more
since then.
07 0672321416 CH04 7/24/01 11:55 AM Page 146
In today’s newest browsers we have the Document Object Model (DOM) at our dis-
posal. This is an attempt to standardize the method in which you access elements
within a given document, such as an HTML or XHTML document. This is definitely
the way of the future, but it does not remove the fact that some of the older browsers
are still around.
Within this section of the chapter, we are going to take a look at both the old (DHTML)
and new (scripting the DOM) ways of doing things. We will also show you how to build
cross-browser scripts that will work in all version 4+ browsers. With the rate of adop-
tion of the DOM, this will most likely be the last edition of this book that covers the
old way, but for now it is definitely still needed.
Navigator 4 Layers
The concept of layers was introduced in Navigator 4, but not only in the HTML, but
also through the new Layers object in JavaScript 1.2. Similar to many things at the
time, these layers were only supported in Navigator 4—not Internet Explorer. They
did have some usefulness, however, by providing the ability to control the stacking and
movement of elements within a single window.
On the HTML side, one of the new tags created was the <layer> tag. This tag allowed
you use JavaScript for layer manipulation. The following shows an example of using
this tag.
<layer id=”myLayer” width=”220” height=”100” bgcolor=”red” top=”150”
left=”100” visibility=”show”>
This is a Navigator 4 tag
</layer>
The positioning of layers could be either absolute or relative, as with most elements.
With absolute positioning, you can specify the position within its containing layer.
Relative positioning is when the object appears in its natural location within the flow
of the document.
The <layer> tag used absolute positioning, and contained properties that let a devel-
oper specify the exact position in the document. Now the second tag they introduced
07 0672321416 CH04 7/24/01 11:55 AM Page 147
allowed for relative positioning. The <ilayer> tag was considered an inflow or inline
layer.
The HTML tags were only half of what was added by Netscape for this functionality.
In addition to this, they also added the Layer object and the document.layers array to
JavaScript for accessing and manipulating these layers. This object contained its own
methods and properties for performing these tasks.
Even though it is not defined in the HTML 4 Recommendation, Navigator 4 required
that you have the name attribute set in the tags, be it <layer>, <ilayer>, or <div>
(which was used to define groups of tags) for this to work. The syntax is rather simple
for accessing layers in this manner. For instance, if you are wanting to access a layer
called layer1, you could accomplish this through the following syntax:
document.layers[‘layer1’]
Because these types of layers represent the old method of performing document
dynamics, we are not going to go into any more detail here. We will, however, include
a cross-browser example later in the chapter in the section called “Dynamic
Documents” that will help show how dynamic documents in Navigator 4 works. But
moving forward, you should pay close attention to the new method, which is what has
been implemented in Netscape 6.
NOTE
Want some more information on Navigator’s Layer object? Check out its entry in
Chapter 8.
Even though both the Netscape and Internet Explorer methods differ, both have been
deprecated in favor of the DOM approach.
NOTE
If you really want to learn more about the DOM and all its details, take a look at
the W3C DOM Level 1 and Level 2 Recommendation and the new work involved
around the future Level 3.
The DOM allows a program to access all the elements in a document through a “tree”
like object structure. The structure begins with a root object; typically in an HTML file,
this would be the <html> tag. Within the root object, additional objects are contained
in a parent-child type relationship. A child would be considered as any node nested
07 0672321416 CH04 7/24/01 11:55 AM Page 149
within another node. In the previous example, the <html> node would be a parent to
the <body> node. The <img> node would be considered a child to the body node, and
so on.
Nodes can be accessed directly by name (if they have a name attribute) by using built-
in DOM methods or through parent-child relationship properties. To access a node by
name, use the getElementById() method of the Document object. If using the parent-
child assesors, the Document.parentNode[], Document.childNodes[], and
Document.getSibling[] arrays will be the most useful.
Elements and attributes can be added, modified, or deleted through the DOM. To cre-
ate a new element, the createElement() method is used. Looking at the following
example, we see how to create a new anchor element and add attributes to it:
var myNewLink = document.createElement(‘a’);
myNewLink.setAttribute(‘href’, ‘home.html’);
myNewLink.setAttribute(‘name’, ’Homepage’);
There are many built-in methods and properties for manipulating the DOM. To see a
list of all the properties, refer to the W3C DOM Recommendation available at
http://www.w3.org/DOM or the DOM browser support information for Netscape,
Internet Explorer, or Opera browsers.
DOM Example
Now that we have discussed what the DOM is, some of its methods, and how to manip-
ulate it, let’s take a look at an example. Listing 4.14 demonstrates three different parts;
the first of which is how to add text dynamically within a document. The second shows
how to modify an HTML ordered list to an unordered list, and the third part shows how
a link can be added to a document dynamically.
</ol>
<input type=”button” value=”Change List Type” onclick=”changeList()”>
</form>
<p>
</body>
</html>
As for the function, its purpose is to set the proper variables that represent our script-
ing syntax. It looks like the following, where ieVer represents the major version num-
ber of any IE browser accessing the page. As for the “Gecko” reference, that is part of
the user agent string within browsers built from Mozilla.org’s Gecko rendering engine,
such as Netscape 6.
function checkBrowser(){
// IE 4
if((ieVer < 5) && (ieVer > 0)){
block = “.all”;
style = “.style”;
isDHTML = “true”;
// Navigator 4
}else if(navigator.userAgent.indexOf(“Nav”) != -1){
block = “.layers”;
style = “”;
isDHTML = “true”;
// IE 5+ and Netscape 6+
}else if((navigator.userAgent.indexOf(“Gecko”) != -1) ||
(ieVer >= 5)){
isDOM = “true”;
}
}
These two methods might seem to pose a problem for writing your code because it
appears we will have to write two different sets of code for each browser. Within the
JavaScript language, however, there is a top-level eval() function that takes a string
passed to it, and evaluates it as JavaScript code. This allows us, for instance, to dynam-
ically build a piece of JavaScript code, such as our layer reference, and pass it to the
eval() function to be executed.
This only takes care of the older DHTML method, so we also need to take what we
learned earlier and use it to access the DOM for the newer browsers. We accomplish
this by using the getElementById() method to return a pointer to the layer, and then
using the element.style.visibility property to hide or show the layer. You will also
notice in the function that we set an isDHTML and an isDOM variable, which we will use
later.
The last function takes care of all this and is the one called by our form buttons—
changeState(). This function takes two parameters—the first one is the name of the
07 0672321416 CH04 7/24/01 11:55 AM Page 153
layer it is supposed to effect, and the second is the visibility value that the layer should
be changed to. Because we have to access and change the layer properties using dif-
ferent methods, our function will look similar to
function changeState(dblock, state){
if(isDHTML == “true”){
eval(“document” + block + “[‘“ + dblock + “‘]” + style +
“.visibility = ‘“ + state + “‘“);
}else if(isDOM == “true”){
var blockElement = document.getElementById(dblock);
blockElement.style.visibility = state;
}
At this point, we have gone over most of the code with the exception of some variable
declarations and a single style sheet property setting. Listing 4.15 contains the com-
plete example.
// determine IE version
var ieVer = parseInt(navigator.userAgent.charAt(parseInt(
➥navigator.userAgent.indexOf(“MSIE”)) + 5));
isDHTML = “true”;
}else if((navigator.userAgent.indexOf(“Gecko”) != -1) ||
(ieVer >= 5)){
isDOM = “true”;
}
}
What Is XUL?
XUL is an XML-based programming language used for defining objects and layouts in
a user interface. XUL was created to provide a XML shorthand for describing the con-
tents of windows and dialogs and is heavily used within the Mozilla and Netscape 6
browsers.
07 0672321416 CH04 7/24/01 11:55 AM Page 155
The first line denotes that this is an XML file and specifies the version, while the sec-
ond line defines which style sheets will be used for this particular file. The third line
designates the type of document it is, while the fourth line allocates a namespace to the
XUL file listed at the end of the URL.
NOTE
Want more information on namespaces in XML? Check out
http://www.w3.org/TR/1999/REC-xml-names-19990114.
XUL works primarily with widgets. These are things such as menus, toolbars, buttons,
scrollbars, and so on. These widgets can use JavaScript to interact with the user. For
example, suppose that you create a new button widget and want to perform a specific
function when the button is pressed. Using the JavaScript onclick event handler, you
can determine when the new button has been pressed. This works for other events as
well.
XUL Example
Let’s look at an example of an XUL file, which creates a new menu. Listing 4.16 shows
a very simple XUL program that uses the menubar widget.
07 0672321416 CH04 7/24/01 11:55 AM Page 156
The example creates a new menu, aNewMenu, and adds three options to it. A separator
is used to distinguish between the first two items and the last item. Each item performs
a specific JavaScript function, which is defined in a separate file named
“myScript.js”.
Moving On
In this chapter, we discussed a number of different items related to Client-side script-
ing with JavaScript. In this edition, we’ve expanded to new technologies including the
Document Object Model and XUL. Scripting technology is becoming more advanced
every day. With the advent of DOM and XML, developers are able to create a wide
variety of dynamic Web content.
08 0672321416 CH05 7/24/01 11:57 AM Page 157
NOTE
Netscape and Sun have joined forces to jointly create
various server applications under the name iPlanet
(http://www.iplanet.com). This alliance occurred after the
release of Netscape Enterprise Server 3.6, which is why
the 4.0 server is referred to as iPlanet Enterprise Server.
From this point on, we will simply refer to this server-side
JavaScript environment as the Enterprise Server environ-
ment to avoid confusion.
1 5 8 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
programs. Overall, this chapter will be a primer for any server-side JavaScript you
might be deploying on your site.
Server-Side Environments
One of the first things you should understand about using JavaScript on the server-side
is the fact that the implementations within the Enterprise and IIS servers are different.
This difference is much greater than that on the client-side, where differences appear
in object models and means of implementation.
On the Enterprise front, we find that the Netscape and iPlanet alliance has created
objects, properties, and methods that conform to standard server-side functionality no
matter what the platform. You will find language elements that allow you to access the
file system, send mail, and retrieve data from databases. None of these items are spe-
cific to any platform and are generic enough to be used across all the platforms sup-
ported by the server.
Microsoft, on the other hand, has taken a very Windows-centric approach to imple-
menting a server-side version of its JScript language. It has many objects and related
elements pertaining to the Windows environment. And lately, it has extended support
for the JScript language to be included as a major language within its .NET framework.
We will touch on these areas in this chapter.
Programming Differences
The next items to analyze in server-side JavaScript are the programming differences
that occur. Besides the functionality added on the server-side, JavaScript also has some
key programming differences. These include, but are not limited to, the following:
• Within the Enterprise Server environment, scripts to be executed on the server-
side are contained between beginning <server> and ending </server> tags.
• Within the Microsoft ASP environments, the JScript language must first be
specified. By default, the VBScript language is the dialect of choice.
• Additional objects, methods, properties, and events are available on the
server-side.
08 0672321416 CH05 7/24/01 11:57 AM Page 159
N e t s c a p e ’s S e r v e r- S i d e J a v a S c r i p t 1 5 9
NOTE
Because there are differences in the server-side and client-side implementations,
refer to Part III, “JavaScript Reference,” to determine if the object, method, prop-
erty, or event you want to use is supported.
1 6 0 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
Server Support
Before you start developing any server-side JavaScript application within the
Enterprise Server environment, you should first make sure of the level of support you
have access to. As you are beginning to see, things have changed a lot with JavaScript
over the years, and you want to make sure that you have the resources necessary to per-
form the tasks you need to accomplish. Table 5.1 has a list of the various versions of
JavaScript on the server-side within the Enterprise Server environment.
NOTE
In Table 5.2, all the options are listed as -option. The tool also accepts the syntax
of /option. In addition, all paths should use a backslash (\) for directory mappings
because the forward slash maps to the use of an option.
N e t s c a p e ’s S e r v e r- S i d e J a v a S c r i p t 1 6 1
Option Description
-d Displays the JavaScript contents of your files.
-f filelist This specifies a text file that contains the names of all the files
you want to include in your build. The primary reason for this
option is for those operating systems that have a limit to the
number of characters you can specify on a single command line.
Each filename in the file should be separated by a space. If your
filename has a space in it, include the name within quotes.
-h Displays help for the tool. Do not use with any other options.
-i inputfile Specifies the name of a single input .html file. See -f when
including multiple files.
-l characterset Allows you to specify the character set used when compiling
your application. This would be something similar to iso-8859-1.
-o outputfile Specifies the name of the output .web file you are creating. Do
not use this with the -c option.
-p path Designates the root for any relative path filenames you specify.
-r errorfile This option allows you to specify a file to which to have all
errors written.
-v Displays verbose information about the execution of the
compile.
Using these options, a typical build of an application might look something similar to
the following.
jsac -o myApp.web -v index.html results.html jsbeans.js
It specifies to display the build process verbose, defines the output file as myApp.web,
and gives the filenames of the files to include.
Here is another example that specifies a full path to the input file as well as sets an error
file to log any errors during the compilation process.
jsac -o myApp.web -v -i /js/myapps/index.html -r /js/logs/myapperror.log
1 6 2 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
Figure 5.1
Enterprise Server’s Server Side JavaScript Application Manager.
This manager is much more than a start and stop location for applications. In fact, it is
most useful for verifying current status and information, debugging, and setting con-
figuration options. After an application has been compiled and added to the Server Side
JavaScript Application Manager, this interface is used to maintain all aspects of the
program—not including the actual coding, of course. However, before you can use the
JavaScript Application Manager, you must do a few things.
Configuration
Before the Server Side JavaScript Application Manager is available for use, it must be
enabled within an instance of Enterprise Server. This can be done easily from the
Server Manger.
Once logged in to the Administration Server, simply select the option that represents
the instance of the Web server on which you want to enable server-side JavaScript.
When you have accessed the Server Manager for this instance, click the Programs but-
ton in the menu bar. Next, click the link to Server Side JavaScript in the navigation bar
to the left of the page. This takes you to the main screen, shown in Figure 5.2.
When you have access to this page, there are three options:
• Activate the server-side JavaScript environment
• Require a password for access to the JavaScript Application Manager
• Select a JavaScript Thread Pool option
08 0672321416 CH05 7/24/01 11:57 AM Page 163
N e t s c a p e ’s S e r v e r- S i d e J a v a S c r i p t 1 6 3
Figure 5.2
Enabling server-side JavaScript through the Server Manager.
The first thing you need to select in this screen is to activate the server-side JavaScript
environment. Next, consider using the Administration password to access the
JavaScript Application Manager. This is highly recommended because it is a major
security risk to unprotect applications. Without the password, a person could stop, or
even worse, modify the settings for applications. And finally, if you plan on using
server-side JavaScript to connect to databases, you can specify a thread pool. For more
information on thread pooling, click the Help button on this screen.
When server-side JavaScript is enabled and you have made a decision on whether to
password protect the application manager, click the OK button. This will take you to
the Save And Apply Changes page, where you should click Save And Apply to activate
these options. An alert box will be displayed, confirming a successful or unsuccessful
change.
PROBLEMS?
If problems are encountered here, check the following:
• Are any NSAPI (Netscape Server Application Programming Interface) plug-ins run-
ning that might conflict with server-side JavaScript?
• Is any kind of third-party software being used to dynamically build the Web pages
for this site that might have conflicting or overlapping settings?
• Has someone hand modified the obj.conf file recently?
08 0672321416 CH05 7/24/01 11:57 AM Page 164
1 6 4 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
For the first two, think specifically about those applications or NSAPI plug-ins that
parse pages. Consider turning off Parsed HTML if it is enabled. This can be done
within the Web server instance’s administration by clicking the Content
Management menu item and then clicking the Parse HTML link in the navigation.
Finally, if there are still troubles or if the third bullet point came into play, consider
loading a previous version of the obj.conf file. This can be done by clicking the
Server Preferences menu item, and then selecting the Restore Configuration link in
the navigation. Check under the obj.conf column and roll it back one version at a
time until it works. Note that you are undoing any prior changes of the configura-
tion file. Doing so might break another process while trying to fix the JavaScript
ApplicationManager.
When a successful saving of the configuration file (obj.conf) and restarting of the Web
server has been accomplished, you will be returned to the Active Server Side JavaScript
page. At the top of the page, there will now be a link to the Server Side JavaScript
Application Manager. This link will be in the following form, where machinename is
replaced with the name of your machine and domain if applicable.
http://machinename/appmgr
Now that everything is configured to run the application manager, click the link. This
will launch another page and load the Server Side JavaScript Application Manager.
When on this page, click the Preferences tab. This will display a page to set up some
defaults when adding new applications and set a couple of preferences.
Table 5.3 defines the options available when setting the default values for new appli-
cations.
Table 5.3 Default Application Settings That Can Be Set for the
JavaScript Application Manager
Setting Description
Web File Path This is the default path to your .web file. If you store
all your applications in a subdirectory of /ssjsapps/
myprojects, you should choose this option.
Default Page This option specifies the default page of your appli-
cation. For practical purposes, you might want to set
this to index.html.
Initial Page This specifies the initial page of your application. For
example, if your application has global settings that
are only loaded when the application is first started
and you have stored this in a file called global.html,
you should set this option to this file.
Built-In Maximum Database Those of you who are using databases that charge
Connections on a per connection basis will like this feature. It is
the default that restricts your applications to a set
number of maximum connections.
08 0672321416 CH05 7/24/01 11:57 AM Page 165
N e t s c a p e ’s S e r v e r- S i d e J a v a S c r i p t 1 6 5
Setting Description
External Libraries This contains the absolute path to any external
libraries that your application might be using.
Client Object Maintenance This default option is used to determine if you are
going to maintain user sessions in your application.
The possible choices are Client Cookie, Client-URL,
Server-IP, Server-Cookie, and Server-URL.
After specifying the options for the Default Values When Adding Applications section,
specify your preferences. Within the Preferences section, there are two items to set:
• Confirm On—This option determines if a confirmation dialog box is to pop up
before you perform a task. The list of tasks this can be enabled for are Remove,
Start, Stop, and/or Restart an application.
• Debug Output—This option allows you to choose if you want to do your
debugging in the Same Window or Other Window of the application.
After these settings are completed, click the OK button. This will finish the configura-
tion of the Server Side JavaScript Application Manager. Additional help or documen-
tation can be accessed by clicking the links within the user interface.
Script Management
Managing scripts might be one of the most overlooked aspects of deploying a Web-
based application. The mentality seems to be, “It was written to never break.” This, as
we all know, simply never holds up in the real world. Even applications that worked
perfectly for years will eventually hit a bump. It might be after an upgrade to a new
server, or maybe a new browser has come out that implements some client-side
JavaScript differently than expected. Either way, it will happen, so expect it.
The Server Side JavaScript Application Manager provides a common location to man-
age applications as well as perform maintenance on them. You can access the online
documentation at DevEdge and launch the help window with documentation before
clicking any of the available tabs.
When the Applications tab is selected, you will see the list of applications currently
installed. These are located in a scrolling text area at the top of the section. After an
application is selected, any of the options defined in Table 5.4 can be used.
1 6 6 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
Figure 5.3
The Debugging window is used to display various bits of information about the applica-
tion being debugged.
08 0672321416 CH05 7/24/01 11:57 AM Page 167
As a programmer, you often will want to know the value of variables you create and
return values of methods. Server-side JavaScript makes this possible by using the
debug() method in scripts to write information to the Trace Information window dur-
ing runtime. This method is similar to the write() server-side method, where a string
or variable is passed, and the interpreter writes the data passed to the window. A typi-
cal use of this method might look similar to the following:
debug(“myFunction entered and was passed: “ + myVar);
NOTE
For more information on using the debug() method, see its entry in Chapter 9,
“Server-Side.”
1 6 8 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
Server Support
Before you start developing any server-side JScript application within the ASP envi-
ronment, you should first make sure of the level of support you have access to. Table
5.5 has a list of the various versions of JScript on the server-side within IIS.
U s e s o f S e r v e r- S i d e J a v a S c r i p t 1 6 9
NOTE
See Chapter 9 for more information on these objects and their properties, meth-
ods, events, and collections.
</script>
</body>
</html>
1 7 0 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
outline all the uses you might encounter, but rather discusses some of the more
common aspects of using server-side JavaScript. We have included examples for both
environments specific to the server-side implementation, so this should give you a good
taste of what you can do with this powerful language.
Database Connectivity
One of the major features of server-side JavaScript is its capability to connect to data-
bases. As you know, Netscape has paved the way for the use of standardized technol-
ogy, and you can expect nothing less when connecting to databases. It provides
native-support, industry-leading databases such as DB2, Informix, Oracle, and Sybase
databases, as well as access through ODBC for other databases, such as Microsoft’s
SQL Server.
The functionality server-side JavaScript provides for connecting to databases is done
through its LiveWire service, which no longer has to be installed as a separate compo-
nent. This service provides JavaScript objects that can be used to connect to various
databases. Once connected, you are able to run the SQL statements necessary to per-
form the operations you want.
NOTE
When Netscape released version 2 of Enterprise Server, LiveWire was a blanket
term for “server-side JavaScript.” By the time version 3 of Enterprise Server was
released, the acceptance of JavaScript as an industry standard had increased. To
maintain some consistency across terminology, the term LiveWire has now, starting
with version 3 of Enterprise Server, been associated with the service that allows
developers to write code to interact with databases.
U s e s o f S e r v e r- S i d e J a v a S c r i p t 1 7 1
var myPool = new DbPool (DBType, DBInstance, UID, PWD, DBName, MaxConn,
➥CommitFlag);
• name—This is a name you can give your connection. Because you actually
store the connection in a variable, this name’s primary function becomes one
for debugging purposes.
• timeout—A numeric value for the number of seconds you give the instance to
connect.
After the connection has been made, you are able to perform the necessary processing
you require for your application. For more information on the methods available, check
entries for the Connection, Cursor, and database objects in Chapter 9.
U S E R S E S S I O N S A N D D ATA B A S E A C C E S S
An extensive discussion of how to manage user sessions and database connections
as various users access your application is beyond the scope of this book. However,
there are some items you should be aware of when performing these tasks.
You should know how database queries are handled. You should understand how
the information is returned from your specific database and how to process the
information.
08 0672321416 CH05 7/24/01 11:57 AM Page 172
1 7 2 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
You should also know how to appropriately manage user connections to your
application. It is possible your application will have to manage many connections
from many users at the same time. If your sessions and connections get crossed,
you might send the wrong information to the wrong user.
Maintaining and managing your user sessions and database connections can be a
very important factor and you should take great care when working with them.
E-Mail
Another feature that can be exploited and implemented within server-side JavaScript
applications is the ability to send mail. The properties and methods needed to perform
these tasks are contained in the SendMail object.
NOTE
Refer to the Chapter 9, “Server-Side,” for more information on the SendMail
object.
Using the SendMail object is very straightforward. Simply set the same properties con-
tained in the everyday e-mail you send and invoke the send() method. If an error is
encountered, it can be analyzed by using the error methods supplied. Listing 5.2 shows
an example use of this object to create a page for users to send e-mail. Figure 5.4 shows
what is displayed to the user when she encounters this page, and Figure 5.5 shows the
results of submitting a successful e-mail.
U s e s o f S e r v e r- S i d e J a v a S c r i p t 1 7 3
// If there was an error, give the user the e-mail address of who they
// should contact about the error, as well as the error code and
// message.
write(“Error sending your message. Please send e-mail to “);
write(myMail.Errorsto + “ with the following error message”);
write(“Error “ + myMail.errorCode() + “: “ + myMail.errorMessage());
}else{
// If there was not an error, tell the user they were successful.
write(“Your message was sent successfully!”);
}
}else{
// If this page was called and a form was not submitted, write the
// email form to the page for the user to use.
write(‘<form name=”myForm” method=”post”>’);
write(‘<table border=”1”><tr><td>’);
write(‘<table border=”0”>’);
write(‘<tr align=”left” valign=”top”>’);
write(‘<td><b>To:</b></td>’);
write(‘<td><input type=”text” name=”toAddress” size=”30”></td>’);
write(‘</tr>’);
write(‘<tr align=”left” valign=”top”>’);
write(‘<td><b>From:</b></td>’);
write(‘<td><input type=”text” name=”fromAddress” size=”30”></td>’);
write(‘</tr>’);
write(‘<tr align=”left” valign=”top”>’);
write(‘<td><b>Subject:</b></td>’);
write(‘<td><input type=”text” name=”subject” size=”30”></td>’);
write(‘</tr>’);
write(‘<tr align=”left” valign=”top”>’);
write(‘<td><b>Body:</b></td>’);
write(‘<td><textarea name=”body”’);
write(‘ cols=”60” rows=”10” wrap=”soft”></textarea>’);
write(‘</td>’);
write(‘</tr>’);
write(‘<tr align=”left” valign=”top”>’);
write(‘<TD colspan=2 align=”right”><input type=”submit”’);
write(‘ value=”Send Mail”>’);
write(‘</td>’);
write(‘</tr>’);
write(‘</table>’);
write(‘</td></tr></table>’);
write(‘</form>’);
}
</server>
</body>
</html>
08 0672321416 CH05 7/24/01 11:57 AM Page 174
1 7 4 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
Figure 5.4
Building an e-mail page for your applications.
Figure 5.5
The results of submitting an e-mail successfully.
As the example demonstrates, the SendMail object makes it easy to create a page
through which users can send mail. In a true, fully developed, Web-based application,
a programmer should add code to check for errors in the submission. This would be an
appropriate time to use client-side JavaScript to ensure that basic requirements, such
as syntactically correct e-mail addresses, are entered.
NOTE
Refer to Chapter 9 for more information on the File object.
Similar to the SendMail object, the use of the File object is straightforward. The
methods provided allow you to perform the various tasks needed on the files in your
file system.
08 0672321416 CH05 7/24/01 11:57 AM Page 175
U s e s o f S e r v e r- S i d e J a v a S c r i p t 1 7 5
Part of the functionality of working with these files allows a programmer to specify
how he wants to open the file. A file can be opened to read, write, append, or open in
binary mode. These options are specified in the open() method in the following form.
myFile.open(“option”);
NOTE
Refer to Chapter 9 for more information on the options that can be passed to this
method.
In your applications, you might want to display the contents of a file. This program
could be an administration application that reads a file and displays its contents on a
page. Listing 5.3 contains an application that displays the contents of a selected log file
on the file system.
Listing 5.3 Using the File Object to Display the Contents of a File
<html>
<head>
<title> Using the File object</title>
</head>
<body>
<server>
// If there was not an error, then open the file and display it.
write(‘<h3>The contents of ‘ + request.file + ‘ are as follows:</h3>);
while(!myLog.eof()){
write(myLog.readln());
}
}
}else{
// If this page was called then write the select box to the page for
// the user to use select which log they want to see.
08 0672321416 CH05 7/24/01 11:57 AM Page 176
1 7 6 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
In this example, a user has the ability to select a file for viewing. After submitting the
request, the example tries to open the file for reading. If it is unsuccessful, an error with
the filename is returned to the user. If the file opens, the contents are displayed in the
document.
Within IIS
On the IIS side of the fence, it is important to show how the language syntax differs
from Enterprise Server’s implementation, but remains true to the JavaScript language.
Within this section we will explore examples in the follow areas:
• Form submissions
• Session handling
Form Submissions
One of the nice things about JavaScript on the server-side within both the Enterprise
and IIS environments is the ease with which you can process form data. Within IIS this
is accomplished through the use of the Request object and its associated properties,
methods, and collections, which are detailed in Chapter 9.
To use this object, we must create a form that will pass some information. For sim-
plicity’s sake, we will prompt the user for his first and last name. Listing 5.4 contains
the HTML for this page.
U s e s o f S e r v e r- S i d e J a v a S c r i p t 1 7 7
Now that the form has been created, we must create the process.asp file to handle its
submission. Within this file, we will use the Write() method of the Response object to
output the values of the passed information. As we mentioned before, JScript has sev-
eral objects specific to their IIS implementation for processing data. The Response
object, which is detailed in Chapter 9.
We will use the Request.Form collection, which takes the name of the form element
you are trying to access. In our example, this will be for first and last. Listing 5.5
shows the code we can use to complete this task.
</script>
</body>
</html>
Server Variables
Another use of ASP is to access and use various server variables. For instance, on many
occasions a Web developer might need to determine the browser making the request.
He might want to direct the user agent to a specific site, or possibly post a warning mes-
sage.
In Listing 5.6 we use the Request.ServerVariables collection to access the
HTTP_USER_AGENT variable. After loading into a variable, we use the indexOf() method
to see if it is Internet Explorer. We then print out a message stating if it is Internet
Explorer or not followed by the entire user-agent string.
1 7 8 C h a p t e r 5 : J a v a S c r i p t o n t h e S e r v e r- S i d e
</script>
</body>
</html>
Moving On
Up until this point, we have covered the use of JavaScript on both the client and server-
side. For many of you, this represents the borders of what can be accomplished with
JavaScript. However, Chapter 6, “Windows Scripting,” will map out yet another envi-
ronment where JavaScript (or JScript rather) has taken hold—the Windows Script Host
environment.
09 0672321416 CH06 7/24/01 11:58 AM Page 179
Windows Scripting
CHAPTER 6
Windows Scripting
As many developers know, a big deficiency with Windows was
its lack of scripting support for automating tasks. Most other
operating systems had some type of built-in scripting engine.
Of course there was the batch file support in MS-DOS, but it
was very limited in its capability and not very useful in the
Windows environment.
Microsoft realized this limitation and introduced the Windows
Script specification within Internet Explorer 3.0. This provided
an interface for developers to build scripting engines for dif-
ferent browsers. From the Windows Script Interfaces grew
what is known today as the Windows Script Host.
</script>
</job>
The syntax of a WSH script is fairly simple. You enclose your functionality between
the opening and closing <job><script> tags. This is similar to a normal JScript or
JavaScript program. This script can be run a few different ways. These ways are dis-
cussed later in the chapter.
Architecture
The architecture of the Windows Script Host is fairly basic. There are only a few com-
ponents, which operate together, to make WSH scripts come alive. They are the script
itself, the Windows Shell, the Windows Registry, and the WSH engine. Figure 6.1
shows a diagram indicating how the components interact with each other to process the
script.
3. Determine appropriate
scripting engine from
IActiveScriptParse::ParseScriptText
2. Retrieve file
association for WSH
Registry
Figure 6.1
WSH architecture.
09 0672321416 CH06 7/24/01 11:58 AM Page 181
As you can see, the Windows Shell is the first component to encounter the script file.
The shell must then determine what this file is and does so by looking up the file asso-
ciation in the Registry. When it has this information, it can then pass the file to the
Windows Script Host Engine, which will use the IActiveScriptParse::
ParseScriptText method to determine whether this particular script will go to a
JavaScript engine, Visual Basic Script engine, Perl engine, and so on.
Object Model
The WSH is based on an object model hierarchy, which consists of 14 objects. Every
object stems from the WScript object (root object). The WSH Object model is shown
in Figure 6.2.
WScript
WshArguments
WshNamed
WshUnamed
WshController
WshRemote
WshRemoteError
WshNetwork
WshShell
WshShortCut
WshUrlShortCut
WshEnvironment
WshSpecialFolders
WshScriptExec
Figure 6.2
WSH object model hierarchy.
Not every object can be instantiated directly. The WScript object is available in every
WSH script and does not need to be instantiated. Other objects that can be instantiated
are the WshController, WshNetwork, and WshShell. To create these objects, use the
CreateObject method. All other child objects are indirectly created through the top-
level objects. The WSH object model exposes various COM objects, which can be
manipulated.
09 0672321416 CH06 7/24/01 11:58 AM Page 182
Objects
In the Object Model, you saw that many different objects comprise the Windows Script
Host. Each object has its own methods and properties associated with it. The main
objects from which all other minor objects stem are WScript, WshController,
WshNetwork, and WshShell.
The three most commonly used ones that we’ll discuss are WScript, WshShell, and
WshNetwork. They provide the majority of the top-level functionality for Windows
Script Host. Let us take a look at what each of them can do.
WScript
The WScript object is the root-level object from which all other objects are created. It
does not need to be instantiated and is available from any script file. It can be used for
a number of different tasks. You can use it as an informational object to get script file-
names, command-line arguments, and host information. It can also be used to create
objects, connect to and disconnect from objects, sink events, stop script execution, and
output information. Listing 6.1 displays the simplest form of using the WScript object
by using its Echo method to output the username.
As mentioned earlier, WScript can create any type of child object by using the
CreateObject method. Suppose that you wanted to create a new WshShell object. You
could do so by using the following line.
WshShellObj = WScript.CreateObject(“WScript.Shell”);
09 0672321416 CH06 7/24/01 11:58 AM Page 183
By now you are probably saying to yourself, “This is great, but what can I do with a
new WshShell object?” Keep reading and you will find out. (See Chapter 15,
“Windows Script Host,” for details on all the methods and properties associated with
the WScript object.)
WshShell
WshShell is a very useful object. It is used for manipulating the Windows Registry, cre-
ating shortcuts, starting new shell processes, and reading system information. It pro-
vides the ENVIRONMENT collection for your program, which allows you to access or
manipulate environment variables. (See Chapter 15 for details on all the methods and
properties associated with the WshShell object.)
Let’s look at a simple example in Listing 6.2, which creates a shortcut on the desktop
to the Amazon.com Web site. Using the CreateObject method of the root WScript
object, we can create a WshShell object named WshShellObj. Next we need to specify
that the shortcut is to be created on the desktop. To accomplish this, the
SpecialFolders method is used with “Desktop” as the parameter. Then we call the
CreateShortcut method and pass it the path for our shortcut. Finally the target path
for the shortcut is specified and the shortcut is saved.
</script>
</job>
WshNetwork
The WshNetwork object is used to perform many different network-related tasks. With
this object, you can add printer connections, obtain the computer name, map network
drives, set default printers, get user domains, and more. These types of tasks can be
very useful to a Windows network administrator. (See Chapter 15 for details on all the
methods and properties associated with the WshNetwork object.)
Let’s look at an example. Suppose that a new network printer has been added and the
network administrator wants to make it as easy as possible for users to add this printer
09 0672321416 CH06 7/24/01 11:58 AM Page 184
to their machine. The administrator could create a WSH script that all users can run to
add the printer to their machines. In Listing 6.3, we see the code to add a new printer.
</script>
</job>
Because user input is required for this particular script, it is recommended that the com-
mand line method, cscript.exe, is used to execute the script. (For more information on
differences between cscript.exe and wscript.exe, refer to the “Methods of Executing
Script” section). The user would specify his username and password as the arguments.
So assuming that the file is named “addPrinter.wsf”, it would be executed in an MS-
DOS Windows as follows:
cscript addPrinter.wsf Betty pass123
To execute a script generically from the command line, adhere to the following syntax:
wscript <filename> [//options] [arguments]
cscript <filename> [//options] [arguments]
Arguments should be separated with a space. WSH also supports drag-and-drop func-
tionality for arguments. You can drag and drop a file onto a WSH file, and—provided
that your script is written to parse the argument—it will treat your dragged filename as
an argument.
Windows-Based Scripts
Windows-based WSH scripts allow you to take advantage of the limited graphical
capabilities in WSH. This is particularly useful if your script requires visual user inter-
action. Keep in mind though that WSH doesn’t have very complex dialog boxes. The
graphical components are mostly limited to the tools available in VBScript or JScript
and pop-up dialogs.
There are three methods to execute a Windows-based script. The easiest is to locate
the script file in Windows Explorer and then double-click it to start. The second
method is to use the “Run” option from the Windows Start Menu. Choose the
WSH file in the “Run” option and then click the OK button to run. This is shown in
Figure 6.3. The third method is to run your script from the command line using
wscript.exe.
Any of these methods will work, and it is just a matter of personal preference. Let’s
take a look at the example in Listing 6.4.
09 0672321416 CH06 7/24/01 11:58 AM Page 186
Figure 6.3
Running script from the Run option.
</script>
</job>
If we were to run the script as a Windows-based script, the output would display a pop-
up window as shown in Figure 6.4.
Figure 6.4
The WSH pop-up display box.
Command-Based Scripts
WSH scripts can also be run from the command prompt. This is performed in the DOS
environment using the cscript executable. For example, if you wanted to run a script
called “hello.wsf”, you would type the following at a command prompt:
cscript hello.wsf
This example assumes that you are running the script from the same directory it is
located. Otherwise, the path to the file will need to be specified. Any arguments or
options passed to the script would be added after the script name. So, if you wanted to
use the Interactive mode options and pass a string as the first argument, your script call
would look similar to this:
cscript hello.wsf //I /arg1
suppressed to the same DOS Window in which the script is run. This is one of the dis-
advantages to the command-based scripts. No graphical components are provided. In
Figure 6.5, an example of the well-known Hello World program is executed displaying
the “Hello World” text to the screen.
Figure 6.5
Command-based output display.
Remote Scripting
With the latest version of WSH (version 5.6), it is possible to execute scripts remotely.
This allows you to remotely administer various automation tasks to computers across
the network. These tasks can even be executed simultaneously. You can remotely start,
stop, and get the status of WSH scripts. If an error occurs through the WshRemoteError
object, you can get the character, line number, error description, and even source code
for the error.
When a remote script is executed, the local machine actually copies the script to the
remote machine before execution. Before a remote script can be executed though, the
remote machine must be set up with the proper security settings. To set up remote
scripting on your machine, you need to follow three simple steps. First install WSH,
version 5.6 (if not already installed). The second step is to add yourself to the remote
machine’s local administrators group. The third step is to enable remote WSH through
the Poledit.exe executable. After this is taken care of, your machine is ready for
remote scripting!
There is a caveat to remote scripting. Remote scripting can only be run in the Windows
2000/NT environment. The Windows 9x scripting engine does not support this func-
tionality. This is because you cannot authenticate users who are not on the NT domain.
of the WshController with the CreateObject method. After you have the controller
object, you can use the CreateScript method to specify which script you want to exe-
cute remotely. This method actually returns a WshRemote object that can be used with
its execute() method to run the script remotely.
As with most computer programs, not all the scripts will run without errors. This is not
a problem though. The WSH object model includes the WshRemoteError object, which
can be used to obtain various error information. It is not an object that is directly instan-
tiated, but an object that is available as a child object of the WshRemote object.
// Catch events.
WScript.ConnectObject(RemoteScript, “RemoteScript_”);
// Catch errors.
function remote_Error(){
09 0672321416 CH06 7/24/01 11:58 AM Page 189
Moving On 189
</script>
</job>
Moving On
In this chapter, we have discussed many aspects of the Windows Script Host. We have
taken a look at the object model and a few specific objects in detail. We discussed the
two methods of running WSH scripts and even how to run scripts remotely. Although
the WSH 5.6 is still in beta version, a lot of things can be done with it. Look for even
more to be added as WSH continues to evolve.
09 0672321416 CH06 7/24/01 11:58 AM Page 190
10 0672321416 Part III 7/24/01 11:59 AM Page 191
PA R T I I I
JAVASCRIPT REFERENCE
7 Core Language 193
8 Client-Side 563
9 Server-Side 1175
CD-ROM
10 DOM Core CD:1403
11 DOM HTML CD:1479
12 DOM Events CD:1731
13 DOM CSS CD:1767
14 JScript RunTime CD:1823
15 Windows Script Host CD:1927
10 0672321416 Part III 7/24/01 11:59 AM Page 192
11 0672321416 CH07a 7/24/01 11:59 AM Page 193
Core Language
CHAPTER 7
Core Language
This chapter is a detailed reference of all the items and ele-
ments that make up the core JavaScript and JScript languages
as well as information in the ECMA-262, 3rd Edition standard
(ECMAScript). Because the details of JavaScript, JScript, and
ECMAScript varies slightly, so does each one’s definition of
core. Because of these variations, this chapter covers items that
are considered core in one standard, but might not exist in the
other standards. Every nuance of the languages is covered, giv-
ing you a one-stop place to get answers to all your questions.
Each entry includes version, environment support, syntax, a
description, and an example, as well as many other details.
The chapter is in alphabetical order, by objects, to provide you
with quick, easy access to the major parts of the language. The
methods, properties, functions, and event handlers of every
object appear alphabetically after the respective parent object,
using the simple dot notation that makes the language so easy
to learn. For example, the sin() function is found after the
Math object as Math.sin().
@_alpha
JScript3.0+
IE 4+
Syntax
@_alpha
Description
The @_alpha variable is used in JScript conditional compila-
tion to determine if a DEC Alpha processor is being used.
When the variable is not true, it behaves as NaN although it is
technically undefined.
11 0672321416 CH07a 7/24/01 11:59 AM Page 194
Example
Listing 7.1 alerts the user when a DEC Alpha processor is used.
// -->
</script>
@_jscript
JScript3.0+
IE 4+
Syntax
@_jscript
Description
The @_jscript variable is used in JScript conditional compilation to determine if
JScript is being used. This variable is always true.
Example
Listing 7.2 displays an alert box based on the value of the @_jscript variable.
// -->
</script>
@_jscript_build
JScript3.0+
IE 4+
11 0672321416 CH07a 7/24/01 12:00 PM Page 195
Syntax
@_jscript_build
Description
The @_jscript_build variable is used in JScript conditional compilation to hold the
build number of the JScript scripting engine.
CAUTION
Before accessing the @_jscript_build variable, use the @cc_on statement to define
the variable. More information about the @cc_on statement can be found later in
this chapter.
Example
Listing 7.3 uses the @_jscript_build variable to display the build number of the
JScript engine that is being used.
// -->
</script>
@_jscript_version
JScript3.0+
IE 4+
Syntax
@_jscript_version
Description
The @_jscript_version variable is used in the JScript conditional compilation to hold
the JScript version number in major.minor format.
CAUTION
Before accessing the @_jscript_version variable, use the @cc_on statement to
define the variable.
11 0672321416 CH07a 7/24/01 12:00 PM Page 196
Example
Listing 7.4 uses the @_jscript_version variable to display the JScript version that is
being used.
// -->
</script>
@_mac
JScript3.0+
IE 4+
Syntax
@_mac
Description
The @_mac variable is used in JScript conditional compilation to determine if an Apple
Macintosh system is being us ed. When the variable is not true, it behaves as NaN
although it is technically undefined.
Example
Listing 7.5 alerts the user when an Apple Macintosh system is used.
@if (@_mac)
alert(“You are using an Apple Macintosh system.”);
@else
alert(“You are NOT using an Apple Macintosh system.”);
@end
// -->
</script>
11 0672321416 CH07a 7/24/01 12:00 PM Page 197
@_mc680x0
IE 4+
JScript3.0+
Syntax
@_mc680x0
Description
The @_mc680x0 variable is used in JScript conditional compilation to determine if a
Motorola 680×0 processor is being used. When the variable is not true, it behaves as
NaN although it is technically undefined.
Example
Listing 7.6 alerts the user when a Motorola 680×0 processor is used.
@if (@_mc680x0)
alert(“You are using a Motorola 680x0 processor.”);
@else
alert(“You are NOT using a Motorola 680x0 processor.”);
@end
// -->
</script>
@_PowerPC
IE 4+
JScript3.0+
Syntax
@_PowerPC
Description
The @_PowerPC variable is used in JScript conditional compilation to determine if a
Motorola PowerPC processor is being used. When the variable is not true, it behaves
as NaN although it is technically undefined.
Example
Listing 7.7 alerts the user when a Motorola PowerPC processor is used.
11 0672321416 CH07a 7/24/01 12:00 PM Page 198
@if (@_PowerPC)
alert(“You are using a Motorola PowerPC processor.”);
@else
alert(“You are NOT using a Motorola PowerPC processor.”);
@end
// -->
</script>
@_win16
IE 4+
JScript3.0+
Syntax
@_win16
Description
The @_win16 variable is used in JScript conditional compilation to determine if a win16
system is being used. When the variable is not true, it behaves as NaN although it is
technically undefined.
Example
Listing 7.8 alerts the user when a win16 system is used.
@if (@_win16)
alert(“You are using a 16 bit Windows system.”);
@else
alert(“You are NOT using a 16 bit Windows system.”);
@end
// -->
</script>
@_win32
JScript3.0+
IE 4+
11 0672321416 CH07a 7/24/01 12:00 PM Page 199
Syntax
@_win32
Description
The @_win32 variable is used in JScript conditional compilation to determine if a win32
system is being used. When the variable is not true, it behaves as NaN although it is
technically undefined.
Example
Listing 7.9 alerts the user when a win32 system is used.
@if (@_win32)
alert(“You are using a 32 bit Windows system.”);
@else
alert(“You are NOT using a 32 bit Windows system.”);
@end
// -->
</script>
@_x86
JScript3.0+
IE 4+
Syntax
@_x86
Description
The @_x86 variable is used in JScript conditional compilation to determine if a Intel
processor is being used. When the variable is not true, it behaves as NaN although it is
technically undefined.
Example
Listing 7.10 alerts the user when an Intel processor is used.
@if (@_x86)
alert(“You are using an Intel processor.”);
11 0672321416 CH07a 7/24/01 12:00 PM Page 200
// -->
</script>
@cc_on
JScript3.0+
IE 4+
Syntax
@cc_on
Description
The @cc_on statement is used to activate JScript conditional compilation in the script-
ing engine.
Example
Listing 7.11 shows where the @cc_on statement would be used within JScript code to
get the JScript version.
// -->
</script>
@if
JScript3.0+
IE 4+
Syntax
@if (condition1)
statement1
@elif (condition2)
statement2
11 0672321416 CH07a 7/24/01 12:00 PM Page 201
CoreLanguage 201
@else
statement3
@end
Description
The @if statement operates much the same as a typical if conditional statement, but it
evaluates compiled variables and has a slightly different syntax. If the expression in
condition1 evaluates to true, statement1 is executed. Otherwise, the condition2 is
evaluated to determine whether statement2 should be evaluated. The @elif statement
operates the same as the JavaScript else...if statement, even though it looks differ-
ent. You can use as many @elif statements as needed or none at all. Only one @else
statement should be used to catch conditions that don’t meet any of the previous con-
ditionals. Similar to the @elif statement, the @else statement is optional. The @end
statement is required at the end of all @if conditionals.
Example
Listing 7.12 displays a message based on the type of processor being used.
// -->
</script>
@set
JScript3.0+
IE 4+
Syntax
@set @varName = value
11 0672321416 CH07a 7/24/01 12:00 PM Page 202
Description
The @set property allows the creation of JScript variables. The name of the variable
must start with an ampersand character. If the variable is used before being defined, its
value will be NaN.
Example
Listing 7.13 uses the @set property to create a custom compiled variable called
@number and assigns the number 25 to the variable. The variable is then used to display
a sentence in the browser.
Listing 7.13 Create Custom Compiled Variable Using the @set Property
<script type=”text/jscript” language=”JScript”>
<!--
// -->
</script>
Operators
- (Subtraction)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
num1 - num2
Description
The number to the right of the operator is subtracted from the number to the left of the
operator. If either operand is a string, an attempt is made to convert the string to a num-
ber before performing the operation.
Example
The code in Listing 7.14 creates a string out of the number “45”. The string is
converted to a number before being subtracted from the number 25. The result of the
subtraction operation (20) is displayed.
11 0672321416 CH07a 7/24/01 12:00 PM Page 203
Operators 203
//Subtract 25 from 45
answer = aString - 25;
document.write(“answer = (45-25)<br>”);
//Answer is equal to 20
document.write(“answer = “,answer);
// -->
</script>
- (Unary Negation)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
-num
Description
The unary negation operator changes the sign of num. When negating a variable, the
contents of the variable do not change; only the value returned is negated. If the
operand is a string, it is converted to a number before performing the unary negation
operation.
Example
The code in Listing 7.15 creates a string “36”. The string is converted to a number
before being negated. The result of the negation is -36.
// -->
</script>
-- (Decrement)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
--variable
variable--
Description
The pre-decrement operator, defined in the first syntactical definition, decrements
variable by 1. The new decremented value is returned by the operation.
The second syntactical definition contains the post-decrement operator. This operator
is similar to the pre-decrement operator in that it decrements variable by 1. However,
the original value is returned by the operation before being decremented.
In both cases, if the operand is a string, it is converted to a number before performing
the operation.
Example
Listing 7.16 demonstrates how the pre-decrement and post-decrement operators work.
Notice that the variable num holds a string that is converted before performing the
decrement operations. The result from executing this code is shown in Figure 7.1.
Operators 205
// -->
</script>
Figure 7.1
The difference between pre-decrement and post-decrement.
! (Logical NOT)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
!operand
Description
The ! operator inverts the boolean value returned from the operand. So, if operand
evaluates to true, the result of the operation is false. If the operand evaluates to
false, the result is true. When the operand evaluates to a non-Boolean value, it is
converted to true or false before performing the inversion.
Example
In Listing 7.17 the character “1” is converted to the Boolean true before inverting the
value with the NOT operand. The variable theReverseTruth is assigned false.
11 0672321416 CH07a 7/24/01 12:00 PM Page 206
// -->
</script>
!= (Not Equal)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
expression1 != expression2
Description
The not equal operator compares the first expression to the second expression. If the
expressions are not equal, true is returned from the operation. If they are equal, false
is returned.
JavaScript and Microsoft JScript interpreters attempt to convert the expressions to the
same data type before evaluating the not equal operation using the following rules:
• true is converted to the number 1, and false is converted to zero before being
compared.
• If either of the operands is NaN, the equality operator returns false.
• Null and undefined are equal.
• Null and undefined are not equal to 0 (zero), “” (empty string), or false.
• If a string and a number are compared, attempt to convert the string to a num-
ber and then check for equality.
• If an object and a string are compared, attempt to convert the object to a string
and then check for equality.
• If an object and a number are compared, attempt to convert the object to a
number and then check for equality.
• If both operands of an equality operation are objects, the address of the two
objects are checked for equality.
11 0672321416 CH07a 7/24/01 12:00 PM Page 207
Operators 207
CAUTION
In JavaScript 1.2, the decision was made to NOT do type conversion on the
operands of the not equal operator. JavaScript reverted back to using type conver-
sion with this operator in 1.3 and later.
Example
In the following example, the string “523” is converted to a number (except in
JavaScript 1.2, in which type conversion is not performed), so that two numbers are
compared. Because the left operand is equal to the right operand, the phrase “The
string 523 is EQUAL to the number 523” is written to the browser window.
// -->
</script>
!== (Non-Identity)
JavaScript 1.3+, ECMAScript 3E+, JScript 1.0+
Nav4.06+, IE 3+, Opera5+
Syntax
expression1 !== expression2
Description
The non-identity operator compares the first expression to the second expression. If the
value on the left is not equal to the value on the right side of the operator, true is
returned from the operation. If the values are equal, false is returned.
11 0672321416 CH07a 7/24/01 12:00 PM Page 208
NOTE
No type conversion is performed on the expressions before the comparison is
made.
Example
In Listing 7.19, the string “8765” is NOT converted to a number, so the two expres-
sions are not the same type. Because the two operands are not the same type, they are
not equal, so the phrase “The string 8765 is NOT equal to the number 8765” is
written to the browser window.
// -->
</script>
% (Modulus)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
num1 % num2
Description
The modulus operator begins the same as the division operator, by dividing the left
value by the right; but instead of returning the normal result of division, only the
remainder is returned by the operation. If either operand is a string, an attempt is made
to convert the string to a number before performing the operation.
11 0672321416 CH07a 7/24/01 12:00 PM Page 209
Operators 209
Example
In Listing 7.20, the variable answer is assigned the value 1 because 7 is divided by the
number 2 three times plus a remainder of 1. This remainder is stored in the variable
answer.
// -->
</script>
%= (Modulus Assignment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
variable %= value
Description
The modulus assignment operator divides the value stored in the left variable by the
right value. The remainder is returned by the operation and stored in the variable to the
left of the operator. If value is a string, an attempt is made to convert the string to a
number before performing the modulus and assignment.
Example
In Listing 7.21, the variable answer is initially assigned the value 17. The number 17
is divided by the number 3. The remainder portion (modulos) of the result of the divi-
sion is stored in the variable answer, overwriting the number 3.
// -->
</script>
Syntax
num1 & num2
Description
The bitwise AND operator looks at the integer numbers on both sides of the operator as
32-bit binary numbers. The bitwise AND (&) operator individually evaluates each of the
32 bits representing the number on the left of the operator to the corresponding bit of
the number on the right of the operator using the truth table shown in Table 7.1. The
32-bit binary result of the logical AND operation is converted to an integer value and
returned from the bitwise AND operation.
Example
The code in Listing 7.22 uses the bitwise AND operator on the numbers 11 and 6. The
result of the bitwise AND operation is 2.
// answer is equal to 2
answer = 11 & 6;
11 0672321416 CH07a 7/24/01 12:00 PM Page 211
Operators 211
// -->
</script>
Syntax
expression1 && expression2
Description
The logical AND operator returns true if the expression on the left and the expression
on the right of the operator evaluate to true. If either the left, right, or both evaluates
to false, the result of the operation is false.
Be sure to note that the implementation of the logical AND operator in JavaScript is
more complex than what was just mentioned. The AND operation begins by evaluating
the left expression. If the left expression evaluates to false, the basic logic of the AND
operator is complete, so the right expression is never evaluated. But if the left expres-
sion evaluates to true, the right expression must be evaluated to determine the final
result of the AND operation. In either case, the final result returned by the AND operation
is actually determined by the result of the last expression to be evaluated.
Example
Listing 7.23 demonstrates the complications associated with the logical AND operator.
The first expression evaluates to false, causing the logical AND operation to evaluate to
false and the message “The && evaluated FALSE!” is displayed. Because the first
expression evaluates to false, the second expression, which assigns the number 5 to
the variable x, is not evaluated and x remains equal to 3.
// x is still equal to 3
document.write(“x=”,x,”<br>”);
// -->
</script>
Syntax
variable &= value
Description
The bitwise AND plus assignment operator looks at the integer numbers on both sides of
the operator as 32-bit binary numbers. The bitwise AND (&) operator individually eval-
uates each of the 32 bits representing the number on the left of the operator to the cor-
responding bit of the number on the right of the operator using the truth table shown in
Table 7.2. The 32-bit binary result of the bitwise AND operation is converted to an inte-
ger value and stored in the variable to the left of the operator.
Example
In Listing 7.24, the bitwise AND plus assignment operator is used on the numbers 12 and
6 to generate a result of 4.
Operators 213
// 6 = 00000000000000000000000000000110
// 4 = 00000000000000000000000000000100
// -->
</script>
* (Multiplication)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
num1 * num2
Description
The multiplication operator (*) multiplies the left operand by the right operand. If
either of the operands is a string, an attempt is made to convert the string to a number.
Example
In Listing 7.25, the string “5” is converted to a number before being multiplied by the
number 6. The result of 30 is displayed in the browser window.
// -->
</script>
*= (Multiplication Assignment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
11 0672321416 CH07a 7/24/01 12:00 PM Page 214
Syntax
variable *= value
Description
The number stored in the variable to the left of the operator is multiplied by the num-
ber to the right of the operator. The result of the multiplication is written into the vari-
able to the left of the operand. If either of the operands is a string, it is converted to a
number.
Example
In Listing 7.26, the string “5” is converted to a number before being multiplied by the
number 7. The result of the multiplication, which is 35, is stored in the variable x.
// -->
</script>
, (Comma)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, IE 3+, Opera3+
Syntax
expression1, expression2,...,expressionN3
Description
The comma allows multiple expressions to be evaluated as one expression. The only
value returned from this operation is the return value of the right-most expression.
Example
In Listing 7.27, the comma is used to execute multiple assignment statements on
one line. The number 3 is stored in y, and then 9 is stored in z. Because z=9 is the last
11 0672321416 CH07a 7/24/01 12:00 PM Page 215
Operators 215
statement in the group of comma-separated statements, its value is returned and stored
in the variable x. The final values stored in each variable is displayed (x=9, y=3, z=9).
// -->
</script>
/ (Division)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
num1 / num2
Description
The left number is divided by the right number. If either of the operands is a string, it
is converted to a number.
Example
In Listing 7.28, the string “168” is converted to a number before being divided by the
number 14. The result (12) of the division is stored in the variable x and displayed in
the browser window.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:00 PM Page 216
/* / (Multi-line Comment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, IE 3+, Opera3+
Syntax
/* comments */
Description
Every character that appears within the two comment tags is ignored by the JavaScript
interpreter. Placing the tags on different lines allows comments to span multiple lines.
Be careful not to nest comment tags within comment tags because this will lead to
errors.
Example
Listing 7.29 demonstrates the use of multiple-line comments in JavaScript code.
document.write(“<h2>Multi-line Comments</h2>”);
// -->
</script>
// (Comment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, IE 3+, Opera3+
Syntax
// comment
Description
Every character that appears after this tag and on the same line as the tag is ignored by
the JavaScript interpreter.
Example
Listing 7.30 demonstrates the use of the single line comment in JavaScript code.
11 0672321416 CH07a 7/24/01 12:00 PM Page 217
Operators 217
// -->
</script>
/= (Division Assignment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
variable /= value
Description
The number stored in the variable on the left of the operator is divided by the number
on the right. The result of the division overwrites the value in the variable on the left
of the operator. If either of the operands is a string, it is converted to a number.
Example
In Listing 7.31, the string “8” is converted to a number before being used to divide by
the number 32. The result of the division, which is 4, is stored in the variable x.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:00 PM Page 218
?: (Conditional)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
expression ? v value1 : value2
Description
An expression that evaluates to a Boolean is always placed to the left of the question
mark (?). If the expression evaluates to true, value1 is returned from the operation. If
the expression evaluates to false, value2 is returned.
The same functionality of the conditional operator can be achieved with an if...else
statement.
Example
In Listing 7.32, the conditional operator is shown along with a similar standard if
statement. Both the conditional operator and the if statement have the same result,
except that the conditional operator takes up less space. The string “The hamburgers
are done!” are displayed for both operators.
//Standard if statement
if (doneCooking == “YES”)
message1 = “The hamburgers are done!”;
else
message1 = “The hamburgers are still cooking.”;
// Print the message to the screen. Notice both messages are the same!
document.write(“The if statement returns: “,message1,”<br>”);
document.write(“The conditional operator returns: “,message2);
11 0672321416 CH07a 7/24/01 12:00 PM Page 219
Operators 219
// -->
</script>
Syntax
num1 ^ num2
Description
The bitwise exclusive OR (XOR) operator looks at the integer numbers on both sides of
the operator as 32-bit binary numbers. The bitwise exclusive OR uses a special version
of the logical OR operator, called exclusive OR, to evaluate each individual bit of a binary
number.
Each of the 32 bits representing the number on the left of the operator is compared to
the corresponding bit of the number on the right of the operator using the exclusive OR
truth table shown in Table 7.3. The 32-bit binary result of the operation is converted to
an integer value and returned.
Example
The code in Listing 7.33 uses the bitwise exclusive OR operator on the numbers 6 and
3. The result of executing the code is the number 5, which is written to the browser win-
dow.
Syntax
variable ^= value
Description
The bitwise exclusive OR assignment operator (^=) looks at the integer numbers on both
sides of the operator as 32-bit binary numbers. The bitwise exclusive OR assignment
operator uses a special version of the logical OR operator, called exclusive OR, to eval-
uate each individual bit of a binary number.
Each of the 32 bits representing the number on the left of the operator is compared to
the corresponding bit of the number on the right of the operator using the exclusive OR
truth table shown in Table 7.4. The 32-bit binary result of the operation is converted to
an integer value and stored in the variable to the left of the operator.
Example
Listing 7.34 uses the bitwise exclusive OR assignment operator on the numbers 10 and
6 to generate the result 12.
Operators 221
// -->
</script>
| (Bitwise OR)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
num1 | num2
Description
The bitwise OR operator looks at the integer numbers on both sides of the operator as
32-bit binary numbers. The truth table of the logical OR (||) operator, shown in Table
7.5, is used to individually evaluate each of the 32 bits representing the number on the
left of the operator to the corresponding bit of the number on the right of the operator.
The 32-bit binary result of the bitwise OR operation is converted to an integer value and
returned from the operation.
Example
The code in Listing 7.35 uses the bitwise OR operator on the numbers 9 and 5.
Executing the code displays the number 13 in the browser window.
// -->
</script>
|| (Logical OR)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
expression1 || expression2
Description
The logical OR operator returns true if the left operand, right operand, or both operands
evaluates to true. If both the operands evaluate to false, the result of the operation is
false.
The implementation of the logical OR operator in JavaScript and JScript is more com-
plex than what was just mentioned. The OR operation begins by evaluating the left
operand. If the left operand evaluates to true, the basic logic of the OR operator is com-
plete, so the right operand is never evaluated. But if the left operand evaluates to false,
the right operand must be evaluated to determine the final result of the OR operation. In
either case, the final result returned by the OR operation is actually the result of the last
operand to be evaluated.
Example
Listing 7.36 demonstrates the complications associated with the logical OR operator.
The first expression evaluates to true, causing the logical OR operation to evaluate to
true. Because the first expression evaluates to true, the second expression, which
assigns the number 7 to the variable x, is not evaluated so x remains equal to 8.
Operators 223
else
{
document.write(“The || evaluated FALSE!<br>”);
}
// x is equal to 8.
document.write(“x=”,x,”<br>”);
// -->
</script>
|= (Bitwise OR Assignment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
variable |= value
Description
The bitwise OR assignment operator looks at the integer numbers on both sides of the
operator as 32-bit binary numbers. The logical OR (||) operator individually evaluates
each of the 32 bits representing the number on the left of the operator to the corre-
sponding bit of the number on the right of the operator. The 32-bit binary result of the
logical OR operation is converted to an integer value and stored in the variable on the
left of the operator.
Example
Listing 7.37 uses the bitwise OR assignment operator on the numbers 2 and 5 to gener-
ate the number 7.
// -->
</script>
~ (Bitwise NOT)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
~operand
Description
The bitwise NOT operator begins by looking at the number to the right of the operator
as a 32-bit binary number. Each bit of the given number is reversed so that all ones
become zeros and all zeros become ones. The 32-bit binary result is converted to an
integer value and returned from the bitwise NOT operation.
The result of inverting a number can be very confusing because of the way signed num-
bers are represented. Just remember that applying the bitwise NOT operator to a positive
number will return the original number with the sign changed, minus one.
Example
The code in Listing 7.38 demonstrates the use of the bitwise NOT operator. Notice that
the result of the operation is –3 , which is the original number (2) with the sign reversed
(–2) minus 1.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:00 PM Page 225
Operators 225
+ (Addition)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
operand1 + operand2
Description
The addition operator provides two types of functionality depending on the data type
of the operands. The first type of functionality is simple addition, in which the value
on the left of the addition operator is added to the value on the right. For this type of
addition, both operands must be numbers.
The second type of functionality provided by the addition operator is string concate-
nation. If either of the operands is a string, string concatenation is performed by first
converting any non-string operand to a string. String concatenation is then performed
by appending the string to the right of the operator to the end of the string located to
the left of the operator.
Example
Listing 7.39 demonstrates the addition of numbers as well as string concatenation.
Compare the Listing 7.39 to the result of executing the code as seen in Figure 7.2 to
understand how addition is handled with various variable types.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:00 PM Page 226
Figure 7.2
Using the addition operator to add numbers and concatenate strings.
++ (Increment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
++variable (Pre-Increment)
variable++ (Post-Increment)
Description
The pre-increment operator increments variable by 1. The new incremented value is
returned by the operation.
The post-increment operator is similar to the pre-increment operator in that it incre-
ments variable by 1. However, the original value is returned by the operation before
being incremented.
In both cases, if the operand is a string, it is converted to a number before performing
the operation.
Example
Listing 7.40 demonstrates how the pre-increment and post-increment operators work.
Notice that the variable num holds a string that is converted before performing the incre-
ment operation. The result of executing this code is shown in Figure 7.3.
Operators 227
// -->
</script>
Figure 7.3
The difference between pre-increment and post-increment.
+= (Addition Assignment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
variable += value
Description
The addition assignment operator provides two types of functionality depending on
the data type of the operands. The first type of functionality is simple addition in
which the value stored in the variable on the right of the addition assignment operator
is added to the value on the left. The result of the addition overwrites the value stored
in the variable on the left of the operator. If either of the operands is not a number or
string, it will be converted to a number.
11 0672321416 CH07a 7/24/01 12:00 PM Page 228
The second type of functionality provided by the addition assignment operator is string
concatenation. If either of the operands is a string, string concatenation is performed
by first converting any non-string operand to a string. String concatenation is then per-
formed by appending the string to the right of the operator to the end of the string
located to the left of the operator. The new string is stored in the variable on the left of
the operator.
Example
In Listing 7.41, the addition assignment operator is used to add two numbers together
as well as concatenate two strings.
// -->
</script>
Syntax
num1 < num2
Description
The less than operator compares the value on the left of the operator to the value on the
right. If the value on the left is less than the value on the right, true is returned from
the operation. If the value on the left of the operator is greater than or equal to the value
on the right, false is returned. If either of the operands is not a number or string, it will
be converted to a number before performing the comparison.
11 0672321416 CH07a 7/24/01 12:00 PM Page 229
Operators 229
Example
In Listing 7.42, the string “45” is converted to a number before performing the com-
parison. Because the number 45 is less than the number 68, the phrase “45 is less
than 68” is returned.
// -->
</script>
Syntax
num1 << num2
Description
The shift left operator looks at the integer on the left of the operator as a 32-bit binary
number. The number of positions specified by num2 shifts all the bits of num1 to the left.
As the bits are shifted to the left, zeros are filled in on the right. Because the number
can only be 32-bits long, the extra bits on the left are lost. The 32-bit binary result of
the shifting operation is converted to an integer value and returned from the shift left
operation.
NOTE
The result generated from the shift left operator can be quickly calculated by multi-
plying the number by 2 raised to the x power, where x is the number of positions
shifted.
11 0672321416 CH07a 7/24/01 12:00 PM Page 230
Example
Listing 7.43 shifts the bits that make up the number 2 to the left two positions, which
results in the number 8.
// -->
</script>
Syntax
variable <<= num
Description
The shift left assignment operator looks at the integer stored in the variable to the left
of the operator as a 32-bit binary number. All the bits in this number are shifted to the
left by the number of positions specified by the integer to the right of the operator. As
the bits are shifted to the left, zeros are filled in on the right. Because the number can
only be 32-bits long, the extra bits on the left are lost. The 32-bit binary result of shift-
ing operation is converted to an integer value and stored in the variable to the left of
the operator.
Example
In Listing 7.44, the 32-bit binary version of the number 3, which is stored in the vari-
able x, is shifted two positions to the left. The result of this operation, the number 12,
is stored in the variable x.
Operators 231
// -->
</script>
Syntax
num1 <= num2
Description
The less than or equal operator compares the number on the left of the operator to the
number on the right. If the number on the left is less than or equal to the number on the
right, true is returned from the operation. If the number on the left of the operator is
greater than the number on the right, false is returned.
Example
In Listing 7.45, the string “34” would be converted to a number before performing the
comparison. Because the number 34 is less than the number 77, the phrase “34 is
less than or equal to 77” would be returned.
// -->
</script>
= (Assignment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
variable = value
Description
The value to the right of the operator is stored in the variable to the left of the opera-
tor.
Example
In Listing 7.46, the assignment operator is used to assign various types of values to
variables. The type of operator is then used to determine the type value stored in the
variables. The types are then displayed in the browser (x is a number, y is a string, and
z is a boolean).
//Number
x = 456; //x contains a number.
document.write(“x is a “,typeof x,”<br>”);
//String
y = new String(“Hello”) //y contains a String.
document.write(“y is a “,typeof y,”<br>”);
//Boolean
z = true; //z contains a Boolean.
document.write(“z is a “,typeof z);
// -->
</script>
-= (Subtraction Assignment)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
11 0672321416 CH07a 7/24/01 12:00 PM Page 233
Operators 233
Syntax
variable -= value
Description
The number to the right of the operator is subtracted from the number stored in the vari-
able to the left of the operator. The result of the operation overwrites the value stored
in the variable to the left of the operator. If either operand is a string, an attempt is made
to convert the string to a number before performing the subtraction.
Example
In Listing 7.47, the string “878” is converted to a number before the subtraction oper-
ation begins. The number 55 is subtracted from 878 and the result, 823, is stored in the
variable answer.
// -->
</script>
== (Equal)
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
expression1 == expression2
Description
The equal operator compares the value on the left of the operator to the value on the
right of the operator. If the values are equal, true is returned from the operation. If the
values are not equal, false is returned from the operation.
JavaScript attempts to convert the operands to the same data type before comparing the
values for all versions of JavaScript except 1.2. JavaScript adheres to the following
rules when performing type conversion:
11 0672321416 CH07a 7/24/01 12:00 PM Page 234
CAUTION
In JavaScript 1.2, the decision was made to NOT do type conversion on the
operands of the equal operator. JavaScript reverted back to using type conversion
with this operator in 1.3 and later.
Example
In Listing 7.48, the string “749” is converted to a number (except in JavaScript 1.2, in
which type conversion is not performed) so that two numbers are compared. Because
the left operand is equal to the right operand, the phrase “The string 749 is EQUAL
to the number 749” is written to the browser window.
// -->
</script>
=== (Identity)
JavaScript 1.3+, ECMAScript 3E+, JScript 1.0+
Nav4.06+, IE 3+, Opera5+
11 0672321416 CH07a 7/24/01 12:00 PM Page 235
Operators 235
Syntax
expression1 === expression2
Description
The identity operator compares the first operand to the second operand. If the value on
the left is equal to the value on the right side of the operator, true is returned from
operation. If the values are not equal, false is returned.
NOTE
No type conversion is performed on the operands before the comparison is made.
Example
In Listing 7.49, the string “326” is NOT converted to a number, so the two operands
are not the same type. Because the two operands are not the same type, they are not
equal, so the phrase “The string 326 is NOT equal to the number 326” is writ-
ten to the browser window.
Syntax
num1 > num2
Description
The greater than operator compares the value on the left of the operator to the value on
the right. If the value on the left is greater than the value on the right, true is returned
from the operation. If the value on the left of the operator is less than or equal to the
11 0672321416 CH07a 7/24/01 12:00 PM Page 236
value on the right, false is returned. If either of the operands is not a number, it is con-
verted to a number before performing the comparison.
Example
In Listing 7.50, the string “112” would be converted to a number before performing the
comparison. Because the number 112 is greater than the number 68, the phrase “112
is greater than 68” is returned.
// -->
</script> >
Syntax
variable >= value
Description
The greater than or equal operator compares the number on the left of the operator to
the number on the right. If the number on the left is greater than or equal to the num-
ber on the right, true is returned from the operation. If the number on the left of the
operator is less than the number on the right, false is returned.
Example
In Listing 7.51, the string “95” would be converted to a number before performing the
comparison. Because the number 95 is greater than the number 44, the phrase “95 is
greater than or equal to 44” is returned.
Operators 237
// -->
</script>
Syntax
num1 >> num2
Description
The shift right with sign operator looks at the integer to the left of the operator, num1,
as a 32-bit binary number. All the bits in this number are shifted to the right by the
number of positions specified by num2. As the bits are shifted to the right, either ones
or zeros are filled in on the left. If the original number is positive, zeros are added to
the left side of the binary number. On the other hand, if the original number is nega-
tive, ones are used. Because the result can only be 32-bits long, the extra bits on the
right are lost. The 32-bit binary result of shifting operation is converted to an integer
value and returned from the shift right with sign operation.
NOTE
The result generated from the shift right with sign operator can be quickly calcu-
lated by dividing the number by 2 raised to the x power, where x is the number of
positions shifted. Discard the remainder.
Example
Listing 7.52 shifts the bits that make up the number 14 to the right two positions, which
results in the number 3. The code also shifts the bits that make up the number -14 to
the right one position, which results in the number -2.
//--------------------------------------
document.write(“<br>”);
// -->
</script>
Syntax
variable >>= v value
Description
The shift right with sign assignment operator (>>=) looks at the integer to the left of
the operator as a 32-bit binary number. All the bits in this number are shifted to the
right by the number of positions specified by the integer to the right of the operator. As
the bits are shifted to the right, either ones or zeros are filled in on the left. If the orig-
inal number is positive, zeros are added to the left side of the binary number. On the
other hand, if the original number is negative, ones are used. Because the result can
only be 32-bits long, the extra bits on the right are lost. The 32-bit binary result of shift-
ing operation is converted to an integer value and stored in the variable to the left of
the operator.
11 0672321416 CH07a 7/24/01 12:00 PM Page 239
Operators 239
Example
In Listing 7.53, the 32-bit binary version of the number 15, which is stored in the vari-
able x, is shifted one position to the right. The result of this operation, the number 7, is
stored in the variable x.
Listing 7.53 Using the Shift Right with Sign Assignment Operator
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Syntax
num1 >>> num2
Description
The shift right zero fill operator looks at the integer to the left of the operator as a 32-
bit binary number. All the bits in this number are shifted to the right by the number of
positions specified by the integer to the right of the operator. As the bits are shifted to
the right, zeros are filled in on the left, regardless of the sign of the original integer.
Because the result can only be 32-bits long, the extra bits on the right are lost. The 32-
bit binary result of this shifting operation is converted to an integer value and returned
from the shift right zero fill operation.
Example
Listing 7.54 shifts the bits that make up the number 13 to the right one position, which
results in the number 6. The number 1073741822 results from shifting the bits that
make up the number –8 two positions to the right.
11 0672321416 CH07a 7/24/01 12:00 PM Page 240
//--------------------------------------
document.write(“<br>”);
// -->
</script>
Syntax
variable >>>= value
Description
The shift right zero fill assignment operator (>>>=) looks at the integer to the left of the
operator as a 32-bit binary number. All the bits in this number are shifted to the right
by the number of positions specified by the integer to the right of the operator. As the
bits are shifted to the right, zeros are filled in on the left, regardless of the sign of the
original integer. Because the result can only be 32-bits long, the extra bits on the right
are lost. The 32-bit binary result of this shifting operation is converted to an integer
value and stored in the variable to the left of the operator.
11 0672321416 CH07a 7/24/01 12:00 PM Page 241
Operators 241
Example
In Listing 7.55, the 32-bit binary version of the number –6, which is stored in the vari-
able x, is shifted one position to the right. The result of this operation, the number
1073741822, is stored in the variable x.
Listing 7.55 Using the Shift Right Zero Fill Assignment Operator
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
abstract
JavaScript 1.2+, ECMAScript 2E+, JScript 5+
Nav4+, NES 3+, IE5+, Opera5+
Syntax
Reserved Keyword
Description
The abstract keyword has not been implemented in JavaScript to date, but has been
reserved for future use.
Example
This keyword has not been implemented, therefore no example is provided.
ActiveXObject
JScript3.0+
IE4+
Syntax
var variable = new ActiveXObject(serverName.typeName,location)
11 0672321416 CH07a 7/24/01 12:00 PM Page 242
Description
The ActiveXObject creates a reference to an object that is connected to another appli-
cation or programming tool through automation interfaces. The arguments used by this
object are listed in Table 7.6.
Example
Listing 7.56 uses the ActiveXObject to create a multiplication table in a Microsoft
Excel document. Excel will be started automatically.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:00 PM Page 243
Operators 243
Arguments
JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+
Nav3+, IE3+, Opera5+
Syntax
arguments
arguments [index]
Description
The Arguments object is an array that contains all the arguments passed into the cur-
rently executing function as well as a few other useful properties. This object is auto-
matically created and initialized when a function is invoked and goes out of scope as
soon as the code function finishes executing. To access arguments passed into a func-
tion, simply use array brackets to specify an index. Table 7.7 lists the properties asso-
ciated with the Argument object.
NOTE
To use the Arguments object, you do not specify the function using dot notation
as you might expect. This is because this object is different from the Function.
arguments[] array associated with a Function object. Using this Arguments object
gives you the ability to access the arguments of functions that have no name.
Example
In Listing 7.57, a function is created to display an individual’s favorite food in an alert
box. The function is called when the buttons are pressed. The arguments passed to this
function are accessed within the function with the Arguments object array brackets.
<form>
<input type=”button”
value=”Meredith”
OnClick=displayFood(this,”pizza”)>
11 0672321416 CH07a 7/24/01 12:00 PM Page 244
// -->
</script>
</body>
</html>
Arguments.callee
JavaScript 1.2+, ECMAScript 1E+, JScript 5.5+
Nav4+, IE5.5+, Opera5+
Syntax
arguments.callee
Description
The callee property of the Arguments object contains the function that is currently
executing. This is useful if the function has no name.
11 0672321416 CH07a 7/24/01 12:00 PM Page 245
Operators 245
Example
In Listing 7.58, a function is created to display an individual’s favorite food in an alert
box. The function is called when the buttons are clicked. The code that makes up the
executing function is displayed using the callee property.
<form>
<input type=”button”
value=”Meredith”
OnClick=displayFood(this,”pizza”)>
<input type=”button”
value=”Allison”
OnClick=displayFood(this,”beans”)>
<input type=”button”
value=”BayLeigh”
OnClick=displayFood(this,”carrots”)>
<input type=”button”
value=”Michael”
OnClick=displayFood(this,”corn”)>
<input type=”button”
value=”Rob”
OnClick=displayFood(this,”hotdogs”)>
</form>
Arguments.caller
JavaScript 1.2+
Nav4+
Syntax
arguments.caller
Description
The caller property of the Arguments object contains the Arguments object of the call-
ing function. If the given function was not executed from within another function, null
is stored in this property.
Example
Listing 7.59 creates two functions. One displays an individual’s favorite food in an alert
box, whereas the other displays the number of arguments associated with the calling
function. Anytime a button is clicked, an alert box displays the favorite food. This func-
tion then calls the second function to display an alert box saying two arguments were
passed into the first function.
<form>
<input type=”button”
value=”Meredith”
OnClick=displayFood(this,”pizza”)>
<input type=”button”
value=”Allison”
OnClick=displayFood(this,”beans”)>
<input type=”button”
value=”BayLeigh”
OnClick=displayFood(this,”carrots”)>
<input type=”button”
value=”Michael”
OnClick=displayFood(this,”corn”)>
<input type=”button”
value=”Rob”
OnClick=displayFood(this,”hotdogs”)>
</form>
11 0672321416 CH07a 7/24/01 12:00 PM Page 247
Operators 247
//Display the number of arguments in the function that calls this function.
function displayArgLength()
{
var argLengthStr = “The calling function contained “;
argLengthStr += arguments.caller.length;
argLengthStr += “ arguments.”;
alert(argLengthStr);
}
displayArgLength();
}
// -->
</script>
</html>
Arguments.length
JavaScript 1.1+, ECMAScript 1E+, JScript 5.5+
Nav3+, IE5.5+, Opera5+
Syntax
arguments.length
Description
The length property of the Arguments object contains the number of arguments that
were passed into the function to which the Arguments object is associated. If fewer
arguments are passed in than are specified in the definition of the function, the length
property will only contain the number of arguments passed into the function. This num-
ber matches the number of elements in the arguments array associated with the
Arguments object.
11 0672321416 CH07a 7/24/01 12:00 PM Page 248
Example
In Listing 7.60, the length property of the Arguments object is used to process any
number of arguments passed into the displayFood() function.
<form>
<input type=”button”
value=”Meredith”
OnClick=displayFood(this,”pizza”,”salad”,”cake”)>
<input type=”button”
value=”Allison”
OnClick=displayFood(this,”beans”,”potatoes”)>
<input type=”button”
value=”BayLeigh”
OnClick=displayFood(this,”carrots”)>
<input type=”button”
value=”Michael”
OnClick=displayFood(this,”corn”,”beans”)>
<input type=”button”
value=”Rob”
OnClick=displayFood(this,”hotdogs”)>
</form>
Operators 249
// -->
</script>
Array
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera3+
Syntax
var variable = new Array()
var variable = new Array(int)
var variable = new Array(arg1, ..., argN)
Description
Although arrays can be created with the basic JavaScript object, the Array object pro-
vides a much easier way to create and manage arrays.
Table 7.8 lists the argument and return values associated with this object’s constructors.
These constructors create a new array and, in two cases, initialize the Array object
based on the arguments passed in the parameter list. The constructor that has no argu-
ments sets the length property to 0.
Table 7.8 Arguments and Return Values Associated with the Array
Object
Type Item Description
Arguments int When the array constructor contains one argument,
an array is created, and its length property is set to
the value int.
arg1,...argN When the parameter list of the array constructor
contains more than one argument, an array is cre-
ated and the array is populated with the argu-
ments. The array length property is set to the
number of arguments in the parameter list.
Returns The newly created array is returned from the con-
structor.
Table 7.9 lists the properties and methods used by the Array object.
Example
Listing 7.61 creates an array of numbers using the Array constructor. Once created, the
elements are displayed on the screen using bracket notation ([]).
Operators 251
// -->
</script>
</html>
Array.concat( )
JavaScript 1.2+, ECMAScript 3E+, JScript 3.0+
Nav4+, NES3+, IE 4+, Opera5+
Syntax
array.concat (arg1,...argN)
Description
The concat() method adds the elements listed in the parameter list to the end of the
existing array and returns the result. The original is not changed by this method. Should
any of the arguments be Array, the elements of that array are concatenated to the array
that called the method.
Table 7.10 lists the argument and return values associated with this method.
Example
Listing 7.62 uses the concat() method to display the total inventory of two grocery
store shelves. Notice how the multidimensional arrays wereconcatenated together in
Figure 7.4.
Figure 7.4
Concatenate the items on two grocery store shelves.
11 0672321416 CH07a 7/24/01 12:00 PM Page 253
Operators 253
Array.constructor
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera3+
Syntax
array.constructor
Description
The constructor property of the Array object is used to create the object’s prototype.
Example
Listing 7.63 demonstrates the constructor property as it relates to the Array object.
Array.index
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE 4+, Opera4+
Syntax
array.index
Description
The index property is a read-only property that contains the position of a regular
expression match within a string. This property only appears in the Array object that is
returned from the following regular expression related methods:
• RegExp.exec()
• String.match()
• String.replace()
Example
Listing 7.64 creates a regular expression string that contains the search string “red”.
The exec() method is used to find the regular expression within a string. The index
property is then used to display “The word ‘red’ was found at position 4”, which
contains the position character position (4) within the string where the word “red” was
found.
11 0672321416 CH07a 7/24/01 12:00 PM Page 254
Listing 7.64 Using the index Property to Display the Position of a Match
<script type=”text/javascript” language=”JavaScript”>
<!--
myReg=/red/;
myArray = myReg.exec(“The red ball.”);
document.write(“The word ‘red’ was found at position “,myArray.index);
// -->
</script>
Array.input
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE 4+, Opera4+
Syntax
array.input
Description
The input property is a read-only property that contains the string against which the
regular expression was matched. This property only appears in the Array object that is
returned from the following regular expression related methods:
• RegExp.exec()
• String.match()
• String.replace()
Example
Listing 7.65 creates a regular expression string that contains the search string “red”.
The exec() method is used to find the regular expression within a string. The input
property is then used to display the string that was searched.
Listing 7.65 Using the index Property to Display the Regular Expression
<script type=”text/javascript” language=”JavaScript”>
<!--
myReg=/red/;
myArray = myReg.exec(“The red ball.”);
document.write(“The word red was found in the string ‘“, myArray.input, “‘“);
// -->
</script>
Array.join()
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera3+
Syntax
array.join()
array.join(string)
11 0672321416 CH07a 7/24/01 12:00 PM Page 255
Operators 255
Description
The join() method converts all the elements of the array to strings and then concate-
nates all the strings into one string. If an argument is provided in the parameter list, it
is used to separate the elements in the string returned by the method. Table 7.11 lists
the argument and return values associated with this method.
Example
Listing 7.66 creates an array of fruits. The contents of this array are displayed on the
screen using the join() method. A dash is specified as the delimiter used to separate
the array elements when they are written to the screen as a string.
// -->
</script>
Array.lastIndex
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE 4+
Syntax
array.lastIndex
11 0672321416 CH07a 7/24/01 12:00 PM Page 256
Description
The lastIndex property is a read-only property that contains the position following the
last character in a regular expression match. This property only appears in the Array
object that is returned from the following regular expression related methods:
• RegExp.exec()
• String.match()
• String.replace()
Example
Listing 7.67 creates a regular expression string that contains the search string “red”.
The exec() method is used to find the regular expression within a string. The
lastIndex property is then used to display the number 7, which is the position fol-
lowing the word “red” that was found in the string.
Array.length
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera3+
Syntax
array.length
Description
The length property holds the number of elements in the array. This property is a
read/write variable. If the length property is overwritten with a number that is larger
than the original number, new elements are added to the end of the array and assigned
undefined values. If the length property is overwritten with a number that is smaller
than the original number, elements at the end of the array are lost.
Example
Listing 7.68 creates an array of coins. The number of coins in the array is then reduced
from 4 to 3 by modifying the length property so the array contains only three ele-
ments. Because the quarter was the last element in the array, it was removed when the
length property was changed.
11 0672321416 CH07a 7/24/01 12:00 PM Page 257
Operators 257
// -->
</script>
Array.pop()
JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+
Nav4+, NES3+, IE5.5+, Opera5+
Syntax
array.pop()
Description
The pop()method “pops” elements off the end of the array by deleting the last element
of the array and setting the array’s length property to one less than its current value.
The element popped off the end of the array is returned from the method. Table 7.12
shows the return value associated with this method.
Example
In Listing 7.69, an array of pages is created to represent a stack of papers. The pop()
method removes and returns the top-most paper. After the pop() method is executed,
the variable currentPaper contains “Page3”, and the array’s length property is 2.
Listing 7.69 Using the pop() Method to Remove Elements from the End
of an Array
<script type=”text/javascript” language=”JavaScript”>
<!--
11 0672321416 CH07a 7/24/01 12:00 PM Page 258
// -->
</script>
Array.prototype
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera5+
Syntax
Array.prototype.property
Array.prototype.method
Description
The prototype property allows you to add new properties and methods (designated as
property/method in the Syntax section) to the Array object that can be used through-
out your code.
Example
In Listing 7.70, the prototype property is used to provide a pop() method for work-
ing with arrays. Even though a pop() method is already available, a new pop() method
will be created. This method overrides the functionality of the Array.pop() method.
The new pop() method is used at the end of the code to remove an the “Peach” ele-
ment from the array of juice flavors. The contents of the flavorArray are displayed
before and after the new pop() method is executed to show that the “Peach” flavor was
removed.
Listing 7.70 Assigning a New Method to the Array Object with the
Prototype Property
<script type=”text/javascript” language=”JavaScript”>
<!--
//This function removes the last element in the array. This last
//element is returned from the function.
function pop()
{
if(this.length != 0)
{
var lastElement = this[this.length-1]; //Get last element.
this.length = this.length-1; //Remove last element from array.
return(lastElement); //Return the last element.
11 0672321416 CH07a 7/24/01 12:00 PM Page 259
Operators 259
}
}
//Display the contents of the flavor array after the pop() method.
document.write(“The flavor array now contains: “);
document.write(flavorArray.join(‘, ‘),”<br>”);
// -->
</script>
Array.push()
JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+
Nav4+, NES3+, IE5.5+, Opera5+
Syntax
array.push (arg1,...argN)
Description
The push() method “pushes” the elements specified in the parameter list on to the end
of the array in the order they were listed. Table 7.13 shows the arguments and return
values associated with this method.
Example
In Listing 7.71, an array of pages is created to represent a stack of papers. The push()
method puts two more pages on the end of the array. After the push() method is
executed, the variable currentPaper contains “Page4”, and the array’s length prop-
erty is 4.
Listing 7.71 Using the push() Method to Add Elements to the End of an
Array
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Array.reverse()
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera5+
Syntax
array.reverse()
Description
The reverse() method reverses the order of the elements in the array according to the
array index numbers.
Example
Listing 7.72 creates an array representing a line of people. The reverse() method is
called to reverse the order of the names so that Polly is the first element, Leslie is the
second element, and Cheryl is the last element.
Operators 261
// -->
</script>
Array.shift()
JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+
Nav4+, NES3+, IE5.5+, Opera5+
Syntax
array.shift()
Description
The shift()method deletes and returns the first element of the array. Once deleted, all
the remaining elements are shifted down one spot, so the first position is filled by the
element that was previously in the second position. Table 7.14 shows the return value
associated with this method.
Example
Listing 7.73 creates an array representing people waiting for a table at a restaurant. The
shift() method pulls the first name off the list and shifts all the other names down one
position. After the shift() method is executed, the variable personToSeat now con-
tains Kent. Jon is shifted to lineOfPeople[0] and Jeremy to lineOfPeople[1].
Listing 7.73 Removing the First Element from an Array with the shift()
Method
<script type=”text/javascript” language=”JavaScript”>
<!--
Array.slice()
JavaScript 1.2+, ECMAScript 3E+, JScript 3.0+
Nav4+, NES3+, IE 4+, Opera5+
Syntax
array.slice (start)
array.slice(start, stop)
Description
The slice() method returns a new array that contains the elements of the original
array starting at position start and ending at the element position before stop. If no
stop position is specified, the new array will contain the elements of the original array,
starting at the position stated in start through the end of the array. Table 7.15 lists the
arguments and return values associated with this method.
Example
In Listing 7.74, an array of numbers is created. A new array of numbers is derived from
the original array of numbers using the slice() method. After the slice() method is
executed, the array newNumArray contains the elements 23 and 759.
11 0672321416 CH07a 7/24/01 12:00 PM Page 263
Operators 263
// -->
</script>
Array.sort()
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera5+
Syntax
array.sort()
array.sort (function)
Description
The sort()method rearranges the elements of the array based on a sorting order. Table
7.16 lists the argument associated with this method. If the method has no parameters,
JavaScript attempts to convert all the elements of the array to strings and then sort them
alphabetically. If the array should be sorted some other way, a function must be pro-
vided to handle the new sorting algorithm.
As mentioned before, if the array should be sorted some other way than jscriptbetically,
a function must be provided to handle the new sorting algorithm. The function spec-
ified must operate based on the following rules:
• The function must accept two arguments that are to be compared.
• The function must return a number indicating the order of the two arguments in
relation to each other.
11 0672321416 CH07a 7/24/01 12:00 PM Page 264
• If the first argument should appear before the second argument, a number less
than zero should be returned from the function.
• If the first argument should appear after the second argument, a number greater
than zero should be returned from the function.
• If both arguments are equivalent, zero should be returned from the function.
When the function specified by the sort() method returns zero, signifying that the
arguments are equal, the arguments remain in the same order relative to each other after
the function has been called.
Example
To help solidify how this method operates, Listing 7.75 demonstrates how to use the
method to sort an array based on the number of characters in each argument. Notice
how the sort() method changes the order of the elements of the array in Figure 7.5.
<!--
//Display the contents of an array.
function contentsOfArray(theArray)
{
document.write(“the array contains:<br>”);
//Access each element in the array.
for(i=0; i<theArray.length; i++)
{
document.write(“Position “,i,” = “,theArray[i],”<br>”);
}
}
Operators 265
Figure 7.5
Sort the array elements based on the character length of each element.
Array.splice()
JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+
Nav4+, IE5.5+, Opera5+
Syntax
array.splice(start,delete,arg3,...,argN)
Description
The splice() method provides a way for elements to be either added or deleted from
the array. When the delete parameter contains a number other than zero, the elements
beginning at start and ending at start+delete are deleted from the array. If delete
is zero, no elements are deleted. All elements from start to the end of the array are
deleted when delete is not specified. If arguments follow the delete parameter, they
are added to the array as elements beginning at the position specified by start.
Existing elements are shifted up to allow room for the new elements.
NOTE
There was a bug in Navigator 4 when just one element was deleted from an array.
Rather than returning an array that contained the deleted element, the actual ele-
ment was returned from the method. In addition, when no elements were deleted
from the array, null was returned instead of an empty array.
Table 7.17 lists the arguments and return values associated with the splice() method.
11 0672321416 CH07a 7/24/01 12:00 PM Page 266
Example
To help understand how the splice() method works, Listing 7.76 uses the delete and
insert capabilities of the method to simulate a food order at a restaurant. In Figure 7.6,
notice how the hamburger was replaced with a hot dog based on the customer’s change
in appetite.
Operators 267
Figure 7.6
The food order changed using the splice() method.
Array.toSource()
JavaScript1.3+, JScript3.0
Nav4.06+, IE4
Syntax
array.toSource()
Description
The toSource() method returns one string representing the source of the Array object.
The string that is returned contains all the elements in the array separated with com-
mas. The entire string is enclosed with brackets ([]) to show it is an array. If another
array is contained within an array, its contents are also part of the string with its own
set of brackets.
Example
Listing 7.77 creates an Array object of colors and an Array object of numbers. The
array of numbers is included in the array of colors. The toSource() method is then
applied to the Array object to return the source string.
[“Blue”, “Green”, “Red”, [3, 6, 7]]
Listing 7.77 Accessing the source of an Array object with the toSource()
Method
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Array.toString()
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, IE 4+, Opera5+
Syntax
array.toString()
Description
The toString()method returns one string that contains all the elements in the array
separated with commas. You might be wondering why anyone would need this method
when the join() method can do this and more. The reason is that the toString()
method is what JavaScript uses to automatically convert an array to a string when the
array is used in string context.
CAUTION
JavaScript 1.2 did not use commas to separate the elements. Instead, each element
was enclosed in square brackets.
Table 7.18 shows the return value associated with the toString() method.
Example
Listing 7.78 creates an array of colors and then uses the toString() method to put the
contents of the array into a string which is then displayed in the browser.
Operators 269
Array.unshift()
JavaScript 1.2+, ECMAScript 3E+, JScript 5.5+
Nav4+, NES3+, Opera5+
Syntax
array.unshift(arg1,...argN)
Description
The unshift() method adds the arguments listed in the parameter list to the front of
the array as new elements. Existing elements are shifted up to allow room for the new
elements. Table 7.19 lists the arguments and return values associated with this method.
Example
Listing 7.79 creates an array of school grades. Two new grades, 100 and 93, are added
to the front of the array using the unshift() method. After the unshift() method has
executed, the grades array contains [100,93,95,87], and newLength contains the new
length of the array, 4.
// -->
</script>
Array.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
Array.unwatch (property)
Description
The unwatch() method of the Array object, is used to turn off the watch on a particu-
lar property specified by property.
Example
Listing 7.80 shows how the unwatch() method is used to stop watching the user
defined property p.
myArray.p = 2;
myArray.unwatch(“p”);
myArray.p = 3;
myArray.watch(“p”,alertme);
myArray.p = 4;
// -->
</script>
11 0672321416 CH07a 7/24/01 12:00 PM Page 271
Operators 271
Array.valueOf()
JavaScript1.1+, ECMAScript 1E+, JScript3.0+
Nav3+, NES2+, IE4+, Opera3+
Syntax
array.valueOf ()
Description
The valueOf() method returns the primitive value of the object. In terms of an instance
of an Array object, this method returns the array elements separated by commas. If an
array contains another array, the contents are flattened when this method is used.
Example
Listing 7.81 creates an Array object of colors and an Array object of numbers. The
array of numbers is included in the array of colors. Because the valueOf() method
returns the actual elements in the array, “Blue,Green,Red,3,6,7” is written to the
browser.
Listing 7.81 Using the valueOf() Method to Return the Value of the
Array Object
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Array.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
Array.watch(property,function)
11 0672321416 CH07a 7/24/01 12:00 PM Page 272
Description
The watch()method of the Array object is used to turn on the watch of a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 7.82 shows how the watch() method is used to start watching the user-defined
property p.
myArray.p = 2;
// -->
</script>
Automation
JScript3.0+
IE4+
Syntax
Core JScript Object
Description
Automation objects are objects that are connected to other applications or program-
ming tools through automation interfaces. These objects give JScript developers access
to properties and methods applications from within the JScript code. See
ActiveXObject() and GetObject() for details on using automation objects.
Example
See ActiveXObject() and GetObject() for examples of using automation objects.
boolean
JavaScript1.2, ECMAScript 2E+, JScript 5+
Nav4+, NES3+, IE5+, Opera5+
11 0672321416 CH07a 7/24/01 12:00 PM Page 273
Operators 273
Syntax
Reserved Keyword
Description
The boolean keyword has not been implemented in server-side JavaScript to date, but
has been reserved for future use. Note that this keyword is not the same as the Boolean
object.
Example
This keyword has not been implemented; therefore, no example is provided.
Boolean
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera5+
Syntax
var variable = new Boolean(value)
var variable = Boolean(value)
Description
The Boolean object is a wrapper object that holds a primitive boolean value, as well as
provides a method for converting the value to a string. A primitive boolean can have
only one of two states: true or false. Internally, JavaScript uses the number 1 to rep-
resent true and 0 to represent false, but provides the toString() method to return the
strings “true” and “false”.
A Boolean object is created with the Boolean() constructor and the new operator or by
the Boolean() function. The argument, return value, and method associated with this
object are listed in Table 7.20.
Example
In Listing 7.83, a Boolean object and a primitive Boolean value are created. There are
a couple of key points to notice when examining the results generated by the code,
shown in Figure 7.7. First, the Boolean() constructor converts the string “false” to
the Boolean value true. Second, boolObj is a Boolean object, whereas boolVal is just
a variable holding a primitive Boolean value.
// -->
</script>
Figure 7.7
Boolean object versus primitive boolean value.
11 0672321416 CH07a 7/24/01 12:00 PM Page 275
Operators 275
Boolean.constructor
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera3+
Syntax
Boolean.constructor
Description
The constructor property of the Boolean object is used to create the object’s proto-
type.
Example
Listing 7.84 demonstrates the constructor property as it relates to the Boolean object.
Boolean.prototype
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, IE 4+, Opera5+
Syntax
Boolean.prototype.property
Boolean.prototype.method
Description
The prototype property allows you to add new properties and methods to the Boolean
object that can be used throughout your code.
Example
In Listing 7.85, the prototype property is used to create a new method, called
letter(), which can be used by all Boolean objects. The letter() method uses the
letterBoolean() function to return true or false based on the status of the object.
11 0672321416 CH07a 7/24/01 12:00 PM Page 276
Listing 7.85 Assigning a New Method to the Boolean Object with the
prototype Property
<script type=”text/javascript” language=”JavaScript”>
<!--
//This function returns the string “T” or “F” based on the value stored in the
//Boolean object that uses this function.
function letterBoolean()
{
if(this == true)
return(“T”);
else
return(“F”);
}
//Display the state of the Boolean object using the letter method.
document.write(“myBooleanObj is set to “,myBooleanObj.letter()); //Return “T”
// -->
</script>
Boolean.toSource()
JavaScript1.3+, JScript3.0
Nav4.06+, IE4
Syntax
boolean.toSource()
Description
The toSource() method returns one string representing the source of the Boolean
object. The string that is returned is enclosed in parentheses.
Example
Listing 7.86 creates a Boolean object to represent true. The toSource() method is
then applied to the Boolean object to return the source string “(new Boolean(true))”.
Operators 277
// -->
</script>
Boolean.toString()
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, IE 4+, Opera5+
Syntax
boolean.toString()
Description
The toString()method returns the string representation (“true” or “false”) of the
primitive Boolean value stored in the Boolean object. The return value associated with
this object is listed in Table 7.21.
Example
In Listing 7.87, the toString() method is used to force a comparison of strings rather
than Boolean values. Without the toString() method, the if comparison would find
the Boolean value not equal to the string value.
// -->
</script>
Boolean.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
Boolean.unwatch (property)
Description
The unwatch() method of the Boolean object is used to turn off the watch on a partic-
ular property specified by property.
Example
Listing 7.88 shows how the unwatch() method is used to stop watching the user-
defined property p.
myBoolean.p = 2;
myBoolean.unwatch(“p”);
myBoolean.p = 3;
myBoolean.watch(“p”,alertme);
myBoolean.p = 4;
// -->
</script>
11 0672321416 CH07a 7/24/01 12:00 PM Page 279
Operators 279
Boolean.valueOf()
JavaScript1.1+, ECMAScript 1E+, JScript3.0+, Nav3+, NES2+, IE4+, Opera3+
Syntax
boolean.valueOf()
Description
The valueOf() method returns the primitive value of the object. In terms of an instance
of a Boolean object, this method returns a Boolean value contained in the object.
Example
Listing 7.89 creates a Boolean object representing true. Because the valueOf()
method returns the Boolean value in the object, “true” is written to the browser.
Listing 7.89 Using the valueOf() Method to Return the Value of the
Boolean Object
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Boolean.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
Boolean.watch (property,function)
Description
The watch()method of the Boolean object is used to turn on the watch of a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 7.90 shows how the watch() method is used to start watching the user-defined
property p.
11 0672321416 CH07a 7/24/01 12:00 PM Page 280
myBoolean.p = 2;
// -->
</script>
break
JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+
Nav3+, IE 3+, Opera3+
Syntax
break label;
Description
The keyword break provides a way to exit out of loop structures and switch condi-
tionals prematurely. Most of the time, the word break appears on a line by itself, but
there are times when a label will follow the keyword (see Table 7.22). When a label is
used, code execution completely breaks out of the area designated by label and pro-
ceeds to the code that follows the area. To label a statement, simply place the label
name followed by a colon (:) in front of the code that needs to be broken out of dur-
ing code execution.
Example
Listing 7.91 demonstrates the effect of using labels and break statements when work-
ing with nested loops. Figure 7.8 shows the result of executing this code.
Operators 281
//Break out of inner loop the 3rd time through the inner loop.
if (counter2 == 3)
break;
//Break out of the outer loop the 3rd time through the outer loop.
if (counter1 == 3)
break forLoop1;
}
}
document.write(“All done!”);
//-->
</script>
Figure 7.8
Using labels and the break statement in nested loops.
Notice how the break statement with no label, in Figure 7.8, breaks out of just the inner
loop. When the break statement is used with a label, JavaScript knows at what level to
break.
byte
JavaScript1.2+, ECMAScript 2E+, JScript 5+
Nav4+, NES3+, IE5+, Opera5+
Syntax
Reserved Keyword
11 0672321416 CH07a 7/24/01 12:00 PM Page 282
Description
The byte keyword has not been implemented in server-side JavaScript to date, but has
been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
case
JavaScript1.2+, ECMAScript 2E+, JScript3.0+
Nav4+, NES3+, IE4+, Opera5+
Syntax
Reserved Keyword
Description
The case keyword has not been implemented in server-side JavaScript to date, but has
been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
char
JavaScript1.2+, ECMAScript 2E+, JScript 5+
Nav4+, NES2+, IE5+, Opera5+
Syntax
Reserved Keyword
Description
The char keyword has not been implemented in server-side JavaScript to date, but has
been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
class
JavaScript1.2+, ECMAScript 1E+, JScript3.0+
Nav4+, NES3+, IE4+, Opera5+
Syntax
Reserved Keyword
Description
The word class is reserved for future use, so there is no definition at this time.
11 0672321416 CH07a 7/24/01 12:00 PM Page 283
Operators 283
Example
No example can be provided because class is reserved for future use.
const
JavaScript1.2, ECMAScript 1E+, JScript 5+
Nav4+, NES3+, IE5+, Opera5+
Syntax
Reserved Keyword
Description
The word const is reserved for future use, so there is no definition at this time.
Example
No example can be provided because const is reserved for future use.
continue
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, IE 4+, Opera3+
Syntax
continue label;
Description
The continue statement forces the execution of the code within a loop to continue at
the beginning of the loop. Normally, the continue keyword appears on a line by itself,
but there are times when a label will follow the keyword (see Table 7.23). When a label
is used, code execution immediately jumps to the beginning of the loop designated by
the label and begins executing code.
The beginning of a loop varies depending on the type of loop structure. Table 7.24
shows where each looping structure jumps to when a continue structure is encountered.
CAUTION
There is a bug in Navigator 4 that causes the expression in parentheses following
the while keyword in a do...while loop to not get executed when jumped to
using a continue statement. Instead, execution of code starts at the top of loop,
after the continue statement. This problem can be avoided by using a while loop.
To label a statement, simply place the label name followed by a colon (:) in front of
the code where code execution needs to continue.
Example
Listing 7.92 demonstrates the use of labels and continue. This example is a bit com-
plicated, so take time to compare Listing 7.79 to the output in Figure 7.9. Notice how
the phrase “Bottom of innerLoop” was not printed after the “Continue at top of
innerLoop.” because code execution jumped back to beginning of the inner-most loop.
When a label was attached to the continue keyword, code execution jumped back to
the beginning of the loop labeled outerLoop.
Operators 285
if (counter1 == 2)
{
document.write(“Continue at top of outerLoop.<br>”);
continue outerLoop;
}
document.write(“Bottom of innerLoop.<br>”);
}
document.write(“Bottom of outerLoop.<br>”);
}
document.write(“All done!”);
//-->
</script>
Figure 7.9
The result of using the continue statement.
Date
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
var variable = new Date();
var variable = new Date(milliseconds1);
var variable = new Date(string)
var variable = new Date(year, month, day, hours, minutes, seconds,
milliseconds2)
Description
The Date object represents all aspects of a date and time from year to milliseconds. If
arguments are provided when creating the Date object, the new object will contain the
11 0672321416 CH07a 7/24/01 12:01 PM Page 286
date specified; otherwise the object will be set to the current date. The arguments and
methods are listed in Table 7.25.
CAUTION
If the Date() constructor can also be called as a function by excluding the new
operator. With this is done a string representation of the date is returned rather
than a Date object
Table 7.25 Arguments and Methods Associated with the Date Object
Type Item Description
Argument constructor Specifies the function that creates the
Boolean object’s prototype.
milliseconds1 The desired date is calculated from the
number of milliseconds between midnight
January 1, 1970 GMT and the desired
date.
string The desired date is calculated from the
string representation. The format of the
string should match the parse() method
of the Date object.
year A four-digit representation of the year.
month The month represented as an integer,
where 0 represents January and 11 repre-
sents December.
day The day of the month represented as an
integer from 1 to 31. Optional argument.
hours The hour represented as an integer where
0 represents 12 a.m. (midnight) and 23
represents 11 p.m. Optional argument.
minutes The minutes in the hour represented as an
integer from 0 to 59. Optional argument.
seconds The seconds in the minute represented as
an integer from 0 to 59. Optional argu-
ment.
milliseconds2 The milliseconds in the second represented
as an integer from 0 to 999. Optional argu-
ment.
Methods getDate() Returns the day of the month.
getDay() Returns the day of the week.
getFullYear() Returns the year in local time with four
digits.
getHours() Returns the hour.
getMilliseconds() Returns the milliseconds.
11 0672321416 CH07a 7/24/01 12:01 PM Page 287
Operators 287
Example
Listing 7.93 demonstrates how to create Date objects using various arguments in the
Date() constructor.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 289
Operators 289
Date.constructor
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera3+
Syntax
Date.constructor
Description
The constructor property of the Date object is used to create the object’s prototype.
Example
Listing 7.94 demonstrates the constructor property as it relates to the Date object.
Date.getDate()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getDate ()
Description
The getDate()method returns the day of the month expressed as an integer from
1 to 31.
Example
The code in Listing 7.95 displays the current day of the month expressed as an integer
from 1 to 31 using the getDate() method.
Listing 7.95 Using the getDate() Method to Return the Day of the
Month
<script type=”text/javascript” language=”JavaScript”>
<!--
11 0672321416 CH07a 7/24/01 12:01 PM Page 290
// -->
</script>
Date.getDay()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getDay()
Description
The getDay()method returns the day of the week expressed as an integer from 0
(Sunday) to 6 (Saturday).
Example
The code in Listing 7.96 uses the getDay() method to return the day of the week
expressed as an integer. This number is then converted to a string representation of the
day of the week.
Listing 7.96 Using the getDay() Method to Return the Day of the Week
<script type=”text/javascript” language=”JavaScript”>
<!--
Operators 291
case 3:
day=”Wednesday”;
break;
case 4:
day=”Thursday”;
break;
case 5:
day=”Friday”;
break;
case 6:
day=”Saturday”;
break;
default:
day=”Invalid day”;
}
return day;
}
//Create a Date object that contains the current date and time.
theDate = new Date();
Date.getFullYear()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.getFullYear()
Description
The getFullYear()method returns the year in local time as a full four-digit number.
Example
The code in Listing 7.97 displays the year using the getFullYear() method.
//Create a Date object that contains the current date and time.
theDate = new Date();
11 0672321416 CH07a 7/24/01 12:01 PM Page 292
// -->
</script>
Date.getHours()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getHours()
Description
The getHours() method returns the hour portion of the date expressed as an integer
from 0 (12:00 a.m. midnight) to 23 (11:00 p.m.).
Example
The code in Listing 7.98 displays the current hour as an integer from 0 to 23 using the
getHours() method.
Listing 7.98 Using the getHours() Method to Return the Current Hour
<script type=”text/javascript” language=”JavaScript”>
<!--
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getMilliseconds()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.getMilliseconds()
Description
The getMilliseconds() method returns the millisecond portion of the date expressed
as an integer from 0 to 999.
11 0672321416 CH07a 7/24/01 12:01 PM Page 293
Operators 293
Example
The code in Listing 7.99 displays the milliseconds in the Date object using the
getMilliseconds() method.
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getMinutes()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getMinutes()
Description
The getMinutes() method returns the minutes portion of the Date object expressed as
an integer from 0 to 59.
Example
The code in Listing 7.100 displays the current minute using the getMinutes() method.
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 294
Date.getMonth()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getMonth()
Description
The getMonth() method returns the month portion of the Date object expressed as an
integer from 0 (January) to 11 (December).
Example
The code in Listing 7.101 displays the current month using the getMonth() method.
Operators 295
break;
case 7:
month=”August”;
break;
case 8:
month=”September”;
break;
case 9:
month=”October”;
break;
case 10:
month=”November”;
break;
case 11:
month=”December”;
break;
default:
month=”Invalid month”;
}
return month;
}
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getSeconds()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getSeconds()
Description
The getSeconds() method returns the seconds portion of the Date object expressed as
an integer from 0 to 59.
Example
The code in Listing 7.102 displays the current seconds using the getSeconds()
method.
11 0672321416 CH07a 7/24/01 12:01 PM Page 296
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getTime()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getTime()
Description
The getTime() method returns the equivalence of the Date object in milliseconds. The
milliseconds are expressed as an integer representing the number of milliseconds
between midnight January 1, 1970 (GMT) to the date and time specified in the Date
object.
TIP
It is much easier to compare two different dates as milliseconds by using the
getTime() method, rather than having to examine the individual parts of the date.
Example
The code in Listing 7.103 displays, 946684800000, the number of milliseconds that
passed between midnight January 1, 1970 and midnight January 1, 2000 using the
getTime() method.
Operators 297
// -->
</script>
Date.getTimezoneOffset()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getTimezoneOffset()
Description
The getTimezoneOffset() method returns the difference between the time zones of
local time and Greenwich Mean Time (GMT). This difference is returned as an integer
representing the number of minutes between the time zone of the local time and GMT.
Although this is a method of a Date object, the actual date and time associated with the
date is irrelevant because the time zone difference is based on the environment settings
in which the JavaScript code is run.
Example
The code in Listing 7.104 displays the time zone offset by using the
getTimezoneOffset() method. Notice that when the date and time are changed, the
time zone offset remains the same because the contents of the Date object are not used
in the calculation.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 298
Date.getUTCDate()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.getUTCDate()
Description
The getUTCDate() method returns the day of the month converted to universal time
and expressed as an integer from 1 to 31.
Example
The code in Listing 7.105 displays the day of the month in universal time using the
getUTCDate() method.
Listing 7.105 Using the getUTCDate() Method to Return the Day of the
Month
<script type=”text/javascript” language=”JavaScript”>
<!--
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getUTCDay()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera3+
Syntax
date.getUTCDay()
Description
The getUTCDay() method returns the day of the week converted to universal time and
expressed as an integer from 0 (Sunday) to 6 (Saturday).
Example
The code in Listing 7.106 uses the getUTCDay() method to return the day of the week
expressed as an integer in universal time. The number is then converted to a string
equivalent to the day of the week.
11 0672321416 CH07a 7/24/01 12:01 PM Page 299
Operators 299
Listing 7.106 Using the getUTCDay() Method to Return the Day of the
Week
<script type=”text/javascript” language=”JavaScript”>
<!--
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 300
Date.getUTCFullYear()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.getUTCFullYear()
Description
The getUTCFullYear() method returns the year as a full four-digit number converted
to universal time.
Example
The code in Listing 7.107 displays the year in universal time using the
getUTCFullYear() method.
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getUTCHours()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.getUTCHours()
Description
The getUTCHours() method returns the hour portion of the date, converted to univer-
sal time and expressed as an integer from 0 (12:00 a.m. midnight) to 23 (11:00 p.m.).
Example
The code in Listing 7.108 displays the current hour in universal time using the
getUTCHours() method.
11 0672321416 CH07a 7/24/01 12:01 PM Page 301
Operators 301
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getUTCMilliseconds()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.getUTCMilliseconds()
Description
The getUTCMilliseconds() method returns the milliseconds portion of the date, con-
verted to universal time and expressed as an integer from 0 to 999.
Example
The code in Listing 7.109 displays the current milliseconds in universal time using the
getUTCMilliseconds() method.
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getUTCMinutes()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
11 0672321416 CH07a 7/24/01 12:01 PM Page 302
Syntax
date.getUTCMinutes()
Description
The getUTCMinutes() method returns the minutes portion of the Date object, con-
verted to universal time and expressed as an integer from 0 to 59.
Example
The code in Listing 7.110 displays the current minutes in universal time using the
getUTCMinutes() method.
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getUTCMonth()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.getUTCMonth()
Description
The getUTCMonth() method returns the month portion of the Date object, converted to
universal time and expressed as an integer from 0 (January) to 11 (December).
Example
The code in Listing 7.111 uses the getUTCMonth() method to return the current month,
expressed as an integer, in universal time. The integer is converted to a string repre-
sentation of the month.
Operators 303
// -->
</script>
Date.getUTCSeconds()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.getUTCSeconds()
Description
The getUTCSeconds() method returns the seconds portion of the Date object, con-
verted to universal time and expressed as an integer from 0 to 59.
Example
The code in Listing 7.112 displays the current second in universal time using the
getUTCSeconds() method.
//Create a Date object that contains the current date and time.
theDate = new Date();
// -->
</script>
Date.getVarDate()
JScript 3.0+
IE 4+
Syntax
date.getVarDate()
11 0672321416 CH07a 7/24/01 12:01 PM Page 305
Operators 305
Description
The getVarDate() method returns the date value in VT_DATE format, which can be used
with Visual Basic and VBScript when interacting with COM objects, ActiveX objects,
and so on. The format is dependent on regional settings.
Example
The code in Listing 7.113 displays the date using the getVarDate() method.
Date.getYear()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.getYear()
Description
The getYear()method returns the year portion of the Date object. Unfortunately, the
year is represented as either a two-digit number or a four-digit number, depending on
the browser version. For example, the year 1983 might be returned from the methods
as 1983 or just 83.
NOTE
The getYear() method is obsolete. The getFullYear() method should be used
instead of getYear().
Example
The code in Listing 7.114 displays the year using the getYear() method associated
with your specific browser.
Listing 7.114 Using the getYear() Method to Return the Current Year
<script type=”text/javascript” language=”JavaScript”>
<!--
11 0672321416 CH07a 7/24/01 12:01 PM Page 306
// -->
</script>
Date.parse()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera5+
Syntax
Date.parse (date)
Description
The parse() method returns the time, represented in milliseconds between the date
argument string and midnight, January 1, 1970, GMT. Notice that this method is asso-
ciated with the “Date” object rather than a date that was declared. The string date
should use the format written by the Date toGMTString() method, which resembles the
following:
Mon, 24 Oct 1982 12:03:27 -0200
The method will also accept strings that lack all or any portion of the time and time
zone.
Example
The code in Listing 7.115 displays the milliseconds from 1970 to the string represen-
tation of the date and time.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 307
Operators 307
Date.prototype
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES3+, IE 4+, Opera5+
Syntax
Date.prototype.property
Date.prototype.method
Description
The prototype property allows you to add new properties and methods to the Date
object that can be used throughout your code.
Example
In Listing 7.116, the prototype property is used to create a new method, called
getDayString, which can be used by all Date objects. The getDayString() method
uses the getDayString() function to return a string representation of the day of the
week (for example, Sunday, Monday, Tuesday,…). This new functionality is used to
display the name of the current day.
// -->
</script>
Date.setDate()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.setDate(day)
Description
The setDate() method sets the day of the month in the Date object to the argument
day, an integer from 1 to 31. The method returns an integer representing the number of
milliseconds between midnight January 1, 1970 (GMT) to the date and time specified
in the Date object after the day of the month has been adjusted.
CAUTION
Prior to JavaScript 1.2, this method returned nothing.
Example
The code in Listing 7.117 displays the current date in milliseconds before setting the
day to 4. Notice that the milliseconds specified after the setDate() method are the
same as the result returned from the method.
11 0672321416 CH07a 7/24/01 12:01 PM Page 309
Operators 309
Listing 7.117 Setting the Day of the Month with the setDate() Method
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Date.setFullYear()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.setFullYear(year)
Description
The setFullYear() method sets the year in the Date object to the argument year, a
four-digit integer. The method returns an integer representing the number of millisec-
onds between midnight January 1, 1970 (GMT) to the date and time specified in the
Date object after the year has been adjusted.
Example
The code in Listing 7.118 displays the current date in milliseconds before setting the
year to 2003. Notice that the milliseconds specified after the setFullYear() method
are the same as the result returned from the method.
Listing 7.118 Setting the Day of the Week with the setFullYear()
Method
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Date.setHours()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.setHours (hours)
Description
The setHours() method sets the hour in the Date object to the argument hours, an
integer from 0 (12:00 a.m. midnight) to 23 (11:00 p.m.). The method returns an inte-
ger representing the number of milliseconds between midnight January 1, 1970 (GMT)
to the date and time specified in the Date object after the hour has been adjusted.
Example
The code in Listing 7.119 displays the current date in milliseconds before setting the
hour to 7 (8:00 a.m.). Notice that the milliseconds specified after the setHours()
method are the same as the result returned from the method.
// -->
</script>
Date.setMilliseconds()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
11 0672321416 CH07a 7/24/01 12:01 PM Page 311
Operators 311
Syntax
date.setMilliseconds(milliseconds)
Description
The setMilliseconds() method sets the milliseconds in the Date object to the argu-
ment milliseconds, an integer from 0 to 999. The method returns an integer repre-
senting the number of milliseconds between midnight January 1, 1970 (GMT) to the
date and time specified in the Date object after the milliseconds have been adjusted.
Example
Listing 7.120 displays the current date in milliseconds before setting the milliseconds
to 792. Notice that the milliseconds specified after the setMilliseconds() method are
the same as the result returned from the method.
// -->
</script>
Date.setMinutes()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.setMinutes (minutes)
Description
The setMinutes() method sets the minutes in the Date object to the argument
minutes, an integer from 0 to 59. The method returns an integer representing the num-
ber of milliseconds between midnight January 1, 1970 (GMT) to the date and time
specified in the Date object after the minutes have been adjusted.
11 0672321416 CH07a 7/24/01 12:01 PM Page 312
Example
The code in Listing 7.121 displays the current date in milliseconds before setting the
minutes to 43. Notice that the milliseconds specified after the setMinutes() method
are the same as the result returned from the method.
// -->
</script>
Date.setMonth()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.setMonth (month)
Description
The setMonth() method sets the month in the Date object to the argument month, an
integer from 0 (January) to 11 (December). The method returns an integer representing
the number of milliseconds between midnight January 1, 1970 (GMT) to the date and
time specified in the Date object after the month has been adjusted.
CAUTION
Prior to JavaScript 1.2, this method returned nothing.
Example
The code in Listing 7.122 displays the current date in milliseconds before setting the
month to 2 (March). Notice that the milliseconds specified after the setMonth()
method are the same as the result returned from the method.
11 0672321416 CH07a 7/24/01 12:01 PM Page 313
Operators 313
// -->
</script>
Date.setSeconds()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.setSeconds(seconds)
Description
The setSeconds() method sets the seconds in the Date object to the argument
seconds, an integer from 0 to 59. The method returns an integer representing the num-
ber of milliseconds between midnight January 1, 1970 (GMT) to the date and time
specified in the Date object after the seconds have been adjusted.
CAUTION
Prior to JavaScript 1.2, this method returned nothing.
Example
The code in Listing 7.123 displays the current date in milliseconds before setting the
seconds to 16. Notice that the milliseconds specified after the setSeconds() method
are the same as the result returned from the method.
// -->
</script>
Date.setTime()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.setTime (milliseconds)
Description
The setTime() method sets the time in the Date object to the argument milliseconds,
an integer representing the number of milliseconds between midnight January 1, 1970
(GMT) to the desired date and time.
Example
The code in Listing 7.124 uses the setTime() method to set the date to November, 17,
2005 using milliseconds.
// -->
</script>
Date.setUTCDate()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
11 0672321416 CH07a 7/24/01 12:01 PM Page 315
Operators 315
Syntax
date.setUTCDate(day)
Description
The setUTCDate() method sets the day of the month in the Date object to the argument
day, an integer from 1 to 31 (universal time). The method returns an integer represent-
ing the number of milliseconds between midnight January 1, 1970 (GMT) to the date
and time specified in the Date object after the day of the month has been adjusted.
Example
The code in Listing 7.125 displays the current date in milliseconds (universal time)
before setting the day to 6. Notice that the milliseconds specified after the
setUTCDate() method are the same as the result returned from the method.
// -->
</script>
Date.setUTCFullYear()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.setUTCFullYear(year)
Description
The setUTCFullYear() method sets the year in the Date object to the argument year,
a four-digit integer (universal time). The method returns an integer representing the
number of milliseconds between midnight January 1, 1970 (GMT) to the date and time
specified in the Date object after the year has been adjusted.
11 0672321416 CH07a 7/24/01 12:01 PM Page 316
Example
The code in Listing 7.126 displays the current date in milliseconds (universal time)
before setting the year to 2004. Notice that the milliseconds specified after the
setUTCFullYear() method are the same as the result returned from the method.
// -->
</script>
Date.setUTCHours()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.setUTCHours(hours)
Description
The setUTCHours() method sets the hour in the Date object to the argument hours, an
integer from 0 (12:00 a.m. midnight) to 23 (11:00 p.m.) universal time. The method
returns an integer representing the number of milliseconds between midnight January
1, 1970 (GMT) to the date and time specified in the Date object after the hour has been
adjusted.
Example
The code in Listing 7.127 displays the current date in milliseconds (universal time)
before setting the hour to 5 (5:00 a.m.). Notice that the milliseconds specified after the
setUTCHours() method are the same as the result returned from the method.
Operators 317
// -->
</script>
Date.setUTCMilliseconds()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.setUTCMilliseconds(milliseconds)
Description
The setUTCMilliseconds() method sets the milliseconds in the Date object to the
argument milliseconds, an integer from 0 to 999 (universal time). The method returns
an integer representing the number of milliseconds between midnight January 1, 1970
(GMT) to the date and time specified in the Date object after the milliseconds have
been adjusted.
Example
The code in Listing 7.128 displays the current date in milliseconds (universal time)
before setting the milliseconds to 258. Notice that the milliseconds specified after the
setUTCMilliseconds() method are the same as the result returned from the method.
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 318
Date.setUTCMinutes()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.setUTCMinutes(minutes)
Description
The setUTCMinutes() method sets the minutes in the Date object to the argument
minutes, an integer from 0 to 59 (universal time). The method returns an integer rep-
resenting the number of milliseconds between midnight January 1, 1970 (GMT) to the
date and time specified in the Date object after the minutes have been adjusted.
Example
The code in Listing 7.129 displays the current date in milliseconds (universal time)
before setting the minutes to 19. Notice that the milliseconds specified after the
setUTCMinutes() method are the same as the result returned from the method.
// -->
</script>
Date.setUTCMonth()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.setUTCMonth(month)
Description
The setUTCMonth() method sets the month in the Date object to the argument month,
an integer from 0 (January) to 11 (December) universal time. The method returns an
11 0672321416 CH07a 7/24/01 12:01 PM Page 319
Operators 319
Example
The code in Listing 7.130 displays the current date in milliseconds (universal time)
before setting the month to 4 (May). Notice that the milliseconds specified after the
setUTCMonth() method are the same as the result returned from the method.
// -->
</script>
Date.setUTCSeconds()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera5+
Syntax
date.setUTCSeconds(seconds)
Description
The setUTCSeconds() method sets the seconds in the Date object to the argument
seconds, an integer from 0 to 59 (universal time). The method returns an inte-
ger representing the number of milliseconds between midnight January 1, 1970
(GMT) to the date and time specified in the Date object after the seconds have been
adjusted.
Example
The code in Listing 7.131 displays the current date in milliseconds (universal time)
before setting the seconds to 46. Notice that the milliseconds specified after the
setUTCSeconds() method are the same as the result returned from the method.
11 0672321416 CH07a 7/24/01 12:01 PM Page 320
// -->
</script>
Date.setYear()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.setYear(year)
Description
The setYear()method sets the year in the Date object to the argument year. The argu-
ment can be either a four-digit or two-digit integer. To create a two-digit representation,
subtract 1900 from the desired date. So if “92” was passed in as an argument then the
year 1992 would be set. The method returns an integer representing the number of mil-
liseconds between midnight January 1, 1970 (GMT) to the date and time specified in
the Date object after the year has been adjusted.
NOTE
The getYear() method is obsolete. The setFullYear() method should be used
instead of setYear().
CAUTION
Prior to JavaScript 1.2, this method returned nothing.
Example
The code in Listing 7.132 displays the current date in milliseconds before setting the
year to 1983. Notice that the milliseconds specified after the setYear() method are the
same as the result returned from the method.
11 0672321416 CH07a 7/24/01 12:01 PM Page 321
Operators 321
// -->
</script>
Date.toGMTString()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
date.toGMTString()
Description
The toGMTString() method returns a string representing the universal time of the Date
object. The date is converted to the GMT time zone before being converted to a string.
The format of the string will look similar to the following:
Mon, 24 Oct 1982 12:03:27 GMT
Example
The code in listing 7.133 creates a Date object that contains the current date and time.
The toGMTString() method returns the date as a string in GMT.
Listing 7.133 Converting Date and Time to GMT with the toGMTString()
Method
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 322
Date.toLocaleString()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, IE 3+, Opera5+
Syntax
date.toLocaleString()
Description
The toLocaleString() method returns a string representation of the Date object in the
local time zone. The format of the string can vary greatly, depending on the user’s date
and time format settings.
Example
The code in Listing 7.134 creates a Date object that contains the current date and time.
The toLocaleString() method returns the date and time as a string using the local
time zone.
Listing 7.134 Converting Date and Time to the Local Time Zone with
the toLocaleString() Method
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Date.toSource()
JavaScript1.3, JScript3.0
Nav4.06+, IE4
Syntax
date.toSource()
Description
The toSource() method converts the Date object to a string that represents the source
of the Date instance that was created.
11 0672321416 CH07a 7/24/01 12:01 PM Page 323
Operators 323
NOTE
The toSource() method is usually called internally by JavaScript and not explicitly in
code.
Example
Listing 7.135 creates a date object March 16, 2002. The toSource() method is then
applied to the date object to return the source string “(new Date(1018986503234))”
with the date expressed in milliseconds.
Listing 7.135 Accessing the Source of a Date Object with the toSource()
Method
<script type=”text/javascript1.3” language=”JavaScript1.3”>
<!--
// -->
</script>
Date.toString()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera5+
Syntax
date.toString()
Description
The toString() method returns a string representation of the Date object in the local
time zone.
NOTE
How does the toString() method differ from toGMTString() and
toLocaleString()? Unlike the toGMTString() method, the toString() method
11 0672321416 CH07a 7/24/01 12:01 PM Page 324
displays the date in the local time zone. The toString() does not always display
the date in the local format of the toLocaleString() method.
Example
The code in Listing 7.136 creates a Date object from the current date and time. The
toString() method is then used to display the date as a string in the local time zone.
// -->
</script>
Date.toUTCString()
JavaScript 1.2+, ECMAScript 1E+, JScript 3.0+
Nav4+, IE 4+, Opera3+
Syntax
date.toUTCString()
Description
The toUTCString() method returns a string representing the universal time of the Date
object. The date is converted to the GMT time zone before being converted to a string.
This method is exactly the same as the toGMTString().
Example
The code in Listing 7.137 creates a Date object and initializes it to the current date and
time. The toUTCString() method is then used to display the current date and time as
a string in universal time.
Operators 325
// -->
</script>
Date.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
Date.unwatch(property)
Description
The unwatch() method of the Date object is used to turn off the watch on a particular
property specified by property.
Example
Listing 7.138 shows how the unwatch() method is used to stop watching the user-
defined property p.
myDate.p = 2;
myDate.unwatch(“p”);
myDate.p = 3;
myDate.watch(“p”,alertme);
myDate.p = 4;
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 326
Date.UTC()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE 3+, Opera3+
Syntax
Date.UTC(year, month, day, hours, minutes, seconds, milliseconds)
Description
Because the Date constructor creates new dates in local time, the UTC() method is pro-
vided to create dates in universal time (GMT). The method accepts arguments to allow
you to set all aspects of a date and time, from the year to milliseconds. An integer, rep-
resenting the number of milliseconds between midnight January 1, 1970 (GMT) to the
date and time specified, is returned from the method. The integer can then be used to
create a new Date object. The arguments and return value are in Table 7.26.
CAUTION
The milliseconds returned from the method are incorrect in Navigator 2.
Example
The code in Listing 7.139 creates a new Date object initialized to September 29, 2002
(universal time). The newly created date and time are then displayed in the browser.
11 0672321416 CH07a 7/24/01 12:01 PM Page 327
Operators 327
Listing 7.139 Creating a Date in Universal Time with the UTC() Method
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Date.valueOf()
JavaScript1.1+, ECMAScript 1E+, JScript3.0+
Nav3+, NES2+, IE4+, Opera3+
Syntax
date.valueOf()
Description
The valueOf() method returns the primitive value of the object. In terms of an instance
of a Date object, this method returns the equivalence of the Date object in milliseconds.
The milliseconds are expressed as an integer representing the number of milliseconds
between midnight January 1, 1970 (GMT) to the date and time specified in the Date
object.
Example
Listing 7.140 creates a Date object representing the current date and time. The result
of the valueOf() method on this date object is displayed in the browser.
Listing 7.140 Using the valueOf() Method to Return the Value of the
Date Object
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 328
Date.watch
JavaScript 1.2+
Nav4+, NES3+
Syntax
Date.watch (property,function)
Description
The watch() method of the Date object is used to turn on the watch on a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 7.141 shows how the watch() method is used to start watching the user-defined
property p.
myDate.p = 2;
// -->
</script>
debugger
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+, Opera5+
Syntax
Reserved Keyword
Description
The keyword debugger is reserved for future use.
11 0672321416 CH07a 7/24/01 12:01 PM Page 329
Operators 329
Example
This keyword has not been implemented; therefore no example is provided.
decodeURI()
JavaScript 1.5+, ECMAScript 3E+, JScript 5.5+
Nav6+, NES6+, IE5.5+
Syntax
decodeURI (URIString)
Description
The decodeURI() function is used to replace each escape sequence in the URIString
(uniform resource identifiers) with the character that it represents based on the UTF-8
standard. The function returns the decoded string.
NOTE
Escape sequences that do not get encoded by the encodeURI() function (,, /, ?, :,
@, &, =, +, $) cannot be decoded using the decodeURI() function. To decode these
reserved characters, use the decodeURIComponent() function.
Example
In Listing 7.142 the string “The apple is red.” is encoded using the encodeURI()
function. The result is the same string, but with the spaces replaced with “%20”, the
encoded equivalent. This encoded URI string is then decoded back to its original form
using the decodeURI() function.
myString = encodeURI(myString);
document.write(“The encoded sentence: “ + myString + “<br><br>”);
myString = decodeURI(myString);
document.write(“The decoded sentence: “ + myString + “<br><br>”);
// -->
</script>
11 0672321416 CH07a 7/24/01 12:01 PM Page 330
decodeURIComponent()
JavaScript 1.5+, ECMAScript 3E+, JScript 5.5+
Nav6+, NES6+, IE5.5+
Syntax
decodeURIComponent(URIComponentString)
Description
The decodeURIComponent()function is used to replace each escape sequence in the
URIComponentString (uniform resource identifiers) with the character that it repre-
sents based on the UTF-8 standard. The function returns the decoded string.
NOTE
The decodeURIComponent() function differs from the decodeURI() function in that it
decodes some reserved characters (,, /, ?, :, @, &, =, +, $) that are not decoded by
the decodeURI() function. For this reason, the decodeURIComponent method is
designed to only decode URI strings that were originally encoded using the
encodeURIComponent() function.
Example
In Listing 7.143 the phrase “fork, spoon, & knife” is encoded using the
encodeURIComponent() function. The result is the same string but with the spaces,
commas, and ‘&’ characters encoded. This encoded URI component string is then
decoded using the decodeURI() function. But notice that this function only decodes
the spaces. In order to decode the commas and ‘&’ character, the
decodeURIComponent() function must be used.
myString = encodeURIComponent(myString);
document.write(“The encoded phrase: “ + myString + “<br><br>”);
myString = decodeURI(myString);
document.write(“The decoded phrase: “ + myString + “<br><br>”);
myString = decodeURIComponent(myString);
document.write(“The decoded component phrase: “ + myString + “<br><br>”);
11 0672321416 CH07a 7/24/01 12:01 PM Page 331
Operators 331
// -->
</script>
default
JavaScript1.2+, JScript3.0+
Nav4+, NES3+, IE4+, Opera5+
Syntax
Reserved Keyword
Description
The default keyword has not been implemented in JavaScript to date, but has been
reserved for future use.
Example
This keyword has not been implemented; therefore no example is provided.
delete
JavaScript 1.0+, ECMAScript 1E+, JScript 3.0+
Nav2+, NES3+, IE 4+, Opera3+
Syntax
delete property
Description
The delete operator deletes properties from objects and array elements from arrays by
making them undefined. Actual memory deallocation is done by JavaScript garbage
collection. Some objects, such as variables created by the var statement, are not
affected by the delete operator.
CAUTION
Prior to JavaScript 1.2, the delete operator set the object property to null rather
than undefined.
Example
The code in Listing 7.144 demonstrates how to use the delete operator to delete a Date
object. Notice that the last document.write() statement does not write anything to the
browser because theDate is undefined after using the delete operator.
//Delete theDate.
delete theDate;
// -->
</script>
do
ECMAScript 3.0+, ECMAScript 2E+, JScript 5.5+
Nav4+, NES3+, IE 5.5+, Opera5+
Syntax
Reserved Keyword
Description
The do keyword is utilized in the do...while loop structure, thus it cannot be used as
a variable name.
Example
This keyword is reserved. See the do...while entry for more information on its use.
do...while
JavaScript 1.0+ , ECMAScript 1E+, JScript 3.0+
Nav2+, NES3+, IE 4+, Opera 3+
Syntax
do{
statement;
}while(expression);
Description
The do...while loop always executes the loop once before evaluating the expression
for the first time. Once the loop has executed for the first time, the expression, in
parenthesis, is evaluated. If true, the loop is executed again. When the expression
11 0672321416 CH07a 7/24/01 12:01 PM Page 333
Operators 333
evaluates to false, the next line of code following the while structure is executed. A
statement must be included in the loop that modifies a variable in the expression to
prevent an infinite loop. Also, notice that a semicolon (;) must be placed after the right
parenthesis.
Example
Listing 7.145 uses the do...while loop to control access through a gate. Only three
individuals are allowed through the gate.
//Print names of the first 3 individuals who can pass through gate.
do
{
document.write((x+1),”. “,names[x],”<br>”);
x++; //increment counter
}
while(x<3);
// -->
</script>
double
JavaScript1.2+, ECMAScript 2E+, JScript 5.0+
Nav4+, NES3+, IE5+, Opera5+
Syntax
Reserved Keyword
Description
The double keyword has not been implemented in server-side JavaScript to date, but
has been reserved for future use.
Example
This keyword has not been implemented; therefore no example is provided.
12 0672321416 CH07b 7/24/01 12:06 PM Page 334
else
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, IE3+
Syntax
Reserved Keyword
Description
The else statement is used to perform alternative logic should the corresponding if
statement not evaluate to true.
Example
Listing 7.146 shows an example of the basic logic to the else statement. If the if con-
dition does not equate to true, the else statement is executed.
encodeURI()
JavaScript 1.5+, ECMAScript 3E+, JScript 5.5+
Nav6+, NES6+, IE5.5+
Syntax
encodeURI (URIString)
Description
The encodeURI() function is used to encode a URI (uniform resource identifier) by
replacing specific characters with escape sequences representing UTF-8 encoding.
NOTE
Certain characters will not be encoded with the encodeURI() function. They are
shown in Table 7.27.
Operators 335
Example
In Listing 7.147, the string “The apple is red.” is encoded using the encodeURI()
function. The result is the same string, but with the spaces replaced with “%20”, which
is the encoded equivalent.
myString = encodeURI(myString);
document.write(“The encoded sentence: “ + myString + “<br><br>”);
// -->
</script>
</html>
encodeURIComponent()
JavaScript 1.5+, ECMAScript 3E+, JScript 5.5+
Nav6+, NES6+, IE5.5+
Syntax
encodeURIComponent (URIComponentString)
Description
The encodeURIComponent() function is used to replace certain characters in the
URIComponentString (uniform resource identifier) with escape sequences representing
its UTF-8 character encoding. This function assumes a URI component, and therefore
will encode reserved characters.
NOTE
Certain characters will not be encoded with the encodeURIComponent() function.
They are shown in Table 7.28.
Example
In Listing 7.148, the phrase “fork, spoon, & knife” is encoded using the
encodeURIComponent() function. The result is the same string, but with the spaces,
commas, and & characters encoded.
// -->
</script>
</html>
enum
JavaScript 1.3+, ECMAScript 1E+, JScript 3.0+
Nav4.06+, IE4+
Syntax
Reserved Keyword
Description
The enum keyword is initially introduced in JavaScript 1.3 and is reserved for future
use.
Example
This entry has not yet been implemented in the JavaScript language, and no example is
provided.
Enumerator
JScript3.0+
IE4+
Syntax
var variable = new Enumerator(collection)
12 0672321416 CH07b 7/24/01 12:06 PM Page 337
Operators 337
Description
The Enumerator object provides access to items in a collection by allowing iteration
through a collection. Accessing items in a collection requires moving the Enumerator
object to the first element or the next element using special methods. Unlike arrays,
enumerators cannot access a specific position. To create an Enumerator object, use the
Enumerator() constructor. This constructor requires that a collection be passed in as
an argument. The methods associated with the Enumerator object are listed in Table
7.29.
Example
Listing 7.149 creates an Enumerator object for accessing items in the Drives collec-
tion.
Enumerator.atEnd()
JScript 3.0+
IE4+
Syntax
enumeratorobj.atEnd()
Description
The atEnd() method of the Enumerator object returns true if the enumerator is point-
ing to the last element in the collection; otherwise, it returns false. true is also
returned if the collection is empty or undefined.
Example
The atEnd() method is used in Listing 7.150 to determine when to stop looping
through the for loop.
12 0672321416 CH07b 7/24/01 12:06 PM Page 338
<script language=”JScript”>
<!--
// -->
</script>
</html>
Enumerator.item()
JScript 3.0+
IE4+
Syntax
enumeratorobj.item()
Description
The item() method of the Enumerator object returns the element to which the enu-
merator is pointing in the collection. If the collection is empty or undefined, undefined
is returned.
Example
The item() method is used in Listing 7.151 to access the drive letter and drive type of
the current drive.
Operators 339
<script language=”JScript”>
<!--
// -->
</script>
</html>
Enumerator.moveFirst()
JScript 3.0+
IE4+
Syntax
enumeratorobj.moveFirst()
Description
The moveFirst() method of the Enumerator object moves the enumerator to the
beginning of the collection. If the collection is empty or undefined, undefined is
returned.
Example
In Listing 7.152, the enumerator is used to access the drive letters and types. The
moveFirst() method moves the enumerator back to the beginning of the collection so
that the drive status can be determined for each drive.
<script language=”JScript”>
<!--
document.write(“<h1>Drive Status:</h1>”);
// -->
</script>
</html>
Enumerator.moveNext()
JScript 3.0+
IE4+
Syntax
enumeratorobj.moveNext()
Description
The moveNext() method of the Enumerator object moves the enumerator to the next
item in the collection. If the collection is empty, undefined is returned.
Example
The moveNext() method is used in Listing 7.153 to move the enumerator to the next
drive in the collection.
12 0672321416 CH07b 7/24/01 12:06 PM Page 341
Operators 341
<script language=”JScript”>
<!--
// -->
</script>
</html>
Error
JScript 5.0+
IE5+
Syntax
var variable = new Error();
var variable = new Error(num);
var variable = new Error(num, description);
Description
The Error object contains information about errors. The Error() constructors can be
used to create custom error messages. The arguments and properties associated with
the Error object are listed in Table 7.30.
NOTE
An error number is a 32-bit value where the upper 16-bit word is the facility code
and the lower word is the actual error code. The facility code refers to the compo-
nent that caused the error.
Example
Listing 7.154 creates an Error object.
Error.description
JScript 5.0+
IE5+
Syntax
errorobj.description
errorobj.description = string
Description
The description property associated with the Error object contains the description of
the error. This method is read/write so that you can assign descriptions using this prop-
erty.
Example
Listing 7.155 creates an Error object and then displays the description.
<script language=”JScript”>
<!--
Operators 343
// -->
</script>
</html>
Error.message
JScript 5.5+
IE5.5+
Syntax
errorobj.message
errorobj.message = string
Description
The message property associated with the Error object returns a string containing an
error message displayed to users. This is the same as the description property.
Example
Listing 7.156 creates an Error object and then displays the message.
Listing 7.156 Display the Message of an Error with the message Property
<html>
<script language=”JScript”>
<!--
// -->
</script>
</html>
Error.name
JScript 5.5+
IE5.5+
Syntax
errorobj.name
12 0672321416 CH07b 7/24/01 12:06 PM Page 344
Description
The name property associated with the Error object returns a name or exception type
of an error. If the error is a runtime error, the name property is set to one of the excep-
tion types shown in Table 7.31.
Example
Listing 7.157 creates an Error object and then displays the name property.
Listing 7.157 Displays the Name of an Error with the name Property
<html>
<script language=”JScript”>
<!--
// -->
</script>
</html>
Error.number
JScript 5.0+
IE5+
Syntax
errorobj.number
errorobj.number = number;
12 0672321416 CH07b 7/24/01 12:06 PM Page 345
Operators 345
Description
The number property associated with the Error object contains the error number of the
error. This method is read/write, so you can assign an error number using this property.
Example
Listing 7.158 creates an Error object and then displays the error number.
<script language=”JScript”>
<!--
// -->
</script>
</html>
escape()
JavaScript 1.0+, ECMAScript 1E+, JScript 3.0+
Nav2+, NES2+, IE4+, Opera3+
Syntax
escape (string)
escape(expression)
Description
The escape() function takes any string object or expression and returns a string object
in which all non-alphanumeric characters are converted to their numeric equivalent in
the form %XX. The XX is a hexadecimal number representing the non-alphanumeric
character.
Example
Listing 7.159 shows how to use the escape() function. It takes a string of text and
returns the escaped value.
12 0672321416 CH07b 7/24/01 12:06 PM Page 346
<form name=”form1”>
Enter input:
<input type=”text” name=”input1” size=”30”>
<input type=”button” value=”Show Escape Value” onClick=’showEscapeVal()’>
</form>
</body>
</html>
eval()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
eval (command)
eval(string)
Description
The eval() function accepts a string of JavaScript statements and evaluates it as
JavaScript source code. eval() returns the value of the executed JavaScript state-
ment.
12 0672321416 CH07b 7/24/01 12:06 PM Page 347
Operators 347
NOTE
eval() has evolved with JavaScript. In the early releases of JavaScript, version 1.0,
eval() was only a built-in function. When version 1.1 was released, though, it was
made a method as well. But when JavaScript version 1.2 was initially released, it
was changed back to being just a built-in function. However, eval() was once
again changed to a built-in function and method with the release of Navigator
4.02 and later.
Example
Listing 7.161 shows how to use eval() to execute a JavaScript command input by a
user. Simply enter a valid JavaScript command into the text box and click the Execute
button. When the button is clicked, the run() function is called, which performs an
eval on the user input.
<form name=”form1”>
Enter a Javascript command in the text field and click
the “execute” button to execute the command.
<br><br>
Command:<input type=”text” name=”input1” size=”30”>
<br>
<input type=”button” value=”execute” onClick=’run()’>
</form>
</body>
</html>
export
JavaScript 1.2+, ECMAScript 1E+
Nav4+
Syntax
export
12 0672321416 CH07b 7/24/01 12:06 PM Page 348
Description
export is a keyword used by scripts implementing security features that makes objects,
properties, and methods accessible to other unsigned scripts.
Example
Listing 7.162 shows how to use the export keyword. In the JavaScript code, the export
keyword is used to make the variables, name, city, and showName() function available
to other unsigned scripts. Other scripts would access the information using the import
keyword.
function showName(){
alert(“Your name is: “ + name);
}
// -->
</script>
</body>
</html>
extends
JavaScript 1.3+, ECMAScript 1E+
Nav4.06+
Syntax
Reserved Keyword
Description
The extends keyword was initially introduced in JavaScript 1.3, and it is reserved for
future use.
Example
This entry has not yet been implemented in the JavaScript language.
12 0672321416 CH07b 7/24/01 12:06 PM Page 349
Operators 349
false
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The false keyword has not been implemented in JavaScript to date. It has been
reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
final
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The final keyword has not been implemented in JavaScript to date. It has been
reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
float
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The float keyword has not been implemented in JavaScript to date. It has been
reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
12 0672321416 CH07b 7/24/01 12:06 PM Page 350
for
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+
Syntax
for( [initial statement;] [condition;] [num;]){
code;
Description
The for keyword is used to create a loop that consists of three optional expressions,
enclosed in parentheses and separated by semicolons, followed by a block of state-
ments executed in the loop.
The initial statement is a JavaScript statement or variable declaration. The condi-
tion is an optional statement that is evaluated through each iteration of the loop. If a
condition is satisfied, all statements contained in the loop are executed. The num des-
ignates whether the loop increments or decrements every loop iteration. And finally, the
code contains JavaScript statements that are executed each time the condition is satis-
fied.
Example
Listing 7.163 shows an example of a loop that performs a document.write nine times.
An initial variable i is declared and set equal to zero. The variable is then evaluated
against the condition that it is less than nine. If this evaluates to true, the variable is
incremented and the document.write expression is performed.
// -->
</script>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:06 PM Page 351
Operators 351
for...in
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
for(variable in object){
code;
Description
The for...in object iterates a specified variable over all the properties of an object.
The statements, contained in the body, are executed once for each property. The vari-
able is a variable iterated over each property in the object. The code contains
JavaScript statements to be executed.
Example
Listing 7.164 shows how to use the for...in object. The showProperties function
takes an object type and object name as arguments. A for...in loop is then executed
on the object displaying each of the object’s properties and their values.
function
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
function name(parm1, parm2, …, parmN)
function name()
Description
The function keyword is used for specifying JavaScript functions. JavaScript func-
tions typically contain a series of JavaScript statements that are grouped together to
perform a specific task. The name is the name of the function and parm1–parmN are any
optional parameters.
Example
Listing 7.165 shows how the function keyword is used. The function keyword
defines the sendMessage function.
Function()
JavaScript 1.0+, ECMAScript 1E+, JScript 2.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
var variable = new Function()
var variable = new Function(int)
var variable = new Function(arg1, ..., argN)
Description
Function() is a constructor that creates a Function object. Table 7.32 lists the differ-
ent methods and properties of the Function object.
12 0672321416 CH07b 7/24/01 12:06 PM Page 353
Operators 353
Example
Listing 7.166 shows how a new Function object can be created with a single line. In
this example, the function, when called, will change the background color of the page
to blue.
Listing 7.166 Setting the Background Color with a New Function Object
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
Function.apply()
JavaScript 1.3+, ECMAScript 1E+
Nav4.06+, IE3+, Opera3+
Syntax
function.apply()
12 0672321416 CH07b 7/24/01 12:06 PM Page 354
Description
The apply() method of the Function object is used to apply a method of one object to
another object. Using the apply() method keeps developers from having to rewrite
methods for different objects.
Example
Listing 7.167 shows how the apply() method can be used between two objects. The
bigHome function adds a new property, numRooms, to the home object.
Function.arguments
JavaScript 1.1+, JScript 2.0+, ECMAScript 1E+
Nav3+, NES2+, IE3+, Opera3+
Syntax
function.arguments
12 0672321416 CH07b 7/24/01 12:06 PM Page 355
Operators 355
Description
The arguments property of the Function object is an array that holds the arguments
that are passed to a function. The number of arguments passed to a defined function
can be more than the number of parameters if the arguments array is used. The argu-
ments array can only be accessed while inside the function. Any attempt to access the
arguments array outside the function will result in an error.
Example
Listing 7.168 shows how the arguments array is used. A document.write is per-
formed, which calls the foo function. The foo function is passed two arguments and
calls the foobar function with the parameter 123. The foobar function outputs the
number of arguments it has and outputs the second argument to the function that called
it, in this case the foo function.
document.write(foo(21,44) + “\n”);
// -->
</script>
</body>
</html>
Function.arity
JavaScript 1.2
Nav4+, NES3+
Syntax
function.arity
12 0672321416 CH07b 7/24/01 12:06 PM Page 356
Description
The arity property of the Function object represents the number of declared argu-
ments a function expects to receive. This is valid when the language attribute of the
script tag is set to JavaScript1.2. This property is deprecated in JavaScript 1.4. In
JavaScript 1.5, this property is replaced with the length property.
Example
Listing 7.169 shows how arity can be used. The first line written to the user’s page
contains the number of arguments passed to the function. The second line is the result
of running the script.
// -->
</script>
</body>
</html>
Function.call()
JavaScript 1.3+
Nav4.06+, IE3+, Opera3+
Syntax
function.call(this)
Description
The call() method of the Function object allows you to call another object’s method.
Optional arguments can be passed to the method as shown in the second syntactical
definition.
12 0672321416 CH07b 7/24/01 12:06 PM Page 357
Operators 357
Example
Listing 7.170 shows an example of the call() method. The script creates a person and
author object. The author object uses the call() method to perform some of its
creation.
// -->
</script>
Function.callee
JavaScript 1.2+
Nav4+, IE5+
Syntax
function.callee
Description:
The callee property of the Function object was actually a property of
Function.arguments in JavaScript versions through 1.3. In JavaScript 1.4 and later, it
is a local property. It is used to specify the function body of the currently executing
function. It is only available within the body of a function.
12 0672321416 CH07b 7/24/01 12:06 PM Page 358
Example
Listing 7.171 shows how the callee property is used to get the value of the
Function.callee property.
<body>
<form name=”form1”>
<input type=”button” value=”Get callee property” onClick=’display()’>
</form>
</body>
</html>
Function.caller
JavaScript 1.1+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
function.caller
Description:
The caller property of the Function object is used to reference the function that called
the currently executing function. This property is deprecated in JavaScript 1.3. In
JavaScript versions 1.4 and 1.5, this property is no longer used.
Example
Listing 7.172 shows how the caller property is used to get the name of the function
calling John().
Operators 359
</html>
Function.constructor
JavaScript 1.1+, JScript 2.0+
Nav3+, NES2+, IE4+
Syntax
function.constructor
Description
The constructor property of the Function object is used to create the object’s proto-
type.
Example
Listing 7.173 shows how the constructor property is used. A function object named
drive is defined. Then using the constructor property, we determine whether drive is
a Function object.
function drive() {
return “something”;
}
if(drive.constructor == Function)
{
document.write(“Constructor matches”);
}
// -->
</script>
</html>
12 0672321416 CH07b 7/24/01 12:06 PM Page 360
Function.length
JavaScript 1.1+, ECMAScript 1E+
Nav3+
Syntax
function.length
Description:
The length property of the Function object is used to specify the number of arguments
in which the function expects. This is not to be confused with the arguments.length
property that provides the number of arguments actually passed into a function.
Example
Listing 7.174 shows how the length property is used.
<body>
Click the button to get the number of arguments the show function expects
<br><br>
<form name=”form1”>
<input type=”button” value=”Get length property” onClick=’show(1,2)’>
</form>
</body>
</html>
Function.prototype
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
function.prototype.property
function.prototype.method
12 0672321416 CH07b 7/24/01 12:06 PM Page 361
Operators 361
Description
The prototype property of the Function object refers to the object that serves as the
prototype from which classes are created. prototype allows you to add new properties
or methods to an existing class by adding them to the prototype associated with the
constructor of that class.
Example
Listing 7.175 shows how the prototype property is used. The function setTask, which
simply sets the task variable, is defined. Then a new prototype called duty is created
for the String object. The duty prototype is set to call the setTask function. Now all
String objects in the example have the setTask method.
if(str != null){
task = str;
}
return task;
}
String.prototype.duty = setTask;
Function.toSource()
JavaScript 1.3+
Nav4.06+, IE3+, Opera3+
Syntax
function.toSource()
12 0672321416 CH07b 7/24/01 12:06 PM Page 362
Description
The toSource() method of the Function object allows you to create a copy of an
object.
Example
Listing 7.176 uses the toSource() method on a newly created string. Running this
script in a browser returns the following:
(new String(“This is the source”))
// -->
</script>
</body>
</html>
Function.toString()
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE4+, Opera3+
Syntax
function.toString()
Description
The toString() method of the Function object is used to convert a function to a text
string. The method converts the function back to the JavaScript source that defines the
function. The converted string includes all aspects of the defined function.
12 0672321416 CH07b 7/24/01 12:06 PM Page 363
Operators 363
Example:
Listing 7.177 shows how the toString() method is used to convert a function to a text
string.
</body>
</html>
Function.valueOf()
JavaScript 1.1+, JScript 2.0+
Nav3+, IE4+, Opera5+
Syntax
function.valueOf()
Description
The valueOf() method of the Function object is used to obtain a string representation
of the function source code. Typically this is a method used internally by the JavaScript
interpreter and not explicitly in code. However it can be called directly if needed.
Example
Listing 7.178 shows how the valueOf() method is used. A function called myTest sim-
ply calls the valueOf() method to get the string representation of the myTest function.
12 0672321416 CH07b 7/24/01 12:06 PM Page 364
function myTest()
{
var temp;
return (myTest.valueOf() );
}
// -->
</script>
</body>
</html>
GetObject
JScript 3.0+
IE4+
Syntax
GetObject (path)
GetObject(path, app.type)
Description
The GetObject function returns a reference to an Automation object from a file. The
function can take up to two parameters. The path parameter represents the full path and
name to the file containing the object you want to retrieve.
NOTE
Some of the applications you can retrieve objects from allow you to activate only
part of the file. This can be achieved by placing an exclamation point, !, at the end
of the path followed by the string that specifies the part you want to activate.
The app.type attribute is the program ID or formal definition of the object. The app
portion represents the name of the application providing the object, and the type des-
ignates the type of object to create. If this parameter is not passed, the Automation
object will try to determine which application to start.
12 0672321416 CH07b 7/24/01 12:06 PM Page 365
Operators 365
NOTE
Use the ActiveXObject function if you want to create an instance without starting
the object with a file loaded.
Example
Listing 7.179 shows the syntax that can be used to return an Automation object from a
file. The second entry shows how you can activate only part of the object.
Global
JavaScript 1.0+, JScript 3.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
Core JavaScript Object
Description
The Global object is a core object in the JavaScript language. Properties and functions
that are not associated with any other object belong to this object. Table 7.33 shows the
properties and methods of this object
Example
See the separate entries for each of these properties and functions for examples. Note
that the properties and functions are not referred to with a preceding Global reference,
when being used.
Global.decodeURI()
JavaScript 1.5+, ECMAScript 3E+, JScript 5.5+
Nav6+, NES6+, IE5.5+
Syntax
decodeURI (URIString)
Description
The decodeURI() function is used to replace each escape sequence in the URIString
(uniform resource identifier) with the character that it represents based on the UTF-8
standard. (See http://www.utf-8.org/ for more information on UTF-8.) The function
returns the decoded string.
NOTE
Escape sequences that do not get encoded by the encodeURI() function (,, /, ?, :,
@, &, =, +, $) cannot be decoded using the decodeURI() function. To decode these
reserved characters, use the decodeURIComponent() function.
12 0672321416 CH07b 7/24/01 12:06 PM Page 367
Operators 367
Example
In Listing 7.180, the string “The apple is red.” is encoded using the encodeURI()
function. The result is the same string but with the spaces replaced with “%20”, the
encoded equivalent. This encoded URI string is then decoded back to its original form
using the decodeURI() function.
// Create a string.
myString=”The apple is red”;
document.write(“The original sentence: “ + myString + “<br><br>”);
// -->
</script>
</html>
Global.decodeURIComponent()
JavaScript 1.5+, ECMAScript 3E+, JScript 5.5+
Nav6+, NES6+, IE5.5+
Syntax
decodeURIComponent (URIComponentString)
Description
The decodeURIComponent() function is used to replace each escape sequence in the
URIComponentString (uniform resource identifier) with the character that it represents
based on the UTF-8 standard. The function returns the decoded string.
NOTE
The decodeURIComponent() function differs from the decodeURI() function in that it
decodes some reserved characters (,, /, ?, :, @, &, =, +, $) that are not decoded by
the decodeURI() function. For this reason, the decodeURIComponent method is
designed to only decode URI strings that were originally encoded using the
encodeURIComponent() function.
12 0672321416 CH07b 7/24/01 12:06 PM Page 368
Example
In Listing 7.181, the phrase “fork, spoon, & knife” is encoded using the
encodeURIComponent() function. The result is the same string, but with the spaces,
commas, and & characters encoded. This encoded URI component string is then
decoded using the decodeURI() function. But notice that this function only decodes
the spaces. In order to decode the commas and the & character, the
decodeURIComponent() function must be used.
// -->
</script>
</html>
Global.encodeURI()
JavaScript 1.5+, ECMAScript 3E+, JScript 5.5+
Nav6+, NES6+, IE5.5+
Syntax
encodeURI (URIString)
Description
The encodeURI() function is used to encode a URI by replacing specific characters
with escape sequences representing UTF-8 encoding.
12 0672321416 CH07b 7/24/01 12:06 PM Page 369
Operators 369
NOTE
Certain characters will not be encoded with the encodeURI() function. They are
shown in Table 7.34.
Example
In Listing 7.182, the string “The apple is red.” is encoded using the encodeURI()
function. The result is the same string, but with the spaces replaced with “%20”, the
encoded equivalent.
// -->
</script>
</html>
Global.encodeURIComponent()
JavaScript 1.5+, ECMAScript 3E+, JScript 5.5+
Nav6+, NES6+, IE5.5+
Syntax
encodeURIComponent (URIComponentString)
Description
The encodeURIComponent()function is used to replace certain characters in the
URIComponentString (uniform resource identifier) with escape sequences representing
12 0672321416 CH07b 7/24/01 12:07 PM Page 370
their UTF-8 character encoding. This function assumes a URI component and there-
fore will encode reserved characters.
NOTE
Certain characters will not be encoded with the encodeURIComponent() function.
They are shown in Table 7.35.
Example
In Listing 7.183, the phrase “fork, spoon, & knife” is encoded using the
encodeURIComponent() function. The result is the same string, but with the spaces,
commas, and & characters encoded.
// -->
</script>
</html>
Global.escape()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
escape (string)
escape(expression)
Description
The escape() method takes any string object or expression and returns a string object
in which all non-alphanumeric characters are converted to their numeric equivalent in
12 0672321416 CH07b 7/24/01 12:07 PM Page 371
Operators 371
Example
Listing 7.184 shows how to use the escape() method and what it returns. It takes a
string of text and returns the escaped value.
Listing 7.185 Example of Taking User Input and Passing Data to the
Escape Method
<html>
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Writes the value of input after escape has been performed.
function showEscapeVal(){
document.write(escape(document.form1.input1.value);
}
// -->
</script>
<form name=”form1”>
<input type=”text” name=”input1” size=30>
</form>
</body>
</html>
Global.eval()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
eval (command)
eval(string)
12 0672321416 CH07b 7/24/01 12:07 PM Page 372
Description
The eval() function accepts a string of JavaScript statements and evaluates it as
JavaScript source code. eval() returns the value of the executed JavaScript statement.
NOTE
eval() has evolved with JavaScript. In the early releases of JavaScript, version 1.0,
eval() was only a built-in function. When version 1.1 was released though, it was
made a method as well. But when JavaScript version 1.2 was initially released, it
was changed back to being just a built-in function. However, eval() was once
again changed to a built-on function and method, with the release of Navigator
4.02 and later. With JavaScript 1.4 and later, the eval() method is a top level func-
tion not associated with any object.
Example
Listing 7.186 shows how to use eval() to execute a JavaScript command input by a
user. Simply enter a valid JavaScript command into the text box and click the Execute
button. When the button is clicked, the run() function is called, which performs an
eval on the user input.
<form name=”form1”>
Enter a JavaScript command in the text field and click
the “execute” button to execute the command.
<br><br>
Command:<input type=”text” name=”input1” size=”30”>
<br>
<input type=”button” value=”execute” onClick=’run()’>
</form>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 373
Operators 373
Global.Infinity
JavaScript 1.3+, JScript 3.0+, ECMAScript 1E+
Nav4.06+, IE4+, Opera3+
Syntax
Infinity
Description
Infinity is a JavaScript keyword that represents positive infinity.
Example
Listing 7.187 shows how the Infinity keyword is used. An input text box is provided
to enter a value to be compared to Infinity. If any number is entered, it will result in
being less than Infinity. However, if the word Infinity is entered, it will result in
being equal to Infinity.
input=document.form1.num.value;
}
// -->
</script>
<form name=”form1”>
Enter a number to compare against Infinity.
<br><br>
<input type=”text” size=”35” name=”num”>
12 0672321416 CH07b 7/24/01 12:07 PM Page 374
</body>
</html>
Global.isFinite()
JavaScript 1.3+, ECMAScript 1E+, JScript 3.0+
Nav4.06+, IE4+, Opera3+
Syntax
isFinite()
Description
The isFinite() method is used to determine whether a variable has finite bounds.
Example
In Listing 7.188, you see how the isFinite() method is used to verify whether the
user input value has finite bounds.
<form name=”form1”>
Enter a number or character into the text box and then click the check value
button to verify if the input is a number.
<br><br>
12 0672321416 CH07b 7/24/01 12:07 PM Page 375
Operators 375
</body>
</html>
Global.isNaN()
JavaScript 1.1+, JScript 1.0+, ECMAScript 1E+
Nav3+, NES2+, IE3+, Opera3+
Syntax
isNaN (variable)
Description
The isNaN()function is used to determine whether variable is a valid number.
Example
In Listing 7.189, you see how the isNaN() function can be used to check user input.
<form name=”form1”>
Enter a number or character into the text box and then click the check value
button to verify if the input is a number.
<br><br>
<input type=”text” name=”text1” size=3>
<br><br>
<input type=”button” value=”Check value” onClick=’checkNum()’>
12 0672321416 CH07b 7/24/01 12:07 PM Page 376
</body>
</html>
Global.NaN
JavaScript 1.3+, JScript 3.0+, ECMAScript 1E+
Nav4.06+, IE4+
Syntax
NaN
Description
The NaN object represents an object that is not equal to any number, including itself.
NaN stands for Not a Number.
Example
Listing 7.190 shows how the NaN object is used in a comparison.
</body>
</html>
Global.Number()
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
Number(obj)
12 0672321416 CH07b 7/24/01 12:07 PM Page 377
Operators 377
Description
The Number() method takes whatever object is passed in as a parameter, obj, and con-
verts it to a Number. If the object being converted does not contain a well-formed
numeric literal, NaN is returned. When converting a Date object, the time is measured
in milliseconds from Jan 1970 GMT.
Example
Listing 7.191 shows how the Number() method is used to convert a Date object into a
number.
</html>
Global.parseFloat()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
parseFloat (string)
Description
The parseFloat() method is used to convert a string to a number.
Example
Listing 7.192 shows how the parseFloat() method is used. In the example,
parseFloat is called with two different strings. The first string, which contains numer-
ical characters, is converted to a number without any problems. The second string,
which contains alphabetic characters, is unable to be converted into a number.
12 0672321416 CH07b 7/24/01 12:07 PM Page 378
</body>
</html>
Global.parseInt()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
parseInt(string, radix)
parseInt(string)
Description
The parseInt() method is used to convert a string to an integer. It can take string
input with an optional radix input. The radix input represents the base of the number
in the string.
Example
Listing 7.193 shows how parseInt() is used to parse a string. A few different exam-
ples are shown for different string types.
Operators 379
// -->
</script>
</body>
</html>
Global.String()
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
String(obj)
Description
The String() method takes whatever object is passed in as a parameter and converts
it to a String. It is the same as using the toString() method.
Example
Listing 7.194 shows how the String() method is used to convert a Date into a String.
// -->
</script>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 380
Global.unescape()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
unescape (string)
Description
The unescape() method takes a hexadecimal value and returns the ISO-Latin-1 ASCII
equivalent. This method performs the opposite operation of the escape() method and
is commonly used to escape user-entered data before form submission.
Example
Listing 7.195 declares a local variable, escapedVal, and passes it to the unescaped()
method. The result, “@”, is then written to the page.
// Create a variable.
var escapedVal = “%40”;
// -->
</script>
Global.undefined
JavaScript 1.3+, JScript 5.5+
Nav4.06+, IE5.5+
Syntax
undefined
Description
The undefined property represents an undefined value.
12 0672321416 CH07b 7/24/01 12:07 PM Page 381
Operators 381
Example
Listing 7.196 shows how the undefined property can be used to check whether a vari-
able has been assigned.
var myVar;
// -->
</script>
</html>
goto
JavaScript 1.3+
Nav4+
Syntax
Reserved Keyword
Description
The goto keyword has not been implemented in client-side JavaScript to date. It has
been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
if
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
if(statement){
code;
}
12 0672321416 CH07b 7/24/01 12:07 PM Page 382
Description
The if statement is used to perform logic statements on specific cases. If statement
evaluates to true, code is executed.
Example
In Listing 7.197, you see how the if statement is being used to determine whether the
Tilly boolean value is true.
var Tilly = 1;
// -->
</script>
</body>
</html>
if...else
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
if(statement){
code;
}else(statement){
code;
}
Description
The if...else statement is used to perform logic statements on specific cases. If
statement is satisfied, its statements are executed. Otherwise, the else statement is
evaluated. When statement evaluates to true, code is executed.
Example
In Listing 7.198, you see how the if...else statement is being used to determine
whether the isDog boolean value is true.
12 0672321416 CH07b 7/24/01 12:07 PM Page 383
Operators 383
var isDog = 1;
</body>
</html>
implements
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The implements keyword has not been implemented in server-side JavaScript to date.
It has been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
import
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
import
Description
The import keyword allows a script to import properties, functions, and objects from
a signed script that has exported the information.
12 0672321416 CH07b 7/24/01 12:07 PM Page 384
Example
Listing 7.199 shows how the import keyword is used to import multiple properties
from another script.
// Imports the variables name, city and state from another script.
// This makes those properties accessible to myObj.
import myObj.name;
import myObj.city;
import myObj.state;
// -->
</script>
</body>
</html>
in
JavaScript 1.4
Nav6+, IE5.5+
Syntax
Prop in objectName
Description
The in keyword will return true or false depending on whether a specified property,
prop, is in a specified object, objectName. The property can be a string or numeric
expression representing a property name or array index.
Example
Listing 7.200 shows how the in keyword is used to check to see whether the length
property is in the String object.
Operators 385
// -->
</script>
</body>
</html>
Infinity
JavaScript 1.3+, JScript 1.0+
Nav4.06+, IE3+, Opera3+
Syntax
Infinity
Description
Infinity is a JavaScript keyword that represents positive infinity.
Example
Listing 7.201 shows how the Infinity keyword is used. An input text box is provided
to enter a value to be compared to Infinity. If any number is entered, it will result in
being less than Infinity. However, if the word “Infinity” is entered, it will result in
being equal to Infinity.
input=document.form1.num.value;
<form name=”form1”>
Enter a number to compare against Infinity.
<br><br>
<input type=”text” size=”35” name=”num”>
<br><br>
<input type=”button” value=”Check Number” onClick=’checkNum()’>
</form>
</body>
</html>
instanceof
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The instanceof keyword is used to determine whether a specified object is of a spec-
ified object type. It will return true or false depending on this condition.
Example
Listing 7.202 shows how the instanceof keyword is used to check to see whether the
length property is in the String object.
Operators 387
// -->
</script>
</body>
</html>
int
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The int keyword has not been implemented in JavaScript to date. It has been reserved
for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
interface
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The interface keyword has not been implemented in server-side JavaScript to date. It
has been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
isFinite()
JavaScript 1.3+, ECMAScript 1E+, JScript 3.0+
Nav4.06+, IE4+, Opera3+
Syntax
isFinite()
Description
The isFinite() method is used to determine whether a variable has finite bounds.
12 0672321416 CH07b 7/24/01 12:07 PM Page 388
Example
In Listing 7.203, isFinite() method is used to verify whether the user input value has
finite bounds.
<form name=”form1”>
Enter a number or character into the text box and the click the check value
button to verify if the input has finite bounds.
<br><br>
<input type=”text” name=”text1” size=”3”>
<br><br>
<input type=”button” value=”Check value” onClick=’checkNum()’>
<br>
</form>
</body>
</html>
isNaN()
JavaScript 1.1+, JScript 1.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
isNaN (variable)
Description
The isNaN() function is used to determine whether variable is a valid number.
Example
Listing 7.204, shows how the isNaN() function can be used to check user input.
12 0672321416 CH07b 7/24/01 12:07 PM Page 389
Operators 389
<form name=”form1”>
Enter a number or character into the text box and then click the check value
button to verify if the input is a number.
<br><br>
<input type=”text” name=”text1” size=3>
<br><br>
<input type=”button” value=”Check value” onClick=’checkNum()’>
<br>
</form>
</body>
</html>
java
JavaScript 1.1+
Nav3+, NES2+, Opera 3+
Syntax
java
Description
The java object allows you to access any class within the package java.*. It is shorter
and works the same way as using the packages.java property.
Example
Listing 7.205 shows how the java property can be used to call the lang package and
print out a string to the java console.
12 0672321416 CH07b 7/24/01 12:07 PM Page 390
// -->
</script>
</html>
javaArray
JavaScript 1.1+
Nav4+, NES2+
Syntax
var variable = arrayObject
Description
The javaArray object represents a wrapped Java array that can be accessed from
within a JavaScript program. In most situations, to create a javaArray type, simply
store a java array datatype into a variable in JavaScript and it will automatically cre-
ate the javaArray object. It can also be created by using the newInstance function and
passing in the object to be created as the parameter. Table 7.36 shows the method and
property of the javaArray object.
Example
Listing 7.206 shows how a new javaArray object is created for the String object.
Operators 391
// -->
</script>
</html>
javaArray.length
JavaScript 1.1+
Nav3+, NES2+, Opera3+
Syntax
javaArrayName.length
Description
The length property of the javaArray object allows you to get the length of the
javaArray.
Example
Listing 7.207 shows how the length property can be used to get the length of the
myStrBytes javaArray object. Using a for loop, we loop through the whole length of
the array and print out all its contents.
// -->
</script>
</html>
javaArray.toString
JavaScript 1.1+
Nav3+, NES2+, Opera3+
Syntax
javaArrayName.toString()
Description
The toString() method of the javaArray object returns the string representation of
the javaArray. In JavaScript 1.4, this method is overridden by
java.lang.object.toString.
Example
Listing 7.208 shows how the toString() method is used to output the string represen-
tation of the myStrBytes.
// -->
</script>
</html>
javaClass
JavaScript 1.1+
Nav3+, NES2+, Opera3+
12 0672321416 CH07b 7/24/01 12:07 PM Page 393
Operators 393
Syntax
javaClass = classname
Description
The javaClass object provides you a reference to a single class in the Java package. A
javaClass object is created by assigning a specific class object to a JavaScript defined
variable. Once created, the JavaScript defined variable can access static fields and sta-
tic methods of the instantiated class.
Example
Listing 7.209 shows how the javaClass property is used to reference the Color class
within the java.awt package. After creating the javaClass object, col, a new color is
created using the specified RGB values.
col = package.java.awt.Color
// -->
</script>
</body>
</html>
javaObject
JavaScript 1.1+
Nav3+, NES2+, Opera3+
Syntax
javaObject = new Packages.JavaClass(parms)
Description
The javaObject object is a wrapped Java object that can be accessed within JavaScript
code. It can be created in a script by assigning the return value of any Java method that
returns an object type or by creating a new Java object.
Example
Listing 7.210 shows how the javaObject is used to get the byteValue of a Java Integer
object.
12 0672321416 CH07b 7/24/01 12:07 PM Page 394
// -->
</script>
</html>
javaPackage
JavaScript 1.1+
Nav3+, NES2+, Opera3+
Syntax
Packages.javaPackage
Description
The javaPackage object provides you with a reference to a specified Java Package.
Example
Listing 7.211 shows how the javaPackage is used to access the Java Font package and
create a font object that has the UNDERLINE_ON property.
Operators 395
// -->
</script>
</html>
JSException
JavaScript 1.1+
Nav4+, NES2+
Syntax
a) public JSException()
Description
The JSException object is an exception that is thrown when a piece of JavaScript code
returns an error. It is part of the netscape.javascript package. The s parameter rep-
resents the message string. The filename parameter represents the URL of the file con-
taining the error. The lineNum parameter represents the line number in the file in which
the error occurred. The source parameter represents the string containing the code to
be executed. The token parameter represents the index into the source string where the
error occurred. The constructors listed previously are deprecated in JavaScript 1.4.
Table 7.37 shows the JSException method.
Example
Listing 7.212 shows how a JSException is used within a try...catch block. When
running the eval() method, if the dog object is not defined, an exception will be
thrown. When the catch block catches the exception, it will check to see whether the
exception is a JSException. If it is, doRoutineA is called. Otherwise doRoutineB is
called.
JSException.getWrappedException()
JavaScript 1.4+
Nav6+, IE5.5+
Syntax
JSException.getWrappedException()
Description
The getWrappedException() method is used to unwrap a JSException. Typically,
when JavaScript throws an exception, it is wrapped as an instance of JSException.
Example
Listing 7.213 shows how the getWrappedException() method is used to return the
exception thrown as an unwrapped exception.
JSObject
JavaScript 1.1+
Nav4+, NES2+
Syntax
JSObject
12 0672321416 CH07b 7/24/01 12:07 PM Page 397
Operators 397
Description
The JSObject object is a wrapped instance of the netscape.javascript.JSObject
class. This wrapped instance allows a Java program to manipulate a JavaScript object.
Table 7.38 lists the property and methods associated with the JSObject.
Example
Listing 7.214 shows how a new JSObject object is used to access the properties of the
JavaScript Car object. In Listing 7.215, the JavaScript code to create a Car object is dis-
played.
function Car(model,color,year) {
this.model = model
this.color = color
this.year = year
}
</script>
// -->
</html>
JSObject.call()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.call(methodName, argArray)
Description
The call() method allows you to invoke a JavaScript method from within a Java pro-
gram. Pass it the methodName and an array representing an array of Java objects used
to pass arguments to the JavaScript method.
Example
Listing 7.216 shows how the call() method is used to inform the user of the browser
name and version. When the applet is loaded in the browser, the init() method con-
tains a call to the JavaScript’s test function, which provides the alert. Listing 7.217
shows the HTML code for loading the applet.
Operators 399
<body>
<applet code=”myApplet.class” name=”myApplet” width=150 height=25 mayscript>
</applet>
<form name=”form1”>
<input type=”button” value=”Set String”
➥onClick=”document.myApplet.setString(document.form1.str.value)”><br>
<input type=”text” size=”20” name=”str”>
</form>
</body>
</html>
JSObject.equals()
JavaScript 1.1+
Nav3+, NES2+
12 0672321416 CH07b 7/24/01 12:07 PM Page 400
Syntax
JSObject.equals()
Description
The equals() method is used to check whether two JSObjects refer to the same
instance.
Example
Listing 7.218 shows how the equals() method is used to see whether the win object
and the joe object are equal.
if(joe.equals(win) ){
System.out.println(“Objects are equal”);
}
else {
System.out.println(“Objects are NOT equal”);
}
}
JSObject.eval()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.eval()
Description
The eval() method is used to execute a JavaScript expression.
Example
Listing 7.219 shows how the eval() method is used in the Java program to call an
alert() JavaScript function indicating that the Applet is painting. Listing 7.220 shows
the HTML for loading the Applet.
Operators 401
<form name=”form1”>
<input type=”button” value=”Set String”
onClick=”document.myApplet.setString(document.form1.str.value)”><br>
<input type=”text” size=”20” name=”str”>
</form>
</body>
</html>
JSObject.getMember()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.getMember()
12 0672321416 CH07b 7/24/01 12:07 PM Page 402
Description
The getMember() method is used to retrieve the value of a property of a JavaScript
object.
Example
Listing 7.221 shows how the getMember() method is used to get the properties of the
new car object created from the JavaScript script.
Listing 7.222 shows the JavaScript code for creating a new Car object.
function Car(model,color,year) {
this.model = model
this.color = color
this.year = year
}
</script>
// -->
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 403
Operators 403
JSObject.getSlot()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.getSlot()
Description
The getSlot() method is used to get the value of an array element of a JavaScript
object.
Example
Listing 7.223 shows how the getSlot() method is used to get the value of the second
array element of a Car object.
JSObject.getWindow()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.getWindow()
Description
The getWindow() method is a static method that returns a handle to the current
Navigator window.
Example
Listing 7.224 shows how the getWindow() method is used to assign a window handle
to the win JSObject.
12 0672321416 CH07b 7/24/01 12:07 PM Page 404
JSObject.removeMember()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.removeMember()
Description
The removeMember() method is used to remove a property of a JavaScript object.
Example
Listing 7.225 shows how the removeMember() method is used to remove the year prop-
erty of the car object.
Listing 7.226 shows the JavaScript code for creating a new car object.
function Car(model,color,year) {
this.model = model
this.color = color
this.year = year
}
12 0672321416 CH07b 7/24/01 12:07 PM Page 405
Operators 405
</script>
// -->
</html>
JSObject.setMember()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.setMember()
Description
The setMember() method is used to set the value of a property of a JavaScript object.
Example
Listing 7.227 shows how the setMember() method is used to set the value of the model
property in the JavaScript car object (defined in Listing 7.xxx).
Listing 7.227 Example Using the setMember() Method to Set the model
Property
import netscape.javascript.*;
JSObject.setSlot()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.setSlot()
Description
The setSlot() method is used to set the value of an array element of a JavaScript
object.
12 0672321416 CH07b 7/24/01 12:07 PM Page 406
Example
Listing 7.228 shows how the setSlot() method is used to set the value of the second
array element to the string 0-60.
JSObject.toString()
JavaScript 1.1+
Nav3+, NES2+
Syntax
JSObject.toString()
Description
The toString() method is used to obtain the string representation of the JSObject.
Example
Listing 7.229 shows how the toString() method is used to get the string representa-
tion of the win object.
label
JavaScript 1.2+, JScript 1.0+
Nav4+, NES3+, IE3+
Syntax
label:
code;
12 0672321416 CH07b 7/24/01 12:07 PM Page 407
Operators 407
Description
The label keyword provides an identifier that can be used with break or continue to
indicate where a program should continue execution. You can associate a block of
JavaScript statements with each other using a label. When a label is called using break
or continue, code is executed.
Example
Listing 7.230 shows an example of the label statement in conjunction with break.
</body>
</html>
long
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
12 0672321416 CH07b 7/24/01 12:07 PM Page 408
Description
The long keyword has not been implemented in server-side JavaScript to date. It has
been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
Math()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
Core JavaScript Object
Description
The Math object is a built-in object containing properties and methods used for mathe-
matical computation. It is a predefined JavaScript object and can be accessed without
the use of a constructor or calling method. All Math properties and methods are static.
Table 7.39 shows the different methods and properties of the Math object.
Operators 409
Example
Listing 7.231 shows how to create a new Math object.
</body>
</html>
Math.abs()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.abs (num)
Description
The abs() method of the Math object is used to calculate the absolute value of num
compared to the Math object on which it is invoked.
Example
Listing 7.232 shows how to use the abs() method and what it returns.
12 0672321416 CH07b 7/24/01 12:07 PM Page 410
<form name=”form1”>
This example calculates the absolute value of the number entered.
<br><br>
Enter Number:
<input type=”text” name=”input” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
Answer:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.acos()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.acos(num)
Description
The acos() method of the Math object is used to calculate the arccosine of a number.
The return value is between 0 and PI and is measured in radians. If the return value is
outside this range, 0 is returned.
Example
Listing 7.233 shows how the acos() method is used and what values can be returned.
Operators 411
<form name=”form1”>
This example calculates the arccosine of the number entered.
<br><br>
Enter Number:
<input type=”text” name=”input” size=10>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
The arccosine is:
<input type=”text” name=”answer” size=10>
</form>
</body>
</html>
Math.asin()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.asin (num)
Description
The asin() method of the Math object calculates and returns the arcsine of a number.
The return value is –PI/2 and PI/2 in radians. If the return value is not within this range,
0 is returned.
Example
Listing 7.234 shows how the asin() method is used.
<form name=”form1”>
This example calculates the arcsine of the entered number.
<br><br>
Enter Number:
<input type=”text” name=”input” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
The arcsine is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.atan()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.atan (num)
Description
The atan()method of the Math object is used to calculate the arctangent of a number.
The return value is a numeric value between –PI/2 and PI/2 radians.
Example
Listing 7.235 shows how the atan() method is used to calculate the arctangent of a
number.
Operators 413
document.form1.answer.value = result;
}
// -->
</script>
<form name=”form1”>
This example calculates the arctangent of the input number.
<br><br>
Enter Number:
<input type=”text” name=”input” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
The arctan is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.atan2()
JavaScript 1.0+, ECMAScript 1E+, JScript 3.0+
Nav2+, NES2+, IE4+
Syntax
math.atan2(num1, num2)
Description
The atan2() method of the Math object is used to calculate the arctangent of the quo-
tient of its parameters. It returns a numeric value between –PI and PI representing the
angle theta of an (x, y) point.
Example
Listing 7.236 shows an example of how the atan2() method is used. The two inputs
are taken and stored in variables, inputNum1 and inputNum2. The atan2() method is
then called using the user input, and the result is stored in the variable result.
<form name=”form1”>
Enter First Number:
<input type=”text” name=”input1” size=”10”>
<br>
Enter Second Number:
<input type=”Text” name=”input2” size=”10”>
<br><br>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
Answer:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.ceil()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.ceil (num)
Description
The ceil() method of the Math object is used to calculate the smallest integer that is
greater than or equal to the number passed in as a parameter. This is similar to getting
the ceiling of a number.
Example
Listing 7.237 shows how the ceil() method is used to get the smallest integer, which
is greater than or equal to the number input by the user.
Operators 415
<form name=”form1”>
This example calculates ceiling of the entered number.
<br><br>
Enter First Number:
<input type=”text” name=”input” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
The ceil output is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.cos()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.cos (num)
Description
The cos() method of the Math object is used to calculate the cosine of a number. It
returns a numeric value between –1 and 1, representing the cosine of an angle.
Example
Listing 7.238 shows how the cos() method is used to get the cosine of the number
input by the user.
<form name=”form1”>
This example calculates the cosine of the entered number.
<br><br>
Enter First Number:
<input type=”text” name=”input” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
The cosine is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.E
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.E
Description
The E property of the Math object is used to get the value of Euler’s constant. This is
approximately 2.718.
Example
Listing 7.239 shows how the E property is used.
Operators 417
}
// -->
</script>
<form name=”form1”>
Click on the button to get Euler’s constant.
<br><br>
Euler’s constant is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
Math.exp()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.exp(num)
Description
The exp() method of the Math object is used to calculate an exponent in which the base
is Euler’s constant (the base of the natural logarithms).
Example
Listing 7.240 shows how the exp() method is used to calculate an exponential value
using the number input by the user.
<form name=”form1”>
Enter First Number:
12 0672321416 CH07b 7/24/01 12:07 PM Page 418
</body>
</html>
Math.floor()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.floor (num)
Description
The floor() method of the Math object is used to get the largest integer number, which
is equivalent to or less than the number passed as the parameter.
Example
Listing 7.241 shows how the floor() method is used.
<form name=”form1”>
This example calculates the floor of the number entered.
<br><br>
Enter First Number:
<input type=”text” name=”input” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
12 0672321416 CH07b 7/24/01 12:07 PM Page 419
Operators 419
</body>
</html>
Math.LN10
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.LN10
Description
The LN10 property of the Math object is used to get the natural logarithm of 10. This is
approximately equal to 2.302.
Example
Listing 7.242 shows how the LN10 property is used. When the user clicks the button,
the doMath function is called, which calculates the natural logarithm of 10 and displays
the result in the input box.
<form name=”form1”>
The Natural Logarithm of 10 is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 420
Math.LN2
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.LN2
Description
The LN2 property of the Math object is used to get the natural logarithm of 2. This is
approximately equal to 0.693.
Example
Listing 7.243 shows how the LN2 property is used to get the natural logarithm of 2.
<form name=”form1”>
The Natural Logarithm of 2 is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
Math.log()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.log(num)
12 0672321416 CH07b 7/24/01 12:07 PM Page 421
Operators 421
Description
The log() method of the Math object is used to calculate the natural logarithm (base
E) of a number.
Example
Listing 7.244 shows how the log() method is used.
<form name=”form1”>
This example calculates the natural log of the number entered.
<br><br>
Enter First Number:
<input type=”text” name=”input” size=”15”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
The log is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.LOG10E
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.LOG10E
12 0672321416 CH07b 7/24/01 12:07 PM Page 422
Description
The LOG10E property of the Math object calculates the base 10 logarithm of Euler’s con-
stant. The return value is approximately 0.434.
Example
Listing 7.245 shows how the LOG10E property is used. When the user chooses the
Calculate button, the doMath function is executed, which calculates the base 10 loga-
rithm of Euler’s constant and outputs the result in the text box.
<form name=”form1”>
The Base 10 logarithm of Euler’s constant is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
Math.LOG2E
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.LOG2E
Description
The LOG2E property of the Math object calculates the base 2 logarithm of Euler’s
constant. The return value is approximately 1.442.
12 0672321416 CH07b 7/24/01 12:07 PM Page 423
Operators 423
Example
Listing 7.246 shows how the LOG2E property is used.
<form name=”form1”>
The Base 2 logarithm of Euler’s constant is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
Math.max()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.max(num1, num2)
Description
The max() method of the Math object gets the maximum number of the two parameters
passed to it. The larger value is returned as the result.
Example
Listing 7.247 shows how the max() method is used to get the larger of two values.
<form name=”form1”>
This example takes the two numbers entered and determines which is
the larger number.
<br><br>
Enter First Number:
<input type=”text” name=”input1” size=”10”>
<br>
Enter Second Number:
<input type=”text” name=”input2” size=”10”>
<input type=”button” value=”Show Max number” onClick=’doMath()’>
<br>
The Maximum number is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.min()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.min(num1, num2)
Description
The min() method of the Math object gets the minimum number of the two number
parameters passed to it. The smaller value is returned as the result.
Example
Listing 7.248 shows how to use the Math.min() method.
12 0672321416 CH07b 7/24/01 12:07 PM Page 425
Operators 425
<form name=”form1”>
This example takes the two numbers entered and determind which is
the smaller number.
<br><br>
Enter First Number:
<input type=”text” name=”input1” size=”10”>
<br>
Enter Second Number:
<input type=”text” name=”input2” size=”10”>
<input type=”button” value=”Show Min number” onClick=’doMath()’>
<br>
The Minimum number is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.PI
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.PI
Description
The PI property of the Math object is used to get the constant PI. This is approximately
3.14159.
12 0672321416 CH07b 7/24/01 12:07 PM Page 426
Example
Listing 7.249 shows how the PI property is used. When the user clicks the Calculate
button, the doMath function is called, which calculates the value of PI and returns the
result to the text box.
<form name=”form1”>
The Approximate value of PI is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
Math.pow()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.pow(num1, num2)
Description
The pow() method of the Math object is used to calculate an exponent power.
Example
Listing 7.250 shows how the pow() method is used.
Operators 427
<form name=”form1”>
Enter Base number:
<input type=”text” name=”input1” size=”10”>
<br>
Enter exponent to be raised to:
<input type=”text” name=”input2” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
The result is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.random()
JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
math.random(num)
Description
The random() method of the Math object is used to obtain a random number between
the values 0 and 1.
Example
Listing 7.251 shows how the random() method is used to calculate random numbers.
<form name=”form1”>
The random number is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
Math.round()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.round(num)
Description
The round() method of the Math object is used to round a number to its nearest inte-
ger value. If the fractional portion of the number is .5 or greater, the result is rounded
to the next highest integer. If the fractional portion of number is less than .5, the result
is rounded to the next lowest integer.
Example
Listing 7.252 shows how the round() method is used.
Operators 429
<form name=”form1”>
Enter Number:
<input type=”text” name=”input1” size=”10”>
<input type=”button” value=”Round” onClick=’doMath()’>
<br>
The rounded value is:
<input type=”text” name=”answer” size=”10”>
</form>
</body>
</html>
Math.sin()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.sin (num)
Description
The sin() method of the Math object is used to calculate the sine of a number. It returns
a numeric value between –1 and 1.
Example
Listing 7.253 shows how the sin() method is used.
</body>
</html>
Math.sqrt()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.sqrt (num)
Description
The sqrt() method of the Math object is used to calculate the square root of a number.
If the return value is outside the required range, sqrt() returns 0.
Example
Listing 7.254 shows how the sqrt() method is used.
<form name=”form1”>
Enter Number:
<input type=”text” name=”input1” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
12 0672321416 CH07b 7/24/01 12:07 PM Page 431
Operators 431
<br>
The square root is:
<input type=”text” name=”answer” size=”20”>
</form>
</body>
</html>
Math.SQRT1_2
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.SQRT1_2
Description
The SQRT1_2 property of the Math object returns the square root of one half, which is
approximately 0.707.
Example
Listing 7.255 shows how SQRT1_2 can be used. The function, doMath, returns the
square root of 1/2 to the text box on the page.
<form name=”form1”>
The square root of 1/2 is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 432
Math.SQRT2
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.SQRT2
Description
The SQRT2 property of the Math object returns the value of the square root of 2. This is
approximately equal to 1.414.
Example
Listing 7.256 shows how the SQRT2 property is used. The function, doMath, returns the
square root of 2 to the text box on the page.
<form name=”form1”>
The square root of 2 is:
<input type=”text” name=”answer” size=”20”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
</form>
</body>
</html>
Math.tan()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
math.tan (num)
12 0672321416 CH07b 7/24/01 12:07 PM Page 433
Operators 433
Description
The tan() method of the Math object is to calculate the tangent of a number. It returns
a value representing the tangent of an angle.
Example
Listing 7.257 shows how the tan() method is used.
<form name=”form1”>
This example calculates the tangent of the entered number.
<br><br>
Enter Number:
<input type=”text” name=”input1” size=”10”>
<input type=”button” value=”Calculate” onClick=’doMath()’>
<br>
The tangent is:
<input type=”text” name=”answer” size=”20”>
</form>
</body>
</html>
Math.toSource()
JavaScript 1.3+
Nav4.06+
Syntax
math.toSource()
Description
The toSource()method of the Math object is used to create a copy of the object. It
returns a string representation of an object, which can be passed to the eval() method
to create a copy of the object.
12 0672321416 CH07b 7/24/01 12:07 PM Page 434
Example
Listing 7.258 shows how the toSource() method is used to make a copy of the Math
object.
<form name=”form1”>
Click on the button to create a copy of a Math object.
<br><br>
<input type=”button” value=”Copy” onClick=’copy()’>
<br>
The result of toSource is:
<input type=”text” name=”answer” size=”20”>
</form>
</body>
</html>
Math.toString()
JavaScript 1.0+, JScript 3.0+
Nav2+, NES2+, IE4+
Syntax
math.toString()
Description
The toString() method of the Math object returns a string value representing the
object.
Example
Listing 7.259 shows how the toString() method is used to get a string value repre-
senting the Math object.
12 0672321416 CH07b 7/24/01 12:07 PM Page 435
Operators 435
<form name=”form1”>
<input type=”button” value=”Get String” onClick=’copy()’>
<br>
The result of toString is:
<input type=”text” name=”answer” size=”20”>
</form>
</body>
</html>
Math.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
math.unwatch (prop)
Description
The unwatch() method of the Math object is used to turn off the watch on a particular
property specified by prop. It is inherited from the Object object; however it cannot be
used because math properties are read-only.
Example
All math properties are read-only; therefore, no example can be provided.
Math.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
math.watch( prop, handler )
12 0672321416 CH07b 7/24/01 12:07 PM Page 436
Description
The watch() method of the Math object will watch for an assignment to a specific prop-
erty, prop. When an assignment is made, a specified handler will be called to perform
a user-defined function. It is inherited from the Object object; however, it cannot be
used because math properties are read-only.
Example
Math properties are read-only; therefore, no example is provided.
NaN
JavaScript 1.3+, JScript 1.0+
Nav4.06+, IE3+
Syntax
NaN
Description
The NaN object represents an object that is not equal to any number, including itself.
NaN stands for Not a Number.
Example
Listing 7.260 shows how the NaN object is used within a comparison.
native
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The native keyword has not been implemented in server-side JavaScript to date. It has
been reserved for future use.
12 0672321416 CH07b 7/24/01 12:07 PM Page 437
Operators 437
Example
This keyword has not been implemented, therefore no example is provided.
netscape
JavaScript 1.1+
Nav3+, NES2+, Opera3+
Syntax
netscape
Description
The netscape object allows you to access any class within the package netscape.*. It
is shorter and works the same way as using the packages.netscape property.
Example
Listing 7.261 shows how the netscape property can be used to determine whether the
current browser supports the netscape package.
// -->
</script>
</body>
</html>
new
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
new
12 0672321416 CH07b 7/24/01 12:07 PM Page 438
Description
The new operator is used to create a new object.
Example
Listing 7.262 shows how new is used to create a new Array object.
// -->
</script>
</body>
</html>
null
JavaScript 1.2+, JScript 3.0+, ECMAScript 1.0+
Nav4+, NES3+, IE4+
Syntax
Reserved Keyword
Description
The null keyword has not been implemented in server-side JavaScript to date. It has
been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
Number()
JavaScript 1.2+, ECMAScript 1.0+
Nav4+, NES3+, IE5+
Syntax
Number (obj)
12 0672321416 CH07b 7/24/01 12:07 PM Page 439
Operators 439
Description
The Number() method takes an object, obj, as input and converts it to a number. If the
object is a string that is not a well-formed numeric literal, NaN is returned.
Example
Listing 7.263 shows an example of the Number() method. A new Date object is created
and converted to a number.
// -->
</script>
</html>
Number()
JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
var variable = new Number(value)
Description
The Number() object represents numeric value types. You can create a Number() object
by specifying a value in the parameter for the number constructor. Table 7.40 shows the
different methods and properties of the Number() object.
Example
Listing 7.264 shows how a new Number object is created.
</body>
</html>
Number.constructor
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE4+
12 0672321416 CH07b 7/24/01 12:07 PM Page 441
Operators 441
Syntax
Number.constructor
Description
The constructor property of the Number object specifies the function that creates the
object.
Example
Listing 7.265 shows an example of the constructor property.
</html>
Number.MAX_VALUE
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
Number.MAX_VALUE
Description
The MAX_VALUE property of the Number object is used to get the maximum representable
value for a number. This is approximately: 1.79E+308.
Example
Listing 7.266 shows how the MAX_VALUE property is used.
if((9999*9999) != Number.MAX_VALUE){
document.write(“The number is not greater than the maximum value”);
}
// -->
</script>
</body>
</html>
Number.MIN_VALUE
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
Number.MIN_VALUE
Description
The MIN_VALUE property of the Number object is used to get the minimum possible
numeric value known to JavaScript. This is approximately: 2.22E–308.
Example
Listing 7.267 shows how the MIN_VALUE property is used.
if((0.00000002) != Number.MIN_VALUE){
document.write(“The number is not the minimum value”);
}
// -->
</script>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 443
Operators 443
Number.NaN
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
Number.NaN
Description
The NaN property of the Number object represents a value that is not equal to any
numeric value.
Example
Listing 7.268 shows how to use the NaN property. An integer constant, 123, is compared
to the NaN constant to see whether it is a numeric value.
if(123 == Number.NaN){
document.write(“This is not a number”);
}
// -->
</script>
</body>
</html>
Number.NEGATIVE_INFINITY
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
Number.NEGATIVE_INFINITY
Description
The NEGATIVE_INFINITY property of the Number object represents a negative infinity
number. It is returned when a calculation returns a negative number greater than the
largest negative number in JavaScript.
12 0672321416 CH07b 7/24/01 12:07 PM Page 444
Example
Listing 7.269 shows how the NEGATIVE_INFINITY property is used. The sqrt() method
is used on a number and the result is compared to NEGATIVE_INFINITY.
if((Math.sqrt(-2)) != Number.NEGATIVE_INFINITY_){
document.write(“This is not equal to NEGATIVE_INFINITY”);
}
else{
document.write(“This is equal to NEGATIVE_INFINITY”);
}
// -->
</script>
</body>
</html>
Number.POSITIVE_INFINITY
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
Number.POSITIVE_INFINITY
Description
The POSITIVE_INFINITY property of the Number object represents a positive infinity
number. It is returned when a calculation returns a positive number greater than the
largest number in JavaScript.
Example
Listing 7.270 shows how the POSITIVE_INFINITY property is used.
Operators 445
// -->
</script>
</body>
</html>
Number.prototype
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
Number.prototype.property
Number.prototype.method
Description
The prototype property of the Number object allows you to add properties or methods
to all instances of this class.
Example
Listing 7.271 shows how the prototype property is used.
</body>
</html>
Number.toExponential()
JavaScript 1.3+, ECMAScript 3E+
Nav6+, IE5.5+
Syntax
number.toExponential()
Description
The toExponential()method of the Number object is used to get an exponential rep-
resentation of the Number object.
Example
Listing 7.272 shows how the toExponential() method is used.
// -->
</script>
12 0672321416 CH07b 7/24/01 12:07 PM Page 447
Operators 447
Number.toFixed()
JavaScript 1.4+, ECMAScript 3E+
Nav6+, IE5.5+
Syntax
number.toFixed(num)
Description
The toFixed() method of the Number object is used to get a fixed-point string repre-
sentation of the Number object. The num parameter represents the number of digits after
the decimal point.
Example
Listing 7.273 shows how the toFixed() method is used to get the fixed form of the
standard Number object.
// -->
</script>
Number.toLocaleString()
JavaScript 1.4+, ECMAScript 3E+, JScript 1.0+
Nav6+, IE5.5+, Opera5+
Syntax
number.toLocaleString()
Description
The toLocaleString()method of the Number object is used to get a string value that
represents the Number object. The value will be formatted according to the conventions
of the host environment’s current locale.
Example
Listing 7.274 shows how the toLocaleString() method is used to display the string
value of myNum.
12 0672321416 CH07b 7/24/01 12:07 PM Page 448
// -->
</script>
Number.toPrecision()
JavaScript 1.4+, ECMAScript 3E+
Nav6+, IE5.5+
Syntax
number.toPrecision(num)
Description
The toPrecision()method of the Number object returns a string representation of the
number in the format of one digit before the significand’s decimal point and num-1 dig-
its after the diginificand’s decimal point.
Example
Listing 7.275 shows how the toPrecision() method is used.
// -->
</script>
Number.toSource()
JavaScript 1.3+, ECMAScript 1E+
Nav4.06+
Syntax
number.toSource()
12 0672321416 CH07b 7/24/01 12:07 PM Page 449
Operators 449
Description
The toSource()method of the Number object is used to get a string representation of
the Number object.
Example
Listing 7.276 shows how the toSource() method is used.
Number.toString()
JavaScript 1.1+, ECMAScript 1E+, JScript 1.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
number.toString()
Description
The toString() method of the Number object is used to get a string representation of
the Number object.
Example
Listing 7.277 shows how the toString() method is used.
Number.unwatch()
JavaScript 1.1+, JScript 3.0+
Nav3+, NES2+, IE4+
12 0672321416 CH07b 7/24/01 12:07 PM Page 450
Syntax
number.unwatch(prop)
Description
The unwatch() method of the Number object will remove a watch point on a property
set by the watch() method.
Example
Listing 7.278 shows an example for the unwatch() method.
myNum.p = 2;
// Remove the watchpoint.
myNum.unwatch(“p”);
myNum.p = 3;
myNum.p = 4;
// -->
</script>
</html>
Number.valueOf()
JavaScript 1.1+, JScript 2.0+
Nav3+, NES2+, IE4+
12 0672321416 CH07b 7/24/01 12:07 PM Page 451
Operators 451
Syntax
number.valueOf()
Description
The valueOf() method of the Number object is used to get the primitive value of a
Number object as a number data type.
Example
Listing 7.279 shows an example for the valueOf() method. A Number object is created
and set to myNum. The document then outputs the result of performing a valueOf func-
tion on the number.
// -->
</script>
</body>
</html>
Number.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
number.watch(prop, handler)
Description
The watch() method of the Number object will watch for an assignment to a specific
property, prop. When an assignment is made, a specified handler will be called to per-
form a user-defined operation.
Example
Listing 7.280 shows an example for the watch() method.
12 0672321416 CH07b 7/24/01 12:07 PM Page 452
myNum.p = 15;
// -->
</script>
</body>
</html>
Object()
JavaScript 1.1+, ECMAScript 1E+, JScript1.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
var variable = new Object(string)
Description
The Object() object is a primitive data type from which all JavaScript objects are
derived. Table 7.41 shows the different properties and methods of the Object() object.
Operators 453
Example
Listing 7.281 shows how the Object object is used.
</body>
</html>
Object.constructor
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES2+, IE4+
Syntax
object.constructor
Description
The constructor property of the Object object specifies the function that creates the
object.
Example
Listing 7.282 shows an example of the constructor property.
</body>
</html>
Object.eval()
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES2+, IE4+
Syntax
object.eval (string)
Description
The eval() method of the Object object evaluates a string of JavaScript code in ref-
erence to this object. Note: In version 1.4 and later, the eval() method is deprecated
and can no longer be called directly for the Object object. To use eval() in versions
1.4 and 1.5, you must use the top-level eval() function.
Example
Listing 7.283 shows how the eval() method is used. Two variables are declared and
set. A statement multiplying the two variables together is passed to the eval() method
to be evaluated.
var x = 9;
var y = 8;
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 455
Operators 455
Object.prototype
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE4+
Syntax
object.prototype.property
object.prototype.method
Description
The prototype property of the Object object allows the addition of properties or meth-
ods to the Object class.
Example
Listing 7.284 shows how the prototype property is used.
</body>
</html>
Object.toSource()
JavaScript 1.3+
Nav4.06+
Syntax
object.toSource()
Description
The toSource() method is used to get a string representation of the object.
Example
Listing 7.285 shows how the toSource() is used.
12 0672321416 CH07b 7/24/01 12:07 PM Page 456
</body>
</html>
Object.toString()
JavaScript 1.1+, ECMAScript 1E+, JScript 2.0+
Nav3+, NES2+, IE4+, Opera3+
Syntax
object.toString()
Description
The toString() method is used to get a string representation of the Number object.
Example
Listing 7.286 shows how the toString() method is used.
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 457
Operators 457
Object.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
object.unwatch (prop)
Description
The unwatch() method of the Object object allows you to remove a watchpoint set on
a property with the watch() method. This method takes the property, prop, as a para-
meter.
Example
Listing 7.287 shows how the unwatch() object is used. A temporary variable, tmp, is
created and initialized. It is then set to be watched by invoking the watch() method. If
any changes occur to the tmp variable, the inform function is called. After a change is
made to the variable, unwatch() is called to turn off watch operations on the variable.
After watch operations are disabled, the variable can be changed without notification.
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 458
Object.valueOf()
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES2+, IE4+, Opera3+
Syntax
object.valueOf()
Description
The valueOf()method for the Object object is used to obtain the value of the speci-
fied object.
Example
Listing 7.288 shows how the valueOf() method is used.
</body>
</html>
Object.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
object.watch(prop, function)
Description
The watch() method of the Object object is used to watch for the event in which a
property gets assigned a value. When the assignment is made, a user-defined function
is executed. The method itself takes the property to watch, prop, and the function to
call, func, when the event occurs.
12 0672321416 CH07b 7/24/01 12:07 PM Page 459
Operators 459
Example
Listing 7.289 shows how the watch() method is used.
</body>
</html>
package
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The package keyword has not been implemented in server-side JavaScript to date. It
has been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
12 0672321416 CH07b 7/24/01 12:07 PM Page 460
Packages
JavaScript 1.1+
Nav3+, NES2+
Syntax
Packages.packagename
Description
The Packages object is a built-in object that provides access to various Java packages
within the browser. Each property of the Packages object refers to a JavaPackage
object containing references to specific classes. Table 7.42 shows the default packages
included in the Packages object.
Example
Listing 7.290 shows how the Packages object is used. The user is provided with an
input text box. When something is entered in the input box and the button clicked, the
input is sent to the Java Console using the Java classes package.
<form name=”form1”>
This script takes the text input and writes it out to the Java Console
using the Java package.
<br><br>
Input:
12 0672321416 CH07b 7/24/01 12:07 PM Page 461
Operators 461
</body>
</html>
Packages.className
JavaScript 1.1+
Nav3+, NES2+
Syntax
Packages.className
Description
The className property of the Packages object is used to access classes in packages
other than netscape, sun, or java. Just specify the fully qualified name of the package
you want to access for className.
Example
Listing 7.291 shows an example for accessing a fictitious class using the className
property.
// -->
</script>
</body>
</html>
Packages.java
JavaScript 1.1+
Nav3+, NES2+
12 0672321416 CH07b 7/24/01 12:07 PM Page 462
Syntax
Packages.java.className.methodName
Description
The java sub-package of the Packages object refers to the JavaPackage containing the
core Java class library. This sub-package is used for several things, but most notably
for adding security to LiveConnect and accessing the Java Console.
Example
Listing 7.292 shows an example for the java sub-package. It is used to write text to the
Java Console.
// -->
</script>
</body>
</html>
Packages.netscape
JavaScript 1.1+
Nav3+, NES2+
Syntax
Packages.netscape.className.methodName
Description
The netscape sub-package of the Packages object refers to the JavaPackage contain-
ing the netscape package. This sub-package is used by Java applets to access
JavaScript code via LiveConnect. The package itself has two classes: plugin and
javascript.
Example
Use of this package occurs within the code of a Java applet, and not JavaScript code.
However, Listing 7.293 shows an example of calling the netscape package directly to
verify it is implemented in the operating browser.
12 0672321416 CH07b 7/24/01 12:07 PM Page 463
Operators 463
</body>
</html>
Packages.sun
JavaScript 1.1+
Nav3+, NES2+
Syntax
Packages.sun.className.methodName
Description
The sun sub-package of the Packages object refers to the JavaPackage for the sun
property. This sub-package is used for several things, but most notably for adding secu-
rity to LiveConnect.
Example
Use of this package occurs within the code of a Java applet, and not JavaScript code.
However, Listing 7.294 shows an example of calling the sun package directly to verify
it is implemented in the operating browser.
</body>
</html>
parseFloat()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
paraseFloat (string)
Description
The parseFloat() function is used to convert a string to a number.
Example
Listing 7.295 shows how the parseFloat() is used. In the example, parseFloat() is
called with two different strings. The first string, which contains numeric characters, is
converted into a number without any problem. The second string, which contains
alphabetic characters, is unable to be converted into a number.
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 465
Operators 465
parseInt()
JavaScript 1.0+, ECMAScript 1E+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
parseInt(string, radix)
parseInt(string)
Description
The parseInt() method is used to convert a string to an integer. It can take string
input with an optional radix input. The radix input represents the base of the number
in the string.
Example
Listing 7.296 shows how parseInt() is used to parse a string. A few different exam-
ples are shown for different types of strings.
// -->
</script>
</body>
</html>
private
JavaScript 1.2+
Nav4+, NES3+
12 0672321416 CH07b 7/24/01 12:07 PM Page 466
Syntax
Reserved Keyword
Description
The private keyword has not been implemented in server-side JavaScript to date. It
has been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
protected
JavaScript 1.2
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The protected keyword has not been implemented in server-side JavaScript to date. It
has been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
public
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The public keyword has not been implemented in server-side JavaScript to date. It has
been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
RegExp()
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
var variable = new RegExp(pattern, flags)
12 0672321416 CH07b 7/24/01 12:07 PM Page 467
Operators 467
Description
The RegExp() object represents a regular expression that is used for pattern matching.
The creation of the object takes pattern and flags parameters. The pattern is a valid
regular expression. The flags are either or both g (global) and i (ignore case). Table
7.43 displays the properties and methods of the RegExp() object.
Example
Listing 7.297 shows how to use the RegExp object. The user is given an input field,
which is used to input a Social Security Number (SSN). Once entered, the Validate but-
ton is clicked, which checks whether the input is valid. This is performed by using a
RegExp object for the SSN.
// -->
</script>
<form name=”form1”>
Enter your SSN:
<input type=”text” size=”15” name=”ssn”>
<br><br>
<input type=”button” value=”Validate SSN” onClick=’checkInput()’>
<br>
</form>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 469
Operators 469
RegExp,$*
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
RegExp, $*
Description
The RegExp,$* property reflects a multiline string search. This is a Boolean, read-
only value that reflects whether strings should be searched across multiple lines. This
is the same as using the multiline property.
Example
Listing 7.298 shows how to use RegExp,$* for pattern matching.
<body>
<form name=”form1”>
When the text in the text box is changed, and the document is clicked,
an alert box will be displayed showing the value of RegExp.$*.
<br><br>
<textarea name=”mytext” cols=”60” rows=”8” onChange=’getinfo()’>
This is a sample textarea containing some dummy text for
testing purposes. The text in this box will be used to
demonstrate how the multiline property is used. If multiple lines are
read, then RegExp.$* will be true.
</textarea>
12 0672321416 CH07b 7/24/01 12:07 PM Page 470
</body>
</html>
RegExp.$&
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
RegExp.$&
Description
The RegExp.$& property represents the last matched characters. This is the same as
using the lastMatch property.
Example
Listing 7.299 shows how RegExp.$& is used.
</body>
</html>
RegExp,$_
JavaScript 1.2+
Nav4+, NES3+, IE4+
12 0672321416 CH07b 7/24/01 12:07 PM Page 471
Operators 471
Syntax
RegExp,$ _
Description
The RegExp,$_ property represents the input to which a string is matched. This is the
same as using the input property.
Example
Listing 7.300 shows how to use the RegExp,$_ property.
<form name=”form1”>
When the text in the text box below is changed, an alert message
will appear showing the value of the input.
<br><br>
Enter some Text:
<input type=”text” name=”mytext” size=”40” onChange=’getinput()’>
<br>
</form>
</body>
</html>
RegExp.$`
JavaScript 1.2+
Nav4+, NES3+, IE4+
12 0672321416 CH07b 7/24/01 12:07 PM Page 472
Syntax
RegExp.$`
Description
The RegExp.$` property represents the substring preceding the most recent pattern
match. This is the same as using the leftContext property.
Example
Listing 7.301 shows how to use RegExp.$`.
// -->
</script>
</body>
</html>
RegExp.$’
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
RegExp.$’
12 0672321416 CH07b 7/24/01 12:07 PM Page 473
Operators 473
Description
The RegExp.$’ property represents the substring following the most recent pattern
match. This is the same as using the rightContext property.
Example
Listing 7.302 shows how to use RegExp.$’.
// -->
</script>
</body>
</html>
RegExp.$+
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
RegExp.$+
Description
The RegExp.$+ property represents the last parenthesized substring pattern match. This
is the same as using the lastParen property.
12 0672321416 CH07b 7/24/01 12:07 PM Page 474
Example
Listing 7.303 shows how RegExp.$+ is used.
// -->
</script>
</body>
</html>
RegExp.$1,$2,..$9
JavaScript 1.2+, JScript 1.0+
Nav4+, NES3+, IE4+
Syntax
RegExp.$1,$2,..$9
Description
The RegExp.$1,$2,..$9 property represents parenthesized substring matches.
Example
Listing 7.304 shows how RegExp.$1,$2,..$9 is used. The user will enter his phone
number in the input text box and, when the button is clicked, the swap function swaps
the last four digits in the phone number with the first three.
Operators 475
<!--
// Function takes the input and swaps the last 4 digits with the
// first three digits.
function swap(){
re = /(\w+)\D(\w+)/;
str = document.form1.text1.value;
newstr=str.replace(re, “$2, $1”);
document.form1.text2.value = newstr;
}
// -->
</script>
<body>
<form name=”form1”>
Enter your 7 digit phone number in the form xxx-xxxx
<br><br><br>
Phone Number (7 digits):<input type=”text” name=”text1” size=”10”>
<br><br>
<input type=”button” value=”Swap” onClick=’swap()’>
<br><br><br>
Output: <input type=”text” name=”text2” size=”10”>
</form>
</body>
</html>
RegExp.constructor()
JavaScript 1.1+, JScript 3.0+
Nav3+, NES2+, IE4+, Opera5+
Syntax
regexp.constructor
Description
The constructor property of the RegExp object specifies the function that creates the
object.
Example
Listing 7.305 shows how the constructor property is used to create a RegExp object.
</body>
</html>
RegExp.compile()
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
regexp.compile(pattern, flag)
Description
The compile() method of the RegExp object compiles a regular expression object. The
creation of the object takes pattern and flags parameters. The pattern is a valid reg-
ular expression. The flags are either or both g (global) and i (ignore case).
Example
Listing 7.306 shows how to use the compile() method. A pattern is created using the
RegExp constructor. It is then compiled using the compile() method, and the result is
displayed in the text area.
Operators 477
<form name=”form1”>
Click the button below to get the pattern for the following
command: new RegExp(“jane”, “i”);
<br><br><br>
Compiled Pattern: <input type=”text” name=”text1” size=”30”>
<br><br>
<input type=”button” value=”Get Pattern” onClick=’getinfo()’>
</form>
</body>
</html>
RegExp.exec()
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
regexp.exec (string)
Description
The exec() method of the RegExp object executes the search for a match in a specified
string. The results are returned in an array. The string passed contains the string the
regular expression is trying to match in.
Example
In Listing 7.307, you see how the exec() method is used. A regular expression is
defined and executed on the string using the exec() method.
myRe=/xyz*/g;
str = “abcxyzdefhij”
myArray = myRe.exec(str);
RegExp.global
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
regexp.global
Description
The global property of the RegExp object specifies whether the g flag is used with the
regular expression. If so, a global pattern match will be performed.
Example
Listing 7.308 shows how the global property is used. A new RegExp object is created
specifying the global option. When the script is loaded, the expression is checked and
the value of the global property is printed out.
// Define a string.
var str = “What if Angela is wondering about gifs?”;
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 479
Operators 479
RegExp.ignoreCase
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
regexp.ignoreCase
Description
The ignoreCase property of the RegExp object is a flag that informs the user whether
case is to be ignored during pattern matching.
Example
Listing 7.309 shows how ignoreCase is used. A new RegExp object is created specify-
ing the ignoreCase option. When the script is loaded, the expression is checked and
according to the value of the ignoreCase property, an appropriate message is dis-
played.
// Define a string.
var str = “Would Missy and Livvy like some Candy?”;
if (myPat.ignoreCase == true){
document.write(“The “ + “<i>” + “ignoreCase” + “</i>” + “ option WAS
used”);
}
else{
document.write(“The “ + “<i>” + “ignoreCase” + “</i>” + “ was NOT used”);
}
// -->
</script>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 480
RegExp.input
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
regexp.input
Description
The input property of the RegExp object represents the string on which the pattern
matching is performed.
Example
Listing 7.310 shows how to use the input property.
// -->
</script>
<form name=”form1”>
When the text in the text box below is changed, an alert message
will appear showing the value of the input.
<br><br>
Enter some Text:
<input type=”text” name=”mytext” size=”40” onChange=’getinput()’>
<br>
</form>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 481
Operators 481
RegExp.lastIndex
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
regexp.lastIndex
Description
The lastIndex property of the RegExp object is used to get the index of where the next
match begins.
Example
Listing 7.311 shows how the lastIndex property is used. A regular expression for “is”
is created and checked against the string. When found, results are written to the docu-
ment.
document.write(“Found: “ + myArray[0] +
“. Next match starts at index: “ + exp.lastIndex);
// -->
</script>
</body>
</html>
RegExp.lastMatch
JavaScript 1.2+, JScript 5.5+
Nav4+, NES3+, IE4+
Syntax
regexp.lastMatch
Description
The lastMatch property of the RegExp object represents the last matched characters.
12 0672321416 CH07b 7/24/01 12:07 PM Page 482
Example
Listing 7.312 shows how the lastMatch property is used. A RegExp object is created to
look for the string “test” within the str variable. Upon loading the document, the
lastMatch property will display the last pattern to be matched.
</body>
</html>
RegExp.lastParen
JavaScript 1.2+, JScript 5.5+
Nav4+, NES3+, IE4+
Syntax
regexp.lastParen
Description
The lastParen property of the RegExp object represents the last parenthesized sub-
string match. It returns a string value for the last parenthesized substring.
Example
Listing 7.313 shows how the lastParen property is used.
Operators 483
// -->
</script>
</body>
</html>
RegExp.leftContext
JavaScript 1.2+, JScript 5.5+
Nav4+, NES3+, IE4+
Syntax
regexp.leftContext
Description
The leftContext property of the RegExp object represents the substring preceding the
most recent pattern match.
Example
Listing 7.314 shows how the leftContext property is used. A RegExp pattern is used
to get all the contents of the string before the is pattern.
</body>
</html>
RegExp.multiline
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
regexp.multiline
Description
The multiline property of the RegExp object is used to determine whether pattern
matching should be performed across multiple lines.
Example
Listing 7.315 shows how multiline is used.
// -->
</script>
12 0672321416 CH07b 7/24/01 12:07 PM Page 485
Operators 485
<form name=”form1”>
When the text in the text box is changed, and the document is clicked,
an alert box will be displayed showing the value of RegExp.multiline.
<br><br>
<textarea name=”mytext” cols=”60” rows=”8” onChange=’getinfo()’>
This is a sample textarea containing some dummy text for
testing purposes. The text in this box will be used to
demonstrate how the multiline property is used. If multiple lines are
read, then RegExp.multiline will be true.
</textarea>
<br>
</form>
</body>
</html>
RegExp.prototype
JavaScript 1.1+
Nav3+, NES2+, Opera4+
Syntax
regexp.prototype.property
regexp.prototype.method
Description
The prototype property of the RegExp object allows you to add properties or methods
to all instances of this class. After properties or methods have been added, any future
instances of the object will contain the newly created prototype property.
Example
Listing 7.316 shows how the prototype property is used to create a new property
named myProp. Then the property is assigned a value and displayed.
</body>
</html>
RegExp.rightContext
JavaScript 1.2+, JScript 5.5+
Nav4+, NES3+, IE4+
Syntax
regexp.rightContext
Description
The rightContext property of the RegExp object represents the substring following the
most recent pattern match.
Example
Listing 7.317 shows how the rightContext property is used. A pattern is defined so
that all the contents of the string that appear after the be pattern will be displayed.
// -->
</script>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 487
Operators 487
RegExp.source
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
regexp.source
Description
The source property of the RegExp object represents the text of the pattern being used
for pattern matching.
Example:
Listing 7.318 shows how the source property can be used to get the pattern being
matched.
// Create a string.
str = “This is just a sample sentence.”;
myArray = exp.exec(str);
</body>
</html>
RegExp.test()
JavaScript 1.2+
Nav4+, NES3+, IE4+
Syntax
regexp.test()
12 0672321416 CH07b 7/24/01 12:07 PM Page 488
Description
The test() method of the RegExp object is used to test for a pattern match in a string.
Returns boolean value true or false.
Example
Listing 7.319 shows how the test() method is used.
// -->
</script>
</body>
</html>
RegExp.toSource()
JavaScript 1.3+, ECMAScript 1E+
Nav4.06+
Syntax
regexp.toSource()
Description
The toSource() method of the Number object is used to get a string representation of
the Number object.
Example
Listing 7.320 shows how the toSource() method is used.
12 0672321416 CH07b 7/24/01 12:07 PM Page 489
Operators 489
</body>
</html>
RegExp.toString()
JavaScript 1.1+, ECMAScript 1E+
Nav3+, NES2+, IE4+, Opera3+
Syntax
regexp.toString()
Description
The toString() method of the RegExp object is used to get a string representation of
the RegExp object.
Example
Listing 7.321 shows how the toString() method is used.
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 490
RegExp.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
regexp.unwatch(prop)
Description
The unwatch() method of the RegExp object will remove a watch point on a property
set by the watch() method.
Example
Listing 7.322 shows an example for the unwatch() method. A property is created using
the prototype() method. Then a watch point is placed on the newly created property
and a message is displayed when the watch point is hit. When the unwatch() method
is called, the watch point is removed.
function alertme(id,oldValue,newValue)
{
document.writeln(“myExp.” + id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
myExp.p = “or”;
// Remove the watchpoint on p.
myExp.unwatch(“p”);
myExp.p = “cat”;
myExp.p = “dog”;
12 0672321416 CH07b 7/24/01 12:07 PM Page 491
Operators 491
// -->
</script>
</body>
</html>
RegExp.valueOf()
JavaScript 1.1+
Nav3+, NES2+, IE4+
Syntax
regexp.valueOf()
Description
The valueOf()method of the RegExp object is used to get the primitive value of a
RegExp object as a number data type.
Example
Listing 7.323 shows an example for the valueOf() method. A RegExp object is created
and set to myExp. The document then outputs the result of performing a valueOf func-
tion on the RegExp object.
// -->
</script>
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 492
RegExp.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
regexp.watch(prop, handler)
Description
The watch() method of the RegExp object will watch for an assignment to a specific
property. When an assignment is made, a specified handler will be called to perform a
user-defined operation.
Example
Listing 7.324 shows an example for the watch() method. A new property is created
using the prototype method. Then a watch point is set on the newly created property.
When an assignment is made, the alertme function will be called to display a message.
function alertme(id,oldValue,newValue)
{
document.writeln(“myExp.” + id + “ changed from “ + “<b>” +
➥oldValue + “</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
// Set a watchpoint on p.
myExp.watch(“p”,alertme);
myExp.p = “or”;
// -->
</script> type=”text
</body>
</html>
12 0672321416 CH07b 7/24/01 12:07 PM Page 493
Operators 493
return
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
return
Description
The return keyword will exit the existing function and return a value.
Example
Listing 7.325 shows an example of using the return statement to return the value of
the processing from the function.
// Function calls getValue() and fills the tmp input box element
// with the value returned.
function fill(){
var x = getValue();
document.form1.tmp.value = x;
}
// -->
</script>
<form name=”form1”>
Value: <input type=”text” Name=”tmp” Size=”5”>
<br>
<br>
<input type=”button” name=”get” value=”Get Returned Value” onClick=’fill()’>
<br>
<br>
</form>
</body>
</html>
13 0672321416 CH07c 7/24/01 12:12 PM Page 494
ScriptEngine
JScript 2.0+
Syntax
ScriptEngine()
Description
The ScriptEngine()function has three possible return values: JScript, VBScript, and
VBA. When implemented in JavaScript scripts, this function returns JScript.
Example
Listing 7.326 prints the complete version information for the Internet Explorer browser
interpreting the script. In addition to the ScriptEngine property, it also uses other
Internet Explorer specific functions.
//-->
</script>
ScriptEngineBuildVersion
JScript 2.0+
Syntax
ScriptEngineBuildVersion
Description
The ScriptEngineBuildVersion() function contains the actual build number of the
scripting engine contained on the user’s machine.
13 0672321416 CH07c 7/24/01 12:12 PM Page 495
Operators 495
Example
Listing 7.327 prints the build number of the scripting engine interpreting the script.
//-->
</script>
ScriptEngineMajorVersion
JScript 2.0+
Syntax
ScriptEngineMajorVersion()
Description
The ScriptEngineMajorVersion() function contains the actual major version number
of the scripting engine contained on the user’s machine.
Example
Listing 7.328 prints the major version number of the scripting engine interpreting the
script.
//-->
</script>
ScriptEngineMinorVersion
JScript 2.0+
13 0672321416 CH07c 7/24/01 12:12 PM Page 496
Syntax
ScriptEngineMinorVersion()
Description
The ScriptEngineMinorVersion() function contains the actual minor version number
of the scripting engine contained on the user’s machine.
Example
Listing 7.329 prints the minor version number of the scripting engine interpreting the
script.
//-->
</script>
short
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The short keyword has not been implemented in JavaScript to date. It has been
reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
static
JavaScript 1.2+
Nav4+, NES3+,
Syntax
Reserved Keyword
13 0672321416 CH07c 7/24/01 12:12 PM Page 497
Operators 497
Description
The static keyword has not been implemented in JavaScript to date. It has been
reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
String (Function)
JavaScript 1.2+, JScript 3.0+, ECMAScript 1E+
Nav4+, NES3+, IE4+, Opera4+
Syntax
String (var)
Description
The String() function is a top-level function, which is often of the Global object. It
converts the value of any var into a readable string.
Example
In Listing 7.330, we will create an instance of the Date object, and then use the
String() function to write out a readable string version of the date.
//-->
</script>
String (Object)
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
var variable = new String(string) JavaScript1.1+
“string”
13 0672321416 CH07c 7/24/01 12:12 PM Page 498
Description
The String object is one of the core JavaScript objects. Instances are created when a
program constructs an instance using the new keyword and passing it the String object.
In JavaScript 1.0, instances were also created when programmers quoted characters in
their script. Table 7.44 lists the properties and methods used by this object.
Operators 499
Example
Listing 7.331 displays the use of some of the String properties and methods. It con-
tains a single button. After the user clicks the button, a second window is opened.
Various methods are called by a string instance created in the script. The results of such
are displayed in the pop-up window.
// Open a window to store the results and create a new String object.
var myWin = open(“”, “”,”width=450,height=200”);
var myString = new String(“Hello, World!”);
// Call various methods on this instance and write their results to the
// window.
myWin.document.write(“Original String, “ + myString);
13 0672321416 CH07c 7/24/01 12:12 PM Page 501
Operators 501
String.anchor()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.anchor(name)
Description
The anchor() method will convert the string it is called on to an instance of the <a>
tag, setting the name attribute to the name that is passed.
Example
Listing 7.332 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<a name=”HELLO”>Hello, World!</a>
// Write the string to the page after invoking the anchor() method on it.
document.write(myString.anchor(“HELLO”));
//-->
</script>
String.big()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.big()
Description
The big() method will convert the string it is called on to an instance of the <big> tag.
Example
Listing 7.333 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<big>Hello, World!</big>
// Write the string to the page after invoking the big() method on it.
document.write(myString.big());
//-->
</script>
13 0672321416 CH07c 7/24/01 12:12 PM Page 503
Operators 503
String.blink()
JavaScript 1.0+
Nav2+, NES2+
Syntax
string.blink()
Description
The blink() method will convert the string it is called on to an instance of the <blink>
tag. This method is only supported in Netscape Navigator because it is the only browser
that has an implementation of the <blink> tag.
Example
Listing 7.334 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<blink>Hello, World!</blink>
// Write the string to the page after invoking the blink() method on it.
document.write(myString.blink());
//-->
</script>
String.bold()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.bold()
Description
The bold() method will convert the string it is called on to an instance of the <bold>
tag.
13 0672321416 CH07c 7/24/01 12:12 PM Page 504
Example
Listing 7.335 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<bold>Hello, World!</bold>
// Write the string to the page after invoking the bold() method on it.
document.write(myString.bold());
//-->
</script>
String.charAt()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.charAt(num)
Description
The charAt() method of an instance of the String object returns the character located
at the indexed, num, position passed. This indexing is done from left to right starting
with the 0 (zero) position. If the num passed is not a valid index in the string, –1 is
returned.
Example
Listing 7.336 creates an instance of a String object. When the page is loaded, the user
is prompted for an index number. After entering the index number and clicking OK, the
character at that indexed location is written to the document. Notice that there is also a
check to see whether the character at that location is a space.
Operators 505
if (myChar == “ “){
document.write(‘<space>’);
}else{
document.write(myChar);
}
//-->
</script>
</body>
</html>
String.charCodeAt()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.charCodeAt(num)
Description
The charCodeAt() method of an instance of the String object returns the ISO-Latin-
1 number of the character located at the indexed, num, position passed. This indexing is
done from left to right starting with the 0 (zero) position. If the num passed is not a valid
index in the string, –1 is returned.
13 0672321416 CH07c 7/24/01 12:12 PM Page 506
Example
Listing 7.337 creates an instance of a String object. When the page is loaded, the user
is then prompted for an index number. After entering the index number and clicking
OK, the ISO-Latin-1 number of the character at that indexed location is written to the
document. Notice that there is also a check to see whether the character at that location
is a space.
//-->
</script>
</body>
</html>
13 0672321416 CH07c 7/24/01 12:12 PM Page 507
Operators 507
String.concat()
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
string.concat(string2)
Description
The concat() method of an instance of the String object concatenates the string in
string2 to the end of string to return a new string.
Example
Listing 7.338 creates two instances of the String object and uses the concat() method
to concatenate them to create a new string. The string is then displayed in an alert box.
//-->
</script>
String.constructor
JavaScript 1.1+, JScript 3.0+, ECMAScript 1E+
Nav3+, NES2+, IE4+, Opera3+
Syntax
string.constructor
Description
The constructor property of the String object specifies the function that creates the
object.
Example
Listing 7.339 shows an example of the constructor property, which is used to check
the type of variable.
13 0672321416 CH07c 7/24/01 12:12 PM Page 508
if(myString.constructor == String){
document.write(“Object created”);
}
//-->
</script>
String.fixed()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.fixed()
Description
The fixed() method will convert the string it is called on to an instance of the <tt>
tag.
Example
Listing 7.340 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<tt>Hello, World!</tt>
// Write the string to the page after invoking the fixed() method on it.
document.write(myString.fixed());
//-->
</script>
13 0672321416 CH07c 7/24/01 12:12 PM Page 509
Operators 509
String.fontcolor()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.fontcolor (hexnum)
string.fontcolor(color)
Description
The fontcolor() method sets the color attribute of an instance of the <font> tag,
which it creates. This attribute can either be passed as the hexadecimal equivalent of
the color or the actual string that represents that color.
Example
Listing 7.341 creates an instance of the String object and uses the document.write()
method to write two instances of the tag to the page. The results of running this script
will be the following:
Hex usage: <font color=”#FF0000”>Hello, World!</font>
<br>Color usage: <font color=”blue”>Hello, World!</font>
//-->
</script>
String.fontsize()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.fontsize(num)
string.fontsize(string2)
13 0672321416 CH07c 7/24/01 12:12 PM Page 510
Description
The fontsize() method sets the size attribute of an instance of the <font> tag, which
it creates. This attribute can be a number between 1 and 7. If you pass the method the
number in the form of a string, the size displayed is relative to the <basefont> tag.
Example
Listing 7.342 creates an instance of the String object and uses the document.write()
method to write two instances of the tag to the page. The results of running this script
will be the following:
Hex usage: <font size=”6”>Hello, World!</font>
<br>Color usage: <font size=”-2”>Hello, World!</font>
//-->
</script
String.fromCharCode()
JavaScript 1.2+, JScript 3.0+, ECMAScript 1E+
Nav4+, NES3+, IE4+
Syntax
String.fromCharCode(num1, num2, ..., numN)
String.fromCharCode(keyevent.which)
Description
The fromCharCode() method of the String object returns the characters that corre-
spond to the ISO-Latin-1 numbers (num1, num2, ..., numN) position passed. You can
also pass the method a key event and use the which property to determine which key
has been pressed. The possible key events are KeyDown, KeyPress, and KeyUp.
13 0672321416 CH07c 7/24/01 12:12 PM Page 511
Operators 511
As you can see in the syntax definition, this is a method of the actual String object and
not an instance of this object. Because of this, you might want to store the results gen-
erated by this method into a variable for future processing.
Example
Listing 7.343 invokes the fromCharCode() method on the numbers 88, 89, and 90. The
results of this processing are then written to the user’s page.
//-->
</script>
String.indexOf()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.indexOf(string, num)
string.indexOf(string)
Description
The indexOf() method of an instance of the String object returns the indexed start
position of the string passed. Additionally, you can specify an index, defined by num
in the syntax definition, to start your search for the string specified. This method is the
same as the String.lastIndexOf() method, but it starts at the beginning of the string.
Example
Listing 7.344 creates a simple instance of the String object. This instance is then
passed to the indexOf() method on two occasions with the result written to the user’s
page. The first occasion looks for a space in the string, which returns 6. The second
occasion starts the search at the fourth position, so it returns the location of the letter
“l” in the word “world”.
13 0672321416 CH07c 7/24/01 12:12 PM Page 512
//-->
</script>
String.italics()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.italics()
Description
The italics() method will convert the string it is called on to an instance of the <i>
tag.
Example
Listing 7.345 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<i>Hello, World!</i>
Operators 513
// Write the string to the page after invoking the italics() method on it.
document.write(myString.italics());
//-->
</script>
String.lastIndexOf()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.lastIndexOf(string, num)
string.lastIndexOf(string)
Description
The lastIndexOf() method of an instance of the String object returns the indexed
start position of the string passed, starting from the right and going left. Additionally,
you can specify an index, defined by num in the syntax definition, to start your search
for the string specified. This method is the same as the String.indexOf() method, but
it starts at the end of the string.
Example
Listing 7.346 creates a simple instance of the String object. This instance is then
passed to the lastIndexOf() method on two occasions with the result written to the
user’s page. The first occasion looks for the last occurrence of the letter e in the string,
which returns 16. The second occasion starts the search at the third position, so it
returns the location of the first l in the word “Hello”.
//-->
</script>
String.length
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.length
Description
The length property of an instance of the String object returns the total length of the
string.
Example
Listing 7.347 creates three instances of the String object. The length property of each
of these instances is accessed and written to the user’s page.
//-->
</script>
13 0672321416 CH07c 7/24/01 12:12 PM Page 515
Operators 515
String.link()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.link(URL)
Description
The link() method will convert the string it is called on to an instance of the <a> tag,
setting the href attribute to the URL that is passed.
Example
Listing 7.348 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<a href=”http://www.purejavascript.com”>The online book!</a>
// Write the string to the page after invoking the link() method on it.
document.write(myString.link(‘http://www.purejavascript.com’));
//-->
</script>
String.localeCompare()
JavaScript 1.5+, ECMAScript 3E+
Nav6
Syntax
string.localeCompare (string2)
Description
The localeCompare() method of an instance of the String object compares string
against string2. The resulting numerical value, which can be negative, zero, or posi-
tive, orders the strings in a sort order specified by the system default locale.
13 0672321416 CH07c 7/24/01 12:12 PM Page 516
Example
In Listing 7.349, two strings are created and the localeCompare() method is called to
compare them.
//-->
</script>
String.match()
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
string.match (regexpression)
Description
The match() method of an instance of the String object searches the string in which
it is invoked for the regular expression passed to the method. The regexpression is
made up of a pattern and flags that dictate what is to be matched. The method returns
an array containing the matches found in the string.
TIP
See the reference entry for RegExp for a list of the patterns and flags that can be
used to create a regular expression.
Example
Listing 7.350 creates an instance of the String object and tries to match instances that
contain a space followed by some characters. If any matches were returned into the
array, they are written to the user’s page one at a time.
Operators 517
// Write the contents of the array to the page. This will put
// R, Allen, and Wyke each on a separate line.
for(var i = 0; i < answerArray.length; i++){
document.write(answerArray[i] + ‘<br>’);
}
}
//-->
</script>
String.prototype
JavaScript 1.1+, ECMAScript 1E+, JScript 3.0+
Nav3+, NES2+, IE4+, Opera3+
Syntax
String.prototype.property
String.prototype.method
Description
The prototype property of the String object allows a programmer to add properties
or methods to a core JavaScript object.
Example
Listing 7.351 creates two instances of the String object. Then it prototypes a new
property, type, and a new method, verify(). In the script, the type property is
assigned to the string instances and then they are checked using the verify() method.
The results of the validation are then written to the user’s page.
13 0672321416 CH07c 7/24/01 12:12 PM Page 518
// Create two instances of the String object and load it with a name.
var myString1 = new String(“Mr. R. Allen Wyke”);
var myString2 = new String(“Mr. Robert J. Wyke”);
// Check each of the types of the strings to see if they are valid.
if(myString1.verify()){
document.write(myString1 + “ has a valid type of “ + myString1.type);
}else{
document.write(myString1 + “ has an invalid type of “ + myString1.type);
}
document.write(‘<br>’);
if(myString2.verify()){
document.write(myString2 + “ has a valid type of “ + myString2.type);
}else{
document.write(myString2 + “ has an invalid type of “ + myString2.type);
}
//-->
</script>
13 0672321416 CH07c 7/24/01 12:12 PM Page 519
Operators 519
String.replace()
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
string.replace(regexpression, replacestring)
Description
The replace() method of an instance of the String object searches the string in which
it is invoked for the regular expression passed to the method. The regexpression is
made up of a pattern and flags that dictate what is to be matched. If and when a match
is found, the method returns a new string with that match supplanted with the replace-
ment string passed to the method.
TIP
See the reference entry for RegExp for a list of the patterns and flags that can be
used to create a regular expression.
Example
Listing 7.352 creates an instance of the String object. This instance is then searched
through to see whether any occurrence of the word “Wyke” is found. If so, it is replaced
with “White”.
//-->
</script>
13 0672321416 CH07c 7/24/01 12:12 PM Page 520
String.search()
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
string.search (regexpression)
Description
The search() method of an instance of the String object searches the string in which
it is invoked for the regular expression passed to the method. The regexpression is
made up of a pattern and flags that dictate what is to be matched. The method returns
the indexed start location of the string if it is found and –1 if the string does not con-
tain a regular expression match.
TIP
See the reference entry for RegExp for a list of the patterns and flags that can be
used to create a regular expression.
Example
Listing 7.353 creates an instance of the String object, which is searched for the first
instance of a space. If a match is found, the indexed start position is returned. The
results of running this script are written to the user’s page.
Operators 521
//-->
</script>
String.slice()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.slice(num1, num2)
string.slice(num)
Description
The slice() method of an instance of the String object returns the characters in the
string between the indexed positions num1 and num2 in which the method is invoked.
The string itself is zero based, so the first character is in position 0. It is also possible
to pass num2 as a negative number. In this scenario, the string counts from the end of
the string to end the slice.
As the syntax definition states, it is also possible to pass a single index location to the
method. In this implementation, the method will not stop at a position and will return
all characters until the end of the string.
Example
Listing 7.354 creates an instance of the String object. The slice() method is invoked
on this string and asked to return the first seven characters of the string. The results of
running this script are written to the user’s page.
//-->
</script>
13 0672321416 CH07c 7/24/01 12:12 PM Page 522
String.small()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.small()
Description:
The small() method will convert the string it is called on to an instance of the <small>
tag.
Example
Listing 7.355 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the
following:
<small>Hello, World!</small>
// Write the string to the page after invoking the small() method on it.
document.write(myString.small());
//-->
</script>
String.split()
JavaScript 1.1+, JScript 1.0+, ECMAScript 1E+
Nav3+, NES2+, IE3+, Opera3+
Syntax
string.split(separator, num)
string.split(separator)
string.split(regexpression, num)
string.split(regexpression)
13 0672321416 CH07c 7/24/01 12:13 PM Page 523
Operators 523
Description
The split() method of an instance of the String object splits the string in which it is
invoked into separate strings based on the regexpression or separator passed to the
method. If a regular expression is passed, it is made up of a pattern and flags that dic-
tate what is to be matched. The separator is a string or character that is matched to
perform the separation.
NOTE
If the language attribute of the <script> tag is set to “JavaScript1.2” when
using the second syntactical definition and the separator is a space, consecutive
spaces are treated differently. In JavaScript 1.1, each space would be split and
returned as part of the results. So if there were an instance of three consecutive
spaces, two of the spaces would be returned in the array. Specifying JavaScript 1.2
tells the interpreter to treat the three spaces as a single space, so you are able to
perform proper splits.
The method returns an array containing each of the segments found in the string.
TIP
See the reference entry for RegExp for a list of the patterns and flags that can be
used to create a regular expression.
Example
Listing 7.356 creates an instance of the String object. This instance is then split, look-
ing for a space as the separator, using each of the syntactical definitions. The results are
then written to the user’s page.
Listing 7.356 Using the split() Method to Split the String Passed into
Separate Strings
<script type=”text/javascript” language=”JavaScript1.2”>
<!--
// Write the contents of the array to the page. This will put
// R, Allen, and Wyke each on a separate line.
for(var i = 0; i < arrayName.length; i++){
document.write(‘[‘ + i + ‘]: ‘ + arrayName[i] + ‘<br>’);
13 0672321416 CH07c 7/24/01 12:13 PM Page 524
//-->
</script>
String.strike()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.strike()
Description
The strike() method will convert the string it is called on to an instance of the
<strike> tag.
Example
Listing 7.357 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<strike>Hello, World!</strike>
Operators 525
// Write the string to the page after invoking the strike() method on it.
document.write(myString.strike());
//-->
</script>
String.sub()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.sub()
Description
The sub() method will convert the string it is called on to an instance of the <sub> tag.
Example
Listing 7.358 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<sub>Hello, World!</sub>
// Write the string to the page after invoking the sub() method on it.
document.write(myString.sub());
//-->
</script>
13 0672321416 CH07c 7/24/01 12:13 PM Page 526
String.substr()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.substr(num1, num2)
string.substr (num)
Description
The substr() method of an instance of the String object returns the characters in the
string, starting with the indexed position num1 and counting to num2 characters. The
string itself is zero based, so the first character is in position 0. It is also possible to pass
num1 as a negative number. In this scenario, the string starts from the end of the string
to begin the substring extraction.
As the syntax definition states, it is also possible to pass a single index location to the
method. In this implementation, the method will not stop at a position and will return
all characters until the end of the string.
Example
Listing 7.359 creates an instance of the String object. The substr() method is
invoked on this string and asked to return the first six characters of the string. The
results of running this script are written to the user’s page.
//-->
</script>
13 0672321416 CH07c 7/24/01 12:13 PM Page 527
Operators 527
String.substring()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.substring(num1, num2)
string.substring(num)
Description
The substring() method of an instance of the String object returns the characters in
the string, starting with the indexed position num1 and ending with the character before
num2. The string itself is zero based, so the first character is in position 0.
If you pass num1 as a negative number, it will be treated as 0. Likewise if you pass num2
as a value greater than the String.length property, it will be treated as
String.length. And finally, if num1 equals num2, an empty string is returned.
As the syntax definition states, it is also possible to pass a single index location to the
method. In this implementation, the method will not stop at a position and will return
all characters until the end of the string.
NOTE
If the language attribute of the <script> tag is set to “JavaScript1.2” and a
Navigator 4 browser is interpreting the script, a runtime out of memory error will
be produced if num1 is greater than num2. Without this attribute set, the method
returns a substring beginning with num2 and ending with num1 –1.
Example
Listing 7.360 creates an instance of the String object. The substring() method is
invoked on this string and asked to return the first 10 characters of the string. The
results of running this script are written to the user’s page.
//-->
</script>
String.sup()
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.sup()
Description
The sup() method will convert the string it is called on to an instance of the <sup> tag.
Example
Listing 7.361 creates an instance of the String object and uses the document.write()
method to write the tag to the page. The results of running this script will be the fol-
lowing:
<sup>Hello, World!</sup>
// Write the string to the page after invoking the sup() method on it.
document.write(myString.sup());
//-->
</script>
String.toLocaleLowerCase()
JavaScript 1.5+, JScript 5.5+, ECMAScript 3E+
Nav6+, IE5.5+
Syntax
string.toLocaleLowerCase()
13 0672321416 CH07c 7/24/01 12:13 PM Page 529
Operators 529
Description
The toLocaleLowerCase() method of an instance of a String object converts the char-
acters in that string to all lowercase values. This is often used when a programmer tries
to evaluate a string a user has entered and does not care about case. This method dif-
fers from the toLowerCase() method by yielding its result to the host environment’s
current locale.
Example
Listing 7.362 pops up a prompt box and asks the user to enter various case text. After
the user clicks OK, the lowercase version of the string is written to the page.
//-->
</script>
String.toLocaleUpperCase()
JavaScript 1.5+, JScript 5.5+, ECMAScript 3E+
Nav6+, IE5.5+
Syntax
string.toLocaleUpperCase()
Description
The toLocaleUpperCase() method of an instance of a String object converts the char-
acters in that string to all uppercase values. This is often used when a programmer is
trying to evaluate a string a user has entered, and case is not an issue. This method dif-
fers from the toUpperCase() method by yielding its result to the host environment’s
current locale.
Example
Listing 7.363 pops up a prompt box and asks the user to enter various case text. After
the user clicks OK, the uppercase version of the string is written to the page.
13 0672321416 CH07c 7/24/01 12:13 PM Page 530
//-->
</script>
String.toLowerCase()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.toLowerCase()
Description
The toLowerCase() method of an instance of a String object converts the characters
in that string to all lowercase values. This is often used when a programmer tries to
evaluate a string a user has entered and does not care about case.
Example
Listing 7.364 pops up a prompt box and asks the user to enter various case text. After
the user clicks OK, the lowercase version of the string is written to the page.
Operators 531
//-->
</script>
String.toSource()
JavaScript 1.3+, JScript 3.0+, ECMAScript 2E+
Nav4.06+, IE4+
Syntax
string.toSource()
String.toSource()
Description
The toSource() method of the String object will return something similar to the fol-
lowing:
function String() { [native code] }
If it is invoked on an instance of the String object, it will contain the source of the
instance you created.
Example
Listing 7.365 creates an instance of the String object. The toSource() method is then
applied to the instance and the results are written to the page. A second
document.write() method writes the results of applying the method to the core object.
The result of this application of the method should be something similar to the
following:
(new String(“Hello, World!”))
// Apply the toSource() method to the instance and the core String
// object.
document.write(myString.toSource() + ‘<br>’);
document.write(String.toSource());
//-->
</script>
13 0672321416 CH07c 7/24/01 12:13 PM Page 532
String.toString()
JavaScript 1.1+, JScript1.0+, ECMAScript 1E+
Nav3+, NES2+, IE3+
Syntax
string.toString()
String.toString()
Description
The toString() method of the String object, if invoked on the core String object,
will return the object type or the name of the constructor that created the object. This
will be something similar to the following:
function String() { [native code] }
If it is invoked on an instance of the String object, it will contain the source string of
the instance you created.
Example
Listing 7.366 creates an instance of the String object. The toString() method is then
applied to the instance and the results are written to the page. A second
document.write() method writes the results of applying the method to the core object.
The result of this application of the method should be something similar to the follow-
ing:
Hello, World!
// Apply the toString() method to the instance and the core String
// object.
document.write(myString.toString() + ‘<br>’);
document.write(String.toString());
//-->
</script>
13 0672321416 CH07c 7/24/01 12:13 PM Page 533
Operators 533
String.toUpperCase()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
string.toUpperCase ()
Description
The toUpperCase() method of an instance of a String object converts the characters
in that string to all uppercase values. This is often used when a programmer is trying
to evaluate a string a user has entered, and case is not an issue.
Example
Listing 7.367 pops up a prompt box and asks the user to enter various case text. After
the user clicks OK, the uppercase version of the string is written to the page.
//-->
</script>
String.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
string.unwatch (property)
Description
The unwatch() method of the String object, is used to turn off the watch on a partic-
ular property specified by property.
13 0672321416 CH07c 7/24/01 12:13 PM Page 534
Example
Listing 7.368 shows how the unwatch() method is used to stop watching the user-
defined property p.
// Change value.
myString.p = 2;
// -->
</script>
String.valueOf()
JavaScript 1.1+, JScript 3.0+, ECMAScript 1E+
Nav3+, NES2+, IE4+, Opera3+
Syntax
string.valueOf()
Description
The valueOf() method returns the primitive value of the object. In terms of an instance
of a String object, this method returns the string itself.
13 0672321416 CH07c 7/24/01 12:13 PM Page 535
Operators 535
Example
In Listing 7.369, an instance of the String object is created. Because the valueOf()
method returns the actual value of the string, “Here is some random text” is writ-
ten to the user’s page.
Listing 7.369 Using the valueOf() Method to Return the Value of the
String() Instance
<script type=”text/javascript” language=”JavaScript1.1”>
<!--
//-->
</script>
String.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
string.watch(property)
Description
The watch() method of the String object, is used to turn on the watch on a particular
property specified by property.
Example
Listing 7.370 shows how the watch() method is used to start watching the user-defined
property p.
// Change value.
myString.p = 2;
// -->
</script>
sun
JavaScript 1.1+
Nav3+, NES2+
Syntax
sun
Description
The sun object allows you to access any class within the package sun.*. It is shorter
and works the same way as using the Packages.sun property.
Example
Listing 7.371 shows how the sun property can be used to determine whether the cur-
rent browser supports the sun package if Java is installed.
Operators 537
// -->
</script>
super
JavaScript 1.3+
Nav4.06+, NES3+,
Syntax
Reserved Keyword
Description
The super keyword was reserved for future use but has not currently been imple-
mented.
Example
No example can be provided because super has not been implemented.
switch
JavaScript 1.2+, JScript 3.0+
Nav4+, NES3+, IE4+
Syntax
switch(expression){
case label1:
code;
break;
case label2:
code;
break;
case labelN:
code;
break;
default:
code;
}
Description
The switch statement allows you to process the expression passed by matching it
with a label—from label1 to labelN. If there is a match, the code following that label
is executed. If the expression passed does not match a label, the default section
is executed. Note that you can have as many labels as you deem necessary in your
script.
Example
Listing 7.372 has a text field and a button. Users are asked to enter a day of the week
into the field. When they press the button, a function is called that contains a switch,
13 0672321416 CH07c 7/24/01 12:13 PM Page 538
which verifies they entered a correct day. If so, an alert box pops up and tells users what
part of the week they entered.
Operators 539
//-->
</script>
</head>
<body>
<form name=”myForm”>
<b>Please enter a day of the week:</b><br>
<input type=”text” value=”” name=”day”>
<input type=”button” value=”Verify” name=”myButton”
onClick=’verifyDay(this.form)’>
</form>
</body>
</html>
synchronized
JavaScript 1.2+, JScript3.0+
Nav4+, NES3+, IE4+
Syntax
Reserved Keyword
Description
The synchronized keyword has not been implemented in JavaScript to date. It has
been reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
this
JavaScript 1.0+, JScript 1.0+
Nav2+, NES2+, IE2+, Opera3+
Syntax
this
this.property
Description
The this keyword is used to refer to the current object and is often used to pass entire
objects, such as those contained in Form instances, to functions and methods specified
in scripts.
Example
Listing 7.373 contains a text box, a text area, and a button. When the user clicks the
button, an onClick event handler passes the form’s information, using the this key-
word, to a function defined in the <head> of the document. The function opens a sec-
ond, smaller window and writes several properties of the form to the page.
13 0672321416 CH07c 7/24/01 12:13 PM Page 540
function displayInfo(form){
Listing 7.374 creates a vehicle object that has three properties: number of doors,
color, and the type of vehicle. The this keyword is used to associate these properties
with the object when it is referenced in other scripts. Further down in the example, an
instance of the vehicle object is created and its properties are written to the page.
Operators 541
//-->
</script>
</head>
<body>
<script type=”text/javascript”>
<!--
throw
JavaScript 1.4+, JScript 5.0+, ECMAScript 3E+
Nav6+, NES3+, IE5+
Syntax
throw exception
Description
The throw element of the JavaScript language was a reserved keyword in the
JavaScript 1.3 and JScript 3.0 languages and in the Netscape Enterprise server 3
environment. Netscape 6 and Internet Explorer 5 were the first browsers to implement
the keyword. It is used to generate an error condition handled by a try..catch
statement or to pass errors found in these statements to higher-level handlers.
13 0672321416 CH07c 7/24/01 12:13 PM Page 542
Example
Listing 7.375 contains a text box and button. The user is asked to insert a numeric value
into the text box and press the button. When this is done, the onClick event handler of
the button calls a function to check whether the entered text was numeric. If it is not,
the myErrorHandler function is called to handle the error. The myErrorHandler func-
tion contains a try..catch statement that allows the programmer to define what hap-
pens on an incorrect entry. In this example, an alert box is displayed containing an
error code and message.
// This function reads in the form data and calls the appropriate error.
function processData(form){
Operators 543
throws
JavaScript 1.2+
Nav4, NES3+
Syntax
Reserved Keyword
Description
The throws keyword has not been implemented in JavaScript to date. It has been
reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
transient
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The transient keyword has not been implemented in JavaScript to date. It has been
reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
13 0672321416 CH07c 7/24/01 12:13 PM Page 544
true
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
Description
The true keyword has not been implemented in JavaScript to date. It has been reserved
for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
try...catch...finally
JScript 5.0+, JavaScript 1.4, ECMAScript 3E+
Nav6+, NES3+, IE5+
Syntax
try{
statement1
throw exception;
}catch(exception if expression){
statement2
throw exception;
}catch(exception){
statement3
throw exception;
}finally{
statement4
throw exception;
}
Description
The try...catch...finally statement of the JavaScript language contained the try,
catch, and finally reserve keywords in the JavaScript 1.3 and JScript 3.0 languages
and in the Netscape Enterprise server 3 environments. Internet Explorer 5 and Netscape
6 were the first browsers to implement this feature.
This statement, of which both catch and finally elements are optional and can con-
tain additional nested try...catch...finally statements, can be used to handle all or
some of the errors that can occur in a script. If an error is not handled by the statement,
it is passed on so other statements can handle the error. If there are no other statements
to handle the error, it is passed to the browser to handle. This usually means a pop-up
dialog box to the user or writing the information to a hidden error dialog.
13 0672321416 CH07c 7/24/01 12:13 PM Page 545
Operators 545
As soon as an error occurs, the value thrown is passed to the catch clause via
exception. If the error cannot be handled, another throw statement is used to pass the
error to a higher-level (or next in line) handler if one has been defined.
statement1 is initially where an error can occur. If an if statement is used in the catch
clause, exception is only caught if expression is true, at which time statement2 is
used to handle the error. If it is not handled, statement3 will be evaluated to handle
the exception. As mentioned, if no block can handle the exception, it is passed back to
the browser. The finally block, which is optional, is executed before this is done.
NOTE
The ability to have multiple catch clauses is an extension within the Netscape 6
environment.
Example
Listing 7.376 contains a text box and button. The user is asked to insert a numeric value
into the text box and click the button. When this is done, the onClick event handler of
the button calls a function to check whether the entered text was numeric. If it is not,
the myErrorHandler function is called to handle the error. The myErrorHandler func-
tion contains a try...catch...finally statement that allows the programmer to
define what happens on an incorrect entry. In this example, an alert box is displayed
containing an error code and message; and a second alert box is popped up, within the
finally block, to signal the end of the error processing.
Two levels of error handling are contained in this example to demonstrate nested usage.
// This function reads in the form data and calls the appropriate error.
function processData(form){
typeof
JavaScript 1.1+, JScript 1.0+
Nav3+, NES2+, IE3+, Opera3+
Syntax
typeof (variable)
13 0672321416 CH07c 7/24/01 12:13 PM Page 547
Operators 547
Description
The typeof unary operator is used to determine the type of the variable passed to it.
The return values of this operator are boolean, number, object, string, or undefined.
NOTE
Because undefined was not fully implemented until JavaScript 1.3 and JScript 3.0,
many supporting browsers return null when passing a variable that has not been
defined.
Example
Listing 7.377 creates boolean, number, object, string, and undefined variable
instances, and then uses the typeof operator to write their types to the page.
Listing 7.377 This Example Uses the typeof Unary Operator to Return
the Types for Four Different Variables
<html>
<head>
<title>Using typeof to determine the type of variables
</title>
<script type=”text/javascript” language=”JavaScript1.1”>
<!--
//-->
</script>
</head>
<body>
<script type=”text/javascript” language=”JavaScript1.1”>
<!--
//-->
</script>
</body>
</html>
13 0672321416 CH07c 7/24/01 12:13 PM Page 548
undefined
JavaScript 1.3+, JScript 5.0+, ECMAScript 1E+
Nav4.06+, IE5+
Syntax
undefined
Description
The undefined property is a primitive value of the Global object. It is returned by vari-
ables that have not had values assigned to them. It is also returned by methods if the
variable being evaluated is not assigned a value. Browsers not supporting this property
return null on the undefined variables.
NOTE
ECMAScript 1st Edition only defines undefined as a primitive value, and does not
define it as a property of the Global object.
Example
Listing 7.378 creates the variable myVariable, and then checks to see whether it is
undefined in an if statement. Note that Opera 3 and later browsers, even though they
do not officially support this property, return null but evaluate the if statement in this
example as true.
// Create a variable.
var myVariable;
unescape()
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
13 0672321416 CH07c 7/24/01 12:13 PM Page 549
Operators 549
Syntax
unescape (string)
Description
The unescape() method takes a hexadecimal value and returns the ISO-Latin-1 ASCII
equivalent. This method performs the opposite operation of the escape() method and
is commonly used to escape user-entered data before form submission.
Example
Listing 7.379 declares a local variable, escapedVal, and passes it to the unescape()
method. The result, “@”, is then written to the page.
// Create a variable.
var escapedVal = “%40”;
//-->
</script>
var
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
var variable
var variable = value
Description
The var keyword is used to declare variables within a script. If it is used in a function,
the scope of the variable is confined to that function. If used outside of a function, it is
not limited and can be accessed anywhere on the page.
Example
Listing 7.380 declares the variable, myVar, in three different locations. It is declared
once at a global level, once within a function where it is the returned value, and once
in a function where it is written to the page.
13 0672321416 CH07c 7/24/01 12:13 PM Page 550
Listing 7.380 This Example Shows Using the var Keyword in Three
Different Instances
<html>
<head>
<title>Examples of the var Keyword</title>
<script type=”text/javascript”>
<!--
//-->
</script>
</body>
</html>
13 0672321416 CH07c 7/24/01 12:13 PM Page 551
Operators 551
VBArray
JScript 3.0+
Syntax
var variable = new VBArray(vbarray)
Description
The VBArray object provides access to Visual Basic safeArrays. These arrays are often
written on the same HTML page and are written in VBScript. Table 7.45 lists the meth-
ods of the VBArray object.
Example
Listing 7.381 calls a VBScript function from a JScript new operator to create a Visual
Basic safe array. The function itself writes the contents of this two-dimensional array
to the user’s page.
</script>
<script type=”text/jscript”>
<!--
//-->
</script>
VBArray.dimensions()
JScript 3.0+
Syntax
vbarray.dimensions()
Description
The dimensions() method of an instance of a VBArray returns the number of dimen-
sions of the array.
Example
Listing 7.382 calls a VBScript function from a JScript new operator to create a Visual
Basic safe array. The array itself writes the contents of this two-dimensional array to
the user’s page. An alert box is also invoked that contains the number of dimensions of
the array.
Operators 553
</script>
<script type=”text/jscript”>
<!--
//-->
</script>
VBArray.getItem()
JScript 3.0+
Syntax
vbarray.getItem(index)
vbarray.getItem(indexA, indexB, ..., indexN)
Description
The getItem() method of an instance of a VBArray returns the value at the index
passed. If the array is multidimensional, you pass the necessary coordinates to access
the location you want.
Example
Listing 7.383 calls a VBScript function from a JScript new operator to create a Visual
Basic safe array. The array itself writes the contents of this two-dimensional array to
13 0672321416 CH07c 7/24/01 12:13 PM Page 554
the user’s page. An alert box is also invoked that contains the value in the second col-
umn of the second row.
</script>
<script type=”text/jscript”>
<!--
//-->
</script>
13 0672321416 CH07c 7/24/01 12:13 PM Page 555
Operators 555
VBArray.lbound()
JScript 3.0+
Syntax
vbarray.lbound(dimension)
vbarray.lbound()
Description
The lbound() method of an instance of a VBArray returns the lowest index value in the
dimension passed. If no dimension is passed, the method defaults to using 1.
Example
Listing 7.384 calls a VBScript function from a JScript new operator to create a Visual
Basic safe array. The array itself writes the contents of this two-dimensional array to
the user’s page. An alert box is also invoked that contains the lowest index number used
in the second dimension.
</script>
<script type=”text/jscript”>
<!--
//-->
</script>
VBArray.toArray()
JScript 3.0+
Syntax
vbarray.toArray()
Description
The toArray() method of an instance of a VBArray returns a valid JScript array from
a VBArray.
Example
Listing 7.385 calls a VBScript function from a JScript new operator to create a Visual
Basic safe array. The array itself writes the contents of this two-dimensional array to
the user’s page. The array is then converted into a valid JScript array and an alert box
is invoked to display a value in this array.
Operators 557
</script>
<script type=”text/jscript”>
<!--
//-->
</script>
VBArray.ubound()
JScript 3.0+
Syntax
vbarray.ubound(dimension)
Description
The ubound() method of an instance of a VBArray returns the highest index value in
the dimension passed.
Example
Listing 7.386 calls a VBScript function from a JScript new operator to create a Visual
Basic safe array. The array itself writes the contents of this two-dimensional array to
13 0672321416 CH07c 7/24/01 12:13 PM Page 558
the user’s page. An alert box is also invoked that contains the highest index number
used in the second dimension.
</script>
<script type=”text/jscript”>
<!--
//-->
</script>
13 0672321416 CH07c 7/24/01 12:13 PM Page 559
Operators 559
void
JavaScript 1.1+, JScript 1.0+, ECMAScript 1E+
Nav3+, NES2+, IE3+
Syntax
void(expression)
void expression
Description
The void operator is used to evaluate an expression without returning a value. This
operator returns undefined and is commonly used in place of the onClick event han-
dler because of various bugs in early Unix Navigator browsers. Note that Opera
browsers do not support this operator.
Example
In Listing 7.387, the void operator is used to keep an <a> link on a page from clicking
through anywhere while still invoking the function specified.
//-->
</script>
</head>
<body>
<a HREF=”javascript:void(myFunc())”>Click here to call the function</A>
</body>
</html>
volatile
JavaScript 1.2+
Nav4+, NES3+
Syntax
Reserved Keyword
13 0672321416 CH07c 7/24/01 12:13 PM Page 560
Description
The volatile keyword has not been implemented in JavaScript to date. It has been
reserved for future use.
Example
This keyword has not been implemented; therefore, no example is provided.
while
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
while(condition){
code;
}
Description
The while conditional statement evaluates the condition passed and executes the code
within the block until the condition is no longer met. This is often used to evaluate the
value of variables, and then perform tasks as well as to iterate through lines in a file
when implemented on the server-side.
Example
Listing 7.388 defines a number and then asks the user for a second number. The user
is continually asked for the second number until a number lower than the defined num-
ber is entered.
Listing 7.388 Using the while Statement to Check the Value Passed In
<html>
<head>
<title>Using while</title>
</head>
<body>
<script type=”text/javascript”>
<!--
// Define the number to compare against and ask the user for a guess.
var indexNum = 30;
var guess = parseInt(prompt(“Please enter a number.”, “”));
Operators 561
// Once the user guesses a number lower than the indexed number
// write the following to the screen.
document.write(‘You have guessed a number lower than the index number. ‘);
document.write(‘You guessed ‘ + guess + ‘ and the index was ‘);
document.write(indexNum + ‘.’);
//-->
</script>
</body>
</html>
with
JavaScript 1.0+, JScript 1.0+, ECMAScript 1E+
Nav2+, NES2+, IE3+, Opera3+
Syntax
with(object){
code;
}
Description
The with statement takes an object and refers to all the properties, methods, and
events of that object within the code without directly referencing the object itself. This
allows you to use these characteristics of an object, such as the Math object, without
specifically referencing the object.
Example
Listing 7.389 creates a variable, and then assigns it and the methods called on it, as a
Math object. Because the with statement is used, you do not have to reference the meth-
ods via the instance of this object.
//-->
</script>
14 0672321416 CH08a 7/24/01 12:16 PM Page 563
Client-Side
CHAPTER 8
Client-Side
This chapter contains all the items and elements making up the
JavaScript language in browsers. As with the other chapters in
this section of the book, each entry includes the version,
browser support, syntax, a description, an example, as well as
many other details.
JavaScript objects are in alphabetical order to provide you with
quick, easy access. The methods, properties, functions, and
event handlers of every object appear alphabetically after the
respective parent object using the simple dot notation used in
all the reference chapters.
NOTE
Throughout this chapter, the following abbreviations will
be used to show browser support for each entry. Each
abbreviation is followed by the browser version when the
entry was first supported and a plus sign (+)if the browser
continues to support the entry today:
NES = Netscape Enterprise Server
Nav = Netscape Communicator
IE = Microsoft’s Internet Explorer
Opera = Opera
14 0672321416 CH08a 7/24/01 12:16 PM Page 564
Anchor
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+, Opera5+
Syntax
document. anchors
Description
An instance of the Anchor object is created with each instance of the <a> tag with the
name attribute (or id attribute) set. An anchor itself is a point in an HTML document
that can be reached by using a hypertext link. The hypertext link that references an
anchor can appear within the same document as the anchor or in a completely differ-
ent Web page. In either case, anchors allow access to specific parts of Web pages rather
than always displaying the top of a document when a Web page is loaded in a browser.
For an anchor to act like an anchor, the name attribute (or id attribute) must be set for
hyperlinks to reference the anchor’s position in the document.
In HTML, the <a> tag is usually accompanied by an href attribute that contains a
hypertext link. This is the complete opposite of the definition of an anchor because
when the href is used in conjunction with the <a> tag, it is a link rather than an anchor.
In fact, JavaScript uses the Link object to access the anchor tag when the tag is used as
a link.
Table 8.1 lists the properties and methods available from the Anchor object.
Example
Listing 8.1 demonstrates how anchors are created and used in HTML documents by
creating a dictionary of fruit. The heading for each letter of the dictionary is designated
as an anchor. At the bottom of the document, some properties of the anchors are
accessed using JavaScript.
14 0672321416 CH08a 7/24/01 12:16 PM Page 565
Client-Side 565
<center>
<h1><u>Fruit Dictionary</u></h1>
Pick a letter:
<a href=”#A”>A</a>|<a href=”#B”>B</a>|<a href=”#C”>C</a>
</center>
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:16 PM Page 566
Anchor.name
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+, Opera5+
Syntax
document. anchors[num].name
Description
The name property holds the name of the anchor and is the way hyperlinks reference
the anchor’s position. This property is originally set by the name attribute in the <a> tag.
Example
Listing 8.2 creates a dictionary of fruit where the heading for each letter of the dictio-
nary is designated as an anchor. At the bottom of the document, the name property of
each anchor is used to create the hyperlink text and reference each anchor.
<center>
<h1><u>Fruit Dictionary</u></h1>
Pick a letter:
<a href=”#A”>A</a>|<a href=”#B”>B</a>|<a href=”#C”>C</a>
</center>
Client-Side 567
document.write(“<a href=’#”,document.anchors[counter].name,”’>”);
document.write(document.anchors[counter].name,”</a>|”);
}
// -->
</script>
</html>
Anchor.text
JavaScript 1.2-1.4
Nav4-4.5
Syntax
document. anchors[num].text
Description
The text property contains the text that appears between the <a> and </a> tags. If other
HTML tags appear within these two anchor tags, the text property might not contain
all the text between the anchor tags.
Example
Listing 8.3 creates a dictionary of fruit where the heading for each letter of the dictio-
nary is designated as an anchor. At the bottom of the document, the text property of
the anchors is used to create hyperlink text that points to each anchor.
<center>
<h1><u>Fruit Dictionary</u></h1>
Pick a letter:
<a href=”#A”>A</a>|<a href=”#B”>B</a>|<a href=”#C”>C</a>
</center>
// -->
</script>
</html>
Anchor.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.anchors[num]. unwatch(property)
Description
The unwatch()method of the Anchor object is used to turn off the watch for a particu-
lar property specified by property.
Example
Listing 8.4 shows how the unwatch() method is used to stop watching the name prop-
erty of the Anchor object after its name has changed to “juice”.
Client-Side 569
// Start watch.
document.anchors[0].watch(“name”,alertme);
// End watch.
document.anchors[0].unwatch(“name”);
Anchor.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.anchors[num]. watch(property,function)
Description
The watch() method of the Anchor object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 8.5 shows how the watch() method is used to start watching the name property
of the Anchor object.
14 0672321416 CH08a 7/24/01 12:16 PM Page 570
// Start watch.
document.anchors[0].watch(“name”,alertme);
Anchor.x
JavaScript 1.2-1.4
Nav4-4.5
Syntax
document. anchors[num].x
Description
The x property contains the x coordinate of the anchor, in pixels, from the left edge of
the document to the anchor.
Example
Listing 8.6 creates a single anchor out of a header at the top of the document. The x
property is used to display the horizontal position of the Anchor object on the bottom
of the page.
<center><a name=”A”><h4>Apple</h4></a></center>
14 0672321416 CH08a 7/24/01 12:16 PM Page 571
Client-Side 571
// -->
</script>
</html>
Anchor.y
JavaScript 1.2-1.4
Nav4-4.5
Syntax
document. anchors[num].y
Description
The y property contains the y coordinate of the anchor, in pixels, from the top edge of
the document to the anchor.
Example
Listing 8.7 creates a single anchor out of a header at the top of the document. The y
property is used to display the vertical position of the Anchor object on the bottom of
the page.
<center><a name=”B”><h4>Banana</h4></a></center>
A long, yellow, curved fruit with a soft core.<br>
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:16 PM Page 572
Applet
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+
Syntax
Core client-side JavaScript object.
Description
In JavaScript, applets embedded in HTML Web pages are represented by the Applet
object. This object, which is created with each instance of the <applet> tag in a docu-
ment, allows access to the public fields and methods of the applet through JavaScript
properties and methods. Table 8.2 lists the properties and methods used by the Applet
object.
Example
Assume, for the sake of the example code in Listing 8.8, that you have a calculator
applet that you want to embed in an HTML document. Also assume that this applet has
a method called add(), which adds two numbers and returns the result. If you wanted
to access this method from within JavaScript, you would begin by defining the applet
using <applet> tags. Then the JavaScript code would pass the numbers 2 and 5 into the
add() method, using dot notation, and the result of 7 would be returned and displayed
in the browser.
NOTE
This example will not work unless you have an applet called calculator that has a
function called add().
Client-Side 573
// -->
</script>
</html>
Area
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
An instance of the Area object is created with each occurrence of the <area> tag within
an HTML document. In HTML documents, the <area> tag is used in conjunction with
the <map> tag to define an area within a picture that will act as a hyperlink. Because the
Area object is a hyperlink, it is equivalent to the Link object in JavaScript. In fact, the
Area object is stored in the same array where Link objects are stored. Table 8.3 lists the
properties, methods, and event handlers of the Area object.
Table 8.3 Properties, Methods, and Event Handlers Used by the Area
Object
Type Item Description
Properties hash The portion of the URL that is the anchor,
including the # symbol.
host The hostname (IP address) and port specified in
the URL.
hostname The hostname specified within the URL.
href The entire URL.
pathname The path of the file specified in the URL begin-
ning with the / symbol.
port The port specified in the URL.
protocol The protocol specified in the URL, including the
ending colon (:).
search The search part of the URL, including the begin-
ning question mark (?).
target The name of the target window in which the
URL should be displayed.
Methods handleEvent() This method calls the event handler associated
with this event.
unwatch() This method removes a watch point.
watch() This method sets a watch point.
14 0672321416 CH08a 7/24/01 12:16 PM Page 574
Example
Listing 8.9 creates a paint store Web page complete with a box of colors that contains
hyperlinks to bogus color sites. The hyperlinks are created over the graphic using the
<map>, <img>, and <area> tags. When the mouse is moved over an area, the properties
associated with that area are displayed in the text fields at the bottom of the screen.
Figure 8.1 shows what happens when the mouse pointer is placed in the green box.
Select one of the 4 colors to find out more about the colors we carry.<br>
<map name=”colorMap”>
<area name=”redArea”
coords=”1,1,48,48”
href=”http://www.red.com:1234/red.html?query=red#RED”
target=”_top”
onMouseOver=”overBox(0)”
onMouseOut=”clearBox()”>
<area name=”greenArea”
coords=”51,1,99,49”
href=”http://www.green.com:5678/green.html?query=green#GREEN”
target=”_top”
onMouseOver=”overBox(1)”
onMouseOut=”clearBox()”>
<area name=”yellowArea”
coords=”1,51,51,99”
href=”http://www.yellow.com:9876/yellow.html?query=yellow#YELLOW”
target=”_top”
onMouseOver=”overBox(2)”
onMouseOut=”clearBox()”>
14 0672321416 CH08a 7/24/01 12:16 PM Page 575
Client-Side 575
<area name=”blueArea”
coords=”51,51,99,99”
href=”http://www.blue.com:5432/blue.html?query=blue#BLUE”
target=”_top”
onMouseOver=”overBox(3)”
onMouseOut=”clearBox()”>
</map>
<img src=”box4.gif” align=”top”
height=”100” width=”100” usemap=”#colorMap”>
<br><br><b><u>AREA Properties</u></b>
<form name=”myForm”>
hash=<input name=”tHash” type=”textarea”><br>
host=<input name=”tHost” type=”textarea”><br>
hostname=<input name=”tHostName” type=”textarea”><br>
href=<input name=”tHref” type=”textarea”><br>
pathname<input name=”tPathName” type=”textarea”><br>
port=<input name=”tPort” type=”textarea”><br>
protocol=<input name=”tProtocol” type=”textarea”><br>
search=<input name=”tSearch” type=”textarea”><br>
target=<input name=”tTarget” type=”textarea”><br>
</form>
</body>
</html>
Figure 8.1
Accessing an area’s properties.
Area.handleEvent()
JavaScript 1.2+
Nav4+
Syntax
document. links[num].handleEvent(event)
14 0672321416 CH08a 7/24/01 12:16 PM Page 577
Client-Side 577
Description
The handleEvent() method invokes the event handler, specified by the event argu-
ment, that is associated with link specified by the num argument. The method returns
the value associated with the specified event argument.
Example
Listing 8.10 creates a Web page for learning more about the toppings used on a pizza.
When an area is clicked, the user is taken to a place within the document to learn more
about the pizza topping. The handleEvent() method is used to pass all the mouse
events from the first area (represented by peppers) to the event handlers of the second
area (represented by onion). Normally, you would want to display a special notice
when the mouse moves over the pepper area, but the handleEvent() method is used to
make the pepper area do the same thing as the onion area. Notice that “onion” is placed
in the text box when the mouse is moved over either of the two defined areas, thanks
to the handleEvent() method.
<center><h1><u>
Learn more about the toppings we use on our pizza
</u></h1></center>
<map name=”toppingsMap”>
<area name=”peppers”
coords=”1,1,48,48”
href=”#PEPPERS”
target=”_top”
onMouseOver=”fillTextField(event)”
onMouseOut=”fillTextField(event)”><br>
<area name=”onion”
coords=”51,1,99,49”
href=”#ONION”
target=”_top”
onMouseOver=”document.pizzaForm.textbox.value=’onion’”
onMouseOut=”document.pizzaForm.textbox.value=’’”>
</map>
<img src=”toppingsBox.gif”
align=”top”
height=”50”
width=”100”
usemap=”#toppingsMap”>
14 0672321416 CH08a 7/24/01 12:16 PM Page 578
// -->
</script>
</body>
</html>
Area.hash
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document. links[num].hash
Description
The hash property associated with an Area object contains the anchor specified in the
URL including the leading hash symbol (#).
14 0672321416 CH08a 7/24/01 12:16 PM Page 579
Client-Side 579
Example
Listing 8.11 creates a truck parts page that allows users to find model numbers of parts
by clicking a picture of the part. When the user selects a part, she is presented with an
alert window that contains the value of the hash property for the selected link. In this
example the value displayed will be one of the following strings: “#SPARKPLUGS”,
“#TIRES”, “#HEADLIGHTS”, and “#FUSES”. After the alert window is closed, the
browser moves to the portion of the document specified by the hash property.
<map name=”partsMap”>
<area name=”sparkPlug”
coords=”1,1,48,48”
href=”#SPARKPLUGS”
target=”_top”
onClick=”alert(document.links[0].hash)”>
<area name=”tires”
coords=”51,1,99,49”
href=”#TIRES”
target=”_top”
onClick=”alert(document.links[1].hash)”>
<area name=”headlights”
coords=”1,51,51,99”
href=”#HEADLIGHTS”
target=”_top”
onClick=”alert(document.links[2].hash)”>
<area name=”fuses”
coords=”51,51,99,99”
href=”#FUSES”
target=”_top”
onClick=”alert(document.links[3].hash)”>
</map>
<img src=”partsBox.gif”
align=”top”
height=”100”
width=”100”
usemap=”#partsMap”>
<br>
14 0672321416 CH08a 7/24/01 12:16 PM Page 580
<a name=”TIRES”><h3>Tires</h3></a>
<ul>
<li>Mud Stompers</li>
<li>Low Riders</li>
<li>Standard</li>
</ul>
<a name=”HEADLIGHTS”><h3>Headlights</h3></a>
<ul>
<li>Night Vision bulbs</li>
<li>Standard</li>
</ul>
<a name=”FUSES”><h3>Fuses</h3></a>
<ul>
<li>Red</li>
<li>Yellow</li>
<li>Green</li>
<li>Blue</li>
</ul>
</body>
</html>
Area.host
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document. links[num].host
Description
The host property associated with an Area object contains the hostname and port that
is specified in the URL separated by a colon (:).
Example
Listing 8.12 creates a truck parts page that allows users to find model numbers of parts
by clicking a picture of the part. When the user selects a part, she is presented with an
alert window that contains the string “www.wildbillstruckparts.com:4000”, which
14 0672321416 CH08a 7/24/01 12:16 PM Page 581
Client-Side 581
is the value of the host property for the selected link. After the alert window is closed,
the browser will attempt to load the specified file located on the fictitious Web site.
<map name=”partsMap”>
<area name=”sparkPlug”
coords=”1,1,48,48”
href=”http://www.wildbillstruckparts.com:4000/sparkplugs.html”
target=”_top”
onClick=”alert(document.links[0].host)”>
<area name=”tires”
coords=”51,1,99,49”
href=”http://www.wildbillstruckparts.com:4000/tires.html”
target=”_top”
onClick=”alert(document.links[1].host)”>
<area name=”headlights”
coords=”1,51,51,99”
href=”http://www.wildbillstruckparts.com:4000/headlights.html”
target=”_top”
onClick=”alert(document.links[2].host)”>
<area name=”fuses”
coords=”51,51,99,99”
href=”http://www.wildbillstruckparts.com:4000/fuses.html”
target=”_top”
onClick=”alert(document.links[3].host)”>
</map>
<img src=”partsBox.gif”
align=”top”
height=”100”
width=”100”
usemap=”#partsMap”>
</center>
</body>
</html>
14 0672321416 CH08a 7/24/01 12:16 PM Page 582
Area.hostname
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
document. links[num].hostname
Description
The hostname property associated with the Area object contains just the hostname that
is specified in the URL.
Example
Listing 8.13 creates a truck parts page that allows users to find model numbers of parts
by clicking a picture of the part. When the user selects a part, she is presented with an
alert window that contains the string “www.wildbillstruckparts.com”, which is the
value of the hostname property for the selected link. After the alert window is closed,
the browser will attempt to load the file located on the fictitious Web site.
<map name=”partsMap”>
<area name=”sparkPlug”
coords=”1,1,48,48”
href=”http://www.wildbillstruckparts.com:4000/sparkplugs.html”
target=”_top”
onClick=”alert(document.links[0].hostname)”>
<area name=”tires”
coords=”51,1,99,49”
href=”http://www.wildbillstruckparts.com:4000/tires.html”
target=”_top”
onClick=”alert(document.links[1].hostname)”>
<area name=”headlights”
coords=”1,51,51,99”
href=”http://www.wildbillstruckparts.com:4000/headlights.html”
target=”_top”
onClick=”alert(document.links[2].hostname)”>
<area name=”fuses”
coords=”51,51,99,99”
href=”http://www.wildbillstruckparts.com:4000/fuses.html”
target=”_top”
onClick=”alert(document.links[3].hostname)”>
14 0672321416 CH08a 7/24/01 12:16 PM Page 583
Client-Side 583
</map>
<img src=”partsBox.gif”
align=”top”
height=”100”
width=”100”
usemap=”#partsMap”>
</center>
</body>
</html>
Area.href
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document. links[num].href
Description
The href property associated with the Area property contains the entire URL specified
by the href attribute of the <area> tag. This property is a read/write string.
Example
In Listing 8.14, a sports car picture site is created. Selecting your location determines
from which site a large picture of the sports car is retrieved. This is accomplished by
modifying the href property to link to a completely different site based on the user’s
choice of cars.
<form name=”question”>
<input name=”carType”
type=”radio”
checked
onClick=”updateLinks(‘LAMBORGHINI’)”>Lamborghini<br>
<input name=”carType”
type=”radio”
onClick=”updateLinks(‘FERRARI’)”>Ferrari
14 0672321416 CH08a 7/24/01 12:16 PM Page 584
<map name=”carMap”>
<area name=”car”
coords=”1,1,48,48”
href=”http://www.cars.com:5678/cars.html?query=fast#LAMBORGHINI”
target=”_top”>
</map>
<img src=”cars.gif” align=”top”
height=”50” width=”50” usemap=”#carMap”>
<br>
// update the picture host links based on the radio box settings
function updateLinks(car)
{
// Set to Lamborghini site
if(car==”LAMBORGHINI”)
document.links[0].href=”http://www.cars.com:5678/cars.html
➥?query=fast#LAMBORGHINI”;
// -->
</script>
</body>
</html>
Area.onDblClick
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
onDblClick=”command”
14 0672321416 CH08a 7/24/01 12:16 PM Page 585
Client-Side 585
Description
The onDblClick event handler associated with the Area object is invoked when the
user double-clicks the mouse pointer while in the region defined by the <area> tag.
Example
Listing 8.15 creates a clothing site with a picture of a shirt. Double-clicking the shirt
displays a message about red shirts, thanks to the onDblClick event handler.
<map name=”clothesMap”>
<area name=”redShirt”
coords=”1,1,48,48”
target=”_top”
onDblClick=”alert(‘You must like red shirts.’)”>
</map>
<img src=”clothes.gif” align=”top”
height=”100” width=”100” usemap=”#clothesMap”>
</body>
</html>
Area.onMouseOut
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
onMouseOut=”command”
Description
The onMouseOut event handler associated with the Area object is invoked when the
user moves the mouse pointer into the region defined by the <area> tag.
Example
Listing 8.16 creates a clothing site with a picture of a shirt. Clicking the shirt graphic
takes you to a site about red shirts. If the mouse is moved out of the region, an alert box
posts a message to the screen, thanks to the onMouseOut event handler.
<map name=”clothesMap”>
<area name=”redShirt”
coords=”1,1,48,48”
href=”http://www.clothes.com/redShirts.html”
target=”_top”
onMouseOut=”alert(‘You did not want to go the red shirt site?’)”>
</map>
<img src=”clothes.gif” align=”top”
height=”100” width=”100” usemap=”#clothesMap”>
</body>
</html>
Area.onMouseOver
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
onMouseOver=”command”
Description
The onMouseOver event handler is invoked when the user moves the mouse pointer
over the region defined by the <area> tag.
Example
Listing 8.17 creates a clothing site with a picture of a shirt. Clicking the shirt graphic
takes you to a site about red shirts. Simply moving the mouse over the region causes
an alert box to be posted alerting the user that a mouseover event occurred.
Click on the sales tag to see the clothes that are on sale:<br>
<map name=”clothesMap”>
<area name=”sale”
coords=”1,1,100,100”
href=”http://www.clothes.com/specials.html”
target=”_top”
onMouseOver=”alert(‘An onMouseOver event occured.’)”>
14 0672321416 CH08a 7/24/01 12:16 PM Page 587
Client-Side 587
</map>
<img src=”sale.gif” align=”top”
height=”100” width=”100” usemap=”#clothesMap”>
</body>
</html>
Area.pathname
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.links[num]. pathname
Description
The pathname property contains the path of the file specified in the URL, including the
leading slash (/).
Example
Listing 8.18 creates a truck parts page that allows users to find model numbers of parts
by clicking a picture of the part. When the user selects a part, she is presented with an
alert window that contains the value of the pathname property for the selected link.
After the alert window is closed, the browser attempts to load the specified file.
<map name=”partsMap”>
<area name=”sparkPlug”
coords=”1,1,48,48”
href=”sparkplugs.html”
target=”_top”
onClick=”alert(document.links[0].pathname)”>
<area name=”tires”
coords=”51,1,99,49”
href=”tires.html”
target=”_top”
onClick=”alert(document.links[1].pathname)”>
<area name=”headlights”
coords=”1,51,51,99”
href=”headlights.html”
14 0672321416 CH08a 7/24/01 12:16 PM Page 588
</center>
</body>
</html>
Area.port
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
document.links[num]. port
Description
The port property contains just the port specified in the URL.
Example
Listing 8.19 creates a truck parts page that allows users to find model numbers of parts
by clicking a picture of the part. When the user selects a part, she is presented with an
alert window that contains the string “4000”, which is the value of the port property
for the selected link. After the alert window is closed, the browser will attempt to load
the specified Web site.
Client-Side 589
<map name=”partsMap”>
<area name=”sparkPlug”
coords=”1,1,48,48”
href=”http://www.wildbillstruckparts.com:4000/sparkplugs.html”
target=”_top”
onClick=”alert(document.links[0].port)”>
<area name=”tires”
coords=”51,1,99,49”
href=”http://www.wildbillstruckparts.com:4000/tires.html”
target=”_top”
onClick=”alert(document.links[1].port)”>
<area name=”headlights”
coords=”1,51,51,99”
href=”http://www.wildbillstruckparts.com:4000/headlights.html”
target=”_top”
onClick=”alert(document.links[2].port)”>
<area name=”fuses”
coords=”51,51,99,99”
href=”http://www.wildbillstruckparts.com:4000/fuses.html”
target=”_top”
onClick=”alert(document.links[3].port)”>
</map>
<img src=”partsBox.gif”
align=”top”
height=”100”
width=”100”
usemap=”#partsMap”>
</center>
</body>
</html>
Area.protocol
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
document.links[num]. protocol
Description
The protocol property contains the protocol (http:, file:, ftp:, and so on) specified
in the URL, including the ending colon (:).
Example
In Listing 8.20, the protocol property containing http: is displayed below the area
link.
14 0672321416 CH08a 7/24/01 12:16 PM Page 590
<map name=”colorMap”>
<area name=”greenArea”
coords=”1,1,48,48”
href=”http://www.green.com:5678/green.html?query=green#GREEN”
target=”_top”>
</map>
<img src=”box4.gif” align=”top”
height=”100” width=”100” usemap=”#colorMap”>
<script>
<!--
// -->
</script>
</html>
Area.search
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
document.links[num]. search
Description
The search property contains the search string specified in the URL, including the
leading question mark (?).
Example
Listing 8.21 creates a truck parts page that allows users to find model numbers of parts
by clicking a picture of the part. When the user selects a part, she is presented with an
alert window that contains the value of the search property for the selected link. In this
example, the value displayed will be one of the following strings: “?sparkplugs”,
“?tires”, “?headlights”, or “?fuses”. After the alert window is closed, the browser
attempts to load the fictitious page.
Client-Side 591
<map name=”partsMap”>
<area name=”sparkPlug”
coords=”1,1,48,48”
href=”parts.html?sparkplugs”
target=”_top”
onClick=”alert(document.links[0].search)”>
<area name=”tires”
coords=”51,1,99,49”
href=”parts.html?tires.html”
target=”_top”
onClick=”alert(document.links[1].search)”>
<area name=”headlights”
coords=”1,51,51,99”
href=”parts.html?headlights.html”
target=”_top”
onClick=”alert(document.links[2].search)”>
<area name=”fuses”
coords=”51,51,99,99”
href=”parts.html?fuses.html”
target=”_top”
onClick=”alert(document.links[3].search)”>
</map>
<img src=”partsBox.gif”
align=”top”
height=”100”
width=”100”
usemap=”#partsMap”>
</center>
</body>
</html>
Area.target
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.links[num]. target
Description
The target property contains the name of the target window or frame in which the
URL should be displayed. This property is a read/write string.
14 0672321416 CH08a 7/24/01 12:16 PM Page 592
Example
In Listing 8.22, a truck parts site is created that allows the user to find out what parts
the store carries. The target of the spark plugs and tires link is modified to make the
information appear in a new browser window. Figure 8.2 shows the result of selecting
the sparkplug image.
<map name=”partsMap”>
<area name=”sparkPlug”
coords=”1,1,48,48”
href=”#SPARKPLUGS”
target=”_top”>
<area name=”tires”
coords=”51,1,99,49”
href=”#TIRES”
target=”_top”>
<area name=”headlights”
coords=”1,51,51,99”
href=”#HEADLIGHTS”
target=”_top”>
<area name=”fuses”
coords=”51,51,99,99”
href=”#FUSES”
target=”_top”>
</map>
<img src=”partsBox.gif” align=”top”
height=”100” width=”100” usemap=”#partsMap”>
<br>
Client-Side 593
// Make the result of the sparkplugs and tires appear in a new window.
document.links[0].target=”_blank”; // sparkplugs
document.links[1].target=”_blank”; // tires
// -->
</script>
</body>
</html>
14 0672321416 CH08a 7/24/01 12:16 PM Page 594
Figure 8.2
A new window opens as a result of clicking the spark plug image.
Area.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.links[num]. unwatch(property)
Description
The unwatch() method of the Area object is used to turn off the watch for a particular
property specified by property.
Example
Listing 8.23 shows how the unwatch() method is used to stop watching the href prop-
erty of the Area object after its name has changed to “http://www.toys.com “.
Select a department<br>
14 0672321416 CH08a 7/24/01 12:16 PM Page 595
Client-Side 595
<map name=”storeMap”>
<area name=”toyArea”
coords=”1,1,100,50”
href=”toys.html”
target=”_top”
<area name=”clothesArea”
coords=”1,50,100,100”
href=”clothes.html”
target=”_top”
</map>
<img src=”menu.gif” align=”top”
height=”100” width=”100” usemap=”#storeMap”>
<br><br>
// Start watch
document.links[0].watch(“href”,alertme);
// Change href
document.links[0].href = “http://www.toys.com”;
// Stop watch
document.links[0].unwatch(“href”,alertme);
Area.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.links[num]. watch(property,function)
Description
The watch() method of the Area object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 8.24 shows how the watch() method is used to start watching the href prop-
erty of the Area object.
Select a department<br>
<map name=”storeMap”>
<area name=”toyArea”
coords=”1,1,100,50”
href=”toys.html”
target=”_top”
<area name=”clothesArea”
coords=”1,50,100,100”
href=”clothes.html”
target=”_top”
</map>
<img src=”menu.gif” align=”top”
height=”100” width=”100” usemap=”#storeMap”>
<br><br>
Client-Side 597
// Start watch
document.links[0].watch(“href”,alertme);
// Change href
document.links[0].href = “http://www.toys.com”;
// -->
</script>
</html>
Button
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Button object represents a graphical button that the user can click to initiate an
action. Buttons are created as part of a form by using the <input> tag with the type
attribute set to “button” in an HTML document. Once created, buttons can be accessed
in JavaScript as an element of a form using dot notation. The arguments, properties,
methods, and event handlers for the Button object are listed in Table 8.4.
Example
In Listing 8.25, a button is created by using the <input> tag. When the button is
clicked, the button’s name is displayed in the adjacent text box.
<form name=”myForm”>
<input type=”button”
value=”Press here to see the name of this button”
name=”myBigButton”
onClick=”displayButtonName()”>
<input type=”text”
name=”textBox”>
</form>
Client-Side 599
// -->
</script>
</html>
Button.blur()
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
document.form. button.blur()
Description
The blur() method removes the focus from a button.
CAUTION
In the Unix versions of Navigator 2 and Navigator 3, the blur() method does not
work for buttons.
Example
In Listing 8.26, two buttons are created by using the <input> tag to demonstrate focus.
The first button retains focus after being clicked, but the second button loses focus as
soon as it is clicked due to the use of the blur() method. There are not a lot of uses for
this method, but it is provided for your use all the same.
Listing 8.26 Removing Focus from a Button with the blur() Method
<html>
Click both buttons. Notice that the second button does not
hold its focus after being clicked.
<form name=”myForm”>
<input type=”button”
value=”I hold my focus after a click”
name=”button1”><br>
14 0672321416 CH08a 7/24/01 12:16 PM Page 600
// -->
</script>
</html>
Button.click()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
document.form.button. click()
Description
The click() method simulates the click event.
Example
In Listing 8.27, two buttons are created by using the <input> tag. The first button dis-
plays an alert box when it is clicked. When the second button is clicked, it causes the
first button’s onClick event handler to be activated, displaying the alert box associated
with the first button.
<form name=”myForm”>
<input type=”button”
value=”Display alert box”
name=”button1”
onClick=”alert(‘You clicked the first button.’)”><br>
14 0672321416 CH08a 7/24/01 12:16 PM Page 601
Client-Side 601
<input type=”button”
value=”Call on button 1”
name=”button2”
onClick=”clickFirstButton()”>
</form>
// -->
</script>
</html>
Button.focus()
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
document. form.button.focus()
Description
The focus() method applies focus to the button without invoking the button’s onFocus
event handler.
CAUTION
In the Unix versions of Navigator 2 and Navigator 3, the focus() method does not
work for buttons.
Example
In Listing 8.28, two buttons are created to demonstrate focus. Choosing the second but-
ton causes the focus to shift to the first button instead of the focus staying on the sec-
ond button, thanks to the focus()method.
14 0672321416 CH08a 7/24/01 12:16 PM Page 602
Listing 8.28 Shifting the Focus to a Button Using the focus() Method
<html>
Click both buttons. Notice that when the second button is clicked
focus is shifted to the first button.
<form name=”myForm”>
<input type=”button”
value=”I hold my focus after a click”
name=”button1”><br>
<input type=”button”
value=”I shift my focus when clicked”
name=”button2”
onClick=”moveFocus()”>
</form>
// -->
</script>
</html>
Button.form
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document. form.button.form
Description
The form property provides access to the button’s parent Form object.
Example
Listing 8.29 proves that the button’s form property contains the parent form object by
evaluating the if statement to true. The sentence “myButton’s form property is
equal to myForm object” is displayed in the browser.
14 0672321416 CH08a 7/24/01 12:16 PM Page 603
Client-Side 603
// -->
</script>
</html>
Button.handleEvent()
JavaScript 1.2-1.3
Nav4-4.5
Syntax
document. form.button.handleEvent(event)
Description
The handleEvent() method provides a way to invoke a button’s event handler, even
though the event was not triggered by the user. The event argument specifies the Event
object associated with the event handler to be invoked.
Example
The code in Listing 8.30 provides information about a car that is for sale. By choosing
one of the buttons labeled Doors, Engine, or Transmission, the related information is
entered into the text boxes. The text boxes can be cleared by clicking the Clear All Info
button. Unlike the other buttons, the Show All Info button passes the click event along
to each of the other buttons using the handleEvent() method. This way, each button
takes care of filling in its respective text box.
Listing 8.30 Handling the click Event with the handleEvent() Method
<html>
<form name=”myForm”>
<input type=”button”
value=”Doors”
name=”doorsButton”
onClick=”document.myForm.doorsBox.value=’4 doors’”>
<input type=”text”
name=”doorsBox”><br>
<input type=”button”
value=”Engine”
name=”engineButton”
onClick=”document.myForm.engineBox.value=’4 cylinder’”>
<input type=”text”
name=”engineBox”><br>
<input type=”button”
value=”Transmission”
name=”transmissionButton”
onClick=”document.myForm.transmissionBox.value=’manual transmission’”>
<input type=”text”
name=”transmissionBox”><br>
<input type=”button”
value=”Clear All Info”
name=”clearAllButton”
onClick=”clearAll()”>
<input type=”button”
value=”Show All Info”
name=”showAllButton”
onClick=”showAll(event)”>
</form>
Client-Side 605
document.myForm.doorsButton.handleEvent(event);
document.myForm.engineButton.handleEvent(event);
document.myForm.transmissionButton.handleEvent(event);
}
// -->
</script>
</html>
Button.name
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document. name.button.name
Description
The name property provides access to the name attribute of the button as specified by
the <input> tag. This property is a read-only string.
Example
In Listing 8.31, a button is created. When the button is clicked, the button’s name prop-
erty is displayed.
<form name=”myForm”>
<input type=”button”
value=”Big Button”
name=”myButton”
onClick=”displayMessage()”>
</form>
// This function displays an alert box the contains the name of the button.
function displayMessage()
{
// Create a string with name of button.
var alertString = String(“You pressed the button named “);
alertString += document.myForm.myButton.name;
14 0672321416 CH08a 7/24/01 12:16 PM Page 606
// -->
</script>
</html>
Button.onBlur
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
onBlur=”command”
Description
The onBlur event handler is defined in an <input> tag and specifies what to do when
the button loses focus.
Example
The code in Listing 8.32 uses the onBlur event handler to display an alert box any time
the button loses focus.
Listing 8.32 Use the onBlur Event Handler to Display an Alert Box When
the Button Loses Focus
<html>
<form name=”myForm”>
<input type=”button”
value=”Big Button”
name=”myButton”
onBlur=”alert(‘Blur event occurred’)”>
</form>
</html>
Button.onClick
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera5+
Syntax
onClick=”command”
14 0672321416 CH08a 7/24/01 12:16 PM Page 607
Client-Side 607
Description
The onClick event handler is defined in an <input> tag and specifies what to do when
the button is clicked.
Example
The code in Listing 8.33 uses the onClick event handler to display an alert box any
time the button is clicked.
Listing 8.33 Use the onClick Event Handler to Display an Alert Box
When the Button Is Clicked
<html>
<form name=”myForm”>
<input type=”button”
value=”Big Button”
name=”myButton”
onClick=”alert(‘Click event occurred’)”>
</form>
</html>
Button.onFocus
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
onFocus=”command”
Description
The onFocus event handler is defined in an <input> tag and specifies what to do when
the button gains focus.
Example
The code in Listing 8.34 uses the onFocus event handler to display an alert box any
time the button gains focus.
Listing 8.34 Use the onFocus Event Handler to Display an Alert Box
When the Button Gains Focus
<html>
<form name=”myForm”>
<input type=”button”
value=”Big Button”
name=”myButton”
onFocus=”alert(‘Focus event occured’)”>
14 0672321416 CH08a 7/24/01 12:16 PM Page 608
</html>
Button.onMouseDown
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
onMouseDown=”command”
Description
The onMouseDown event handler is defined in an <input> tag and specifies what to do
when the left mouse button is clicked.
Example
The code in Listing 8.35 uses the onMouseDown event handler to display an alert box
any time the button is clicked.
Listing 8.35 Use the onMouseDown Event Handler to Display an Alert Box
When the Button Is Clicked
<html>
<form name=”myForm”>
<input type=”button”
value=”Big Button”
name=”myButton”
onMouseDown=”alert(‘MouseDown event occured’)”>
</form>
</html>
Button.onMouseUp
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
onMouseUp=”command”
Description
The onMouseUp event handler is defined in an <input> tag and specifies what to do
when the left mouse button is released while over the button.
14 0672321416 CH08a 7/24/01 12:16 PM Page 609
Client-Side 609
Example
The code in Listing 8.36 uses the onMouseUp event handler to display an alert box any
time the left mouse button is released while over the button.
Listing 8.36 Use the onMouseUp Event Handler to Display an Alert Box
When the Mouse Button Is Released over the Button
<html>
<form name=”myForm”>
<input type=”button”
value=”Big Button”
name=”myButton”
onMouseUp=”alert(‘MouseUp event occured’)”>
</form>
</html>
Button.type
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.form.button.type
Description
The type property provides access to the type attribute of the button. This property is
a read-only string that always contains “button”.
Example
Listing 8.37 creates buttons that relate to various math problems. The type property is
used to determine the number of buttons on the page. This number is then used in the
instructions that are displayed on the bottom of the page.
<form name=”mathForm”>
<input type=”button”
name=”4plus2”
value=”(4 + 2)”
onClick=”document.mathForm.answer.value=’(4 + 2) = 6’”>
<input type=”button”
name=”4minus2”
14 0672321416 CH08a 7/24/01 12:16 PM Page 610
// -->
</script>
</html>
Button.unwatch()
JavaScript 1.2
Nav4, NES3+
Syntax
document.form.button.unwatch(property)
Description
The unwatch() method of the Button object is used to turn off the watch for a partic-
ular property specified by property.
Example
Listing 8.38 shows how the unwatch() method is used to stop watching the value
property of the Button object after its name has changed to “Blue”.
14 0672321416 CH08a 7/24/01 12:16 PM Page 611
Client-Side 611
CAUTION
A bug associated with the watch() and unwatch() methods prevents the actual text
in the button from getting redrawn even though the button’s value property does
get changed.
<form name=”colorForm”>
<input type=”button” name=”colorButton” value=”Red”>
</form>
function alertme(id,oldValue,newValue)
{
document.write(id + “ changed from “ + oldValue + “ to “);
document.write(newValue + “<br>”);
return newValue;
}
// Start watch
document.colorForm.colorButton.watch(“value”,alertme);
// Stop watch
document.colorForm.colorButton.unwatch(“value”);
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:16 PM Page 612
Button.value
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.form.button.value
Description
The value property provides access to the value attribute of the button. This property
is a read-only string that is displayed in the graphical button.
Example
Listing 8.39 uses the value property to customize the text in a button. To modify the
button value, enter your name into the text field and then click the Customize the
Button button. The button at the bottom of the document will no longer contain just the
word “Press”.
<form name=”myForm”>
Please enter your name:
<input type=”text”
name=”nameBox”>
<input type=”button”
name=”customizeTheButton”
value=”Customize the button”
onClick=”customizeButton()”><br>
<input type=”button”
name=”theButton”
value=”Press “
onClick=”displayAlert()”>
</form>
Client-Side 613
// -->
</script>
</html>
Button.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.form.button.watch(property,function)
Description
The watch() method of the Button object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 8.40 shows how the watch() method is used to start watching the value prop-
erty of the Button object.
CAUTION
A bug associated with the watch() and unwatch() methods prevents the actual text
in the button from getting redrawn even though the button’s value property does
get changed.
<form name=”colorForm”>
<input type=”button” name=”colorButton” value=”Red”>
</form>
14 0672321416 CH08a 7/24/01 12:16 PM Page 614
function alertme(id,oldValue,newValue)
{
document.write(id + “ changed from “ + oldValue + “ to “);
document.write(newValue + “<br>”);
return newValue;
}
// Start watch
document.colorForm.colorButton.watch(“value”,alertme);
// -->
</script>
</html>
Checkbox
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Checkbox object represents a graphical check box that the user can click to toggle
the check on or off. Check boxes are created as part of a form by using the <input> tag
with the type attribute set to checkbox in an HTML document. Once created, check
boxes can be accessed in JavaScript as an element of a form using dot notation. Check
boxes can also be grouped together under the same name and accessed as an array by
using brackets. The arguments, properties, methods, and event handlers of the
Checkbox object are listed in Table 8.5
14 0672321416 CH08a 7/24/01 12:16 PM Page 615
Client-Side 615
Example
Listing 8.41 creates a hamburger order page. Check boxes are used to select toppings
for the hamburger. When the Submit Order button is clicked, an alert box is displayed
with the selected toppings.
14 0672321416 CH08a 7/24/01 12:16 PM Page 616
<h2>Hamburger Order</h2>
Step 1: Please select the toppings you would like on your hamburger:<br>
<form name=”orderForm”>
Lettuce
<input type=”checkbox”
value=”lettuce”
name=”lettuceCB”><br>
Cheese
<input type=”checkbox”
value=”cheese”
name=”cheeseCB”><br>
Tomato
<input type=”checkbox”
value=”tomato”
name=”tomatoCB”><br>
Step 2:
<input type=”button”
value=”Submit Order”
name=”orderButton”
onClick=”submitOrder()”>
</form>
// This function creates an alert box to display which toppings were selected.
function submitOrder()
{
// Create a string to display in the alert box
var alertString = String(“Order: Hamburger “);
if(document.orderForm.lettuceCB.checked == true)
alertString += “ with lettuce “; // Add lettuce to string
if(document.orderForm.cheeseCB.checked == true)
alertString += “with cheese “; // Add cheese to string
if(document.orderForm.tomatoCB.checked == true)
alertString += “with tomato “; // Add tomato to string
Client-Side 617
// -->
</script>
</html>
Checkbox.blur()
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+
Syntax
document.form.checkbox.blur()
Description
The blur() method removes the focus from a check box.
CAUTION
In the Unix versions of Navigator 2 and Navigator 3, the blur() method does not
work for check boxes.
Example
In Listing 8.42, two check boxes are created by using the <input> tag. The first check
box retains focus after being clicked, but the second check box loses focus as soon as
it is clicked because of the use of the blur() method. Do not be surprised if you do not
see a difference between the check boxes in this example. In some browsers, you will
not be able to detect the difference between a check box that is focused versus one that
is not focused. For this reason, you will probably find very little use for this method.
Listing 8.42 Removing Focus from a Check Box with the blur() Method
<html>
Click both check boxes. Notice that the second check box does not
hold its focus after being clicked.
<form name=”myForm”>
I hold my focus after a click
<input type=”checkbox”
name=”checkBox1”><br>
I cannot hold my focus after a click
<input type=”checkbox”
name=”checkBox2”
onClick=”removeFocus()”>
14 0672321416 CH08a 7/24/01 12:16 PM Page 618
// -->
</script>
</html>
Checkbox.checked
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+, Opera3+
Syntax
document.form.checkbox.checked
Description
The checked property holds the current state of a check box. Because this property is
a read/write Boolean, the state of the check box can be altered by changing this prop-
erty.
Example
In Listing 8.43, the user is asked to select the door style wanted on her new car. When
the order is submitted, the checked property of each check box is analyzed to deter-
mine whether two different door styles were selected or none at all. If two styles were
selected, the check boxes are reset by altering the checked property.
Step1: Please select the door style you want on your new car:<br>
<form name=”orderForm”>
<input type=”checkbox”
name=”door4”>4 doors<br>
14 0672321416 CH08a 7/24/01 12:16 PM Page 619
Client-Side 619
<input type=”checkbox”
name=”door2”>2 doors<br>
Step 2:
<input type=”button”
value=”Submit Order”
name=”orderButton”
onClick=”submitOrder()”>
</form>
// This function creates a box alerting what door styles were selected.
function submitOrder()
{
// Check for duplicate door selections
if((document.orderForm.door4.checked == true) &&
(document.orderForm.door2.checked == true))
{
// Create alert box.
alert(“You selected two different door the styles. Reselect door style.”);
</html>
Checkbox.click()
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera5+
Syntax
document.form.checkbox.click()
Description
The click() method simulates the click event. The clicked property is adjusted
accordingly when this method is used.
Example
In Listing 8.44, the user can select options for her new car. If the user selects the Alloy
Wheel option, she is told that alloy wheels are great. If the Sports package is selected,
a message is posted to let the user know that alloy wheels come with the sports pack-
age. In addition to this message, the message about allow wheels being great is dis-
played and the Alloy Wheels options is checked, thanks to the click() method.
<form name=”orderForm”>
<input type=”checkbox”
name=”alloy”
onClick=”alert(‘Alloy wheels look great!’)”>Alloy Wheels
<br>
<input type=”checkbox”
name=”sporty”
onClick=”displayNote()”>Sports Package<br>
Step 2:
<input type=”button”
value=”Submit Order”
name=”orderButton”
onClick=”alert(‘Your order has been submitted’)”>
</form>
14 0672321416 CH08a 7/24/01 12:16 PM Page 621
Client-Side 621
</html>
Checkbox.defaultChecked
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+
Syntax
document.form.checkbox.defaultChecked
Description
The defaultChecked property holds the initial state of a check box as defined by the
checked attribute of the <input> tag. Because this property only holds the initial state
of the check box, it is a read-only boolean value.
Example
In Listing 8.45, the defaultChecked property is used to reset the car door check boxes
to their initial state.
Step1: Please select the door style you want on your new car:<br>
<form name=”orderForm”>
<input type=”checkbox”
name=”door4”>4 doors<br>
14 0672321416 CH08a 7/24/01 12:16 PM Page 622
// This function resets the check boxes back to their initial state
function resetCheckboxes()
{
// Access initial state with the defaultChecked property.
document.orderForm.door4.checked = document.orderForm.door4.defaultChecked;
document.orderForm.door2.checked = document.orderForm.door2.defaultChecked;
}
// -->
</script>
</html>
Checkbox.focus()
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+
Syntax
document.form.checkbox.focus()
Description
The focus() method applies focus to a check box without invoking the check box’s
onFocus event handler.
CAUTION
In the Unix versions of Navigator 2 and Navigator 3, the focus() method does not
work for check boxes.
14 0672321416 CH08a 7/24/01 12:16 PM Page 623
Client-Side 623
Example
In Listing 8.46, two check boxes are created by using the <input> tag. Click the Option
1 check box and then the Option 2 check box. Finally, click the Move Focus button to
move the focus back to the first check box. Do not be surprised if you do not see a dif-
ference in the check boxes in this example. In some browsers, you will not be able to
detect the difference between a check box that is focused versus one that is not focused.
For this reason, you will probably find very little use for this method.
Listing 8.46 Applying Focus to a Check Box Using the focus() Method
<html>
Click both checkboxes and then click the button to return focus to
the first checkbox.
<form name=”myForm”>
<input type=”checkbox”
name=”checkBox1”>Option 1<br>
<input type=”checkbox”
name=”checkBox2”>Option 2<br>
<input type=”button”
name=”focusButton”
value=”Move Focus”
onClick=”moveFocus()”>
</form>
// -->
</script>
</html>
Checkbox.form
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+, Opera3+
Syntax
document.form.checkbox.form
14 0672321416 CH08a 7/24/01 12:16 PM Page 624
Description
The form property provides access to a check box’s parent Form object.
Example
The code in Listing 8.47 proves that the check box’s form property contains the parent
Form object by evaluating the if statement to true.
Listing 8.47 Accessing a Check Box’s Parent with the form Property
<html>
<form name=”myForm”>
<input type=”checkbox”
value=”YES”
name=”myCheckBox”
checked>
</form>
// -->
</script>
</html>
Checkbox.handleEvent()
JavaScript 1.2-1.3
Nav4-4.5
Syntax
document.form.checkbox.handleEvent(event)
Description
The handleEvent() method provides a way to invoke a check box’s event handler,
even though the event never happened. The event argument specifies the Event object
associated with the event handler that is to be invoked.
14 0672321416 CH08a 7/24/01 12:16 PM Page 625
Client-Side 625
Example
In Listing 8.48, the user is asked to select the engine wanted in her new car. If the user
selects the V6 engine, she is alerted that the V6 has lots of power. If the 4-cylinder
engine is selected, a message is posted to encourage the user to consider the V6. The
click event is passed to the first check box via the handleEvent() method. This causes
the message about more power to be displayed.
Step1: Please select the engine style you want on your new car:<br>
<form name=”orderForm”>
<input type=”checkbox”
name=”v6”
onClick=”alert(‘The V6 has lots of power!’)”>V6<br>
<input type=”checkbox”
name=”cylinder4”
onClick=”displayNote(event)”>4 Cylinder<br>
Step 2:
<input type=”button”
value=”Submit Order”
name=”orderButton”
onClick=”alert(‘Your order has been submitted’)”>
</form>
// This function passes the click event along to another check box
// using the check box’s handleEvent method.
function displayNote(event)
{
// Display note about V6 engine
alert(“Have you considered the V6 engine?”);
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:16 PM Page 626
Checkbox.name
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+, Opera3+
Syntax
document.form.checkbox.name
Description
The name property provides access to the name attribute of the check box. This prop-
erty is a read-only string.
Example
Listing 8.49 uses the name property of the check boxes to display what engine type was
selected.
Listing 8.49 Display the Name of the Check Box with the name Property
<html>
Step1: Please select the engine style you want on your new truck:<br>
<form name=”orderForm”>
<input type=”checkbox”
name=”V6”
onClick=”duplicateCheck(V6,V8)”>V6<br>
<input type=”checkbox”
name=”V8”
onClick=”duplicateCheck(V8,V6)”>V8<br>
Step 2:
<input type=”button”
value=”Submit Order”
name=”orderButton”
onClick=”submitOrder()”>
</form>
Client-Side 627
// -->
</script>
</html>
Checkbox.onBlur
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+
Syntax
onBlur=”command”
Description
The onBlur event handler is defined in an <input> tag and specifies what to do when
a check box loses focus.
Example
The code in Listing 8.50 uses the onBlur event handler to display a message alerting
the customer that the peppers she is ordering on her pizza are hot.
14 0672321416 CH08a 7/24/01 12:16 PM Page 628
Listing 8.50 Use the onBlur Event Handler to Display an Alert Box When
the Check Box Loses Focus
<html>
<h2>Pizza Machine</h2>
<form name=”orderForm”>
<input type=”checkbox”
name=”peppers”
onBlur=”pepperAlert()”>Peppers<br>
<input type=”checkbox”
name=”sausage”>Sausage<br>
Step 2:
<input type=”button”
value=”Order Pizza”
name=”orderButton”
onClick=”alert(‘Your pizza has been ordered.’)”>
</form>
// -->
</script>
</html>
Checkbox.onClick
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera5+
Syntax
onClick=”command”
14 0672321416 CH08a 7/24/01 12:16 PM Page 629
Client-Side 629
Description
The onClick event handler is defined in an <input> tag and specifies what to do when
a check box is clicked.
Example
The code in Listing 8.51 uses the onClick event handler to display a message alerting
the customer that sausage goes well with peppers.
<h2>Pizza Machine</h2>
<form name=”orderForm”>
<input type=”checkbox”
name=”peppers”
onClick=”recommendSausage()”>Peppers<br>
<input type=”checkbox”
name=”sausage”>Sausage<br>
Step 2:
<input type=”button”
value=”Order Pizza”
name=”orderButton”
onClick=”alert(‘Your pizza has been ordered.’)”>
</form>
</html>
Checkbox.onFocus
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+
Syntax
onFocus=”command”
Description
The onFocus event handler is defined in an <input> tag and specifies what to do when
a check box gains focus.
Example
The code in Listing 8.52 uses the onFocus event handler to automatically select extra
cheese when the customer selects sausage.
Listing 8.52 Using the onFocus Event Handler to Select Extra Cheese
<html>
<h2>Pizza Machine</h2>
<form name=”orderForm”>
<input type=”checkbox”
name=”peppers”>Peppers<br>
<input type=”checkbox”
name=”sausage”
onFocus=”chooseExtraCheese()”>Sausage<br>
<input type=”checkbox”
name=”cheese”>Extra Cheese<br>
Step 2:
<input type=”button”
value=”Order Pizza”
name=”orderButton”
onClick=”alert(‘Your pizza has been ordered.’)”>
</form>
Client-Side 631
// -->
</script>
</html>
Checkbox.type
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera3+
Syntax
document.form.checkbox.type
Description
The type property provides access to the type attribute of the check box. This prop-
erty is a read-only string that always contains “checkbox”.
Example
Listing 8.53 instructs the customer to select only two toppings (check boxes) of all
those offered. To determine the number of toppings, the type property of the check box
is used to determine how many check boxes are in orderForm. The program finds four
check boxes that represent the possible pizza toppings.
<form name=”orderForm”>
<input type=”checkbox”
name=”peppers”>Peppers<br>
<input type=”checkbox”
name=”sausage”>Sausage<br>
<input type=”checkbox”
name=”onion”>Onion<br>
14 0672321416 CH08a 7/24/01 12:16 PM Page 632
// -->
</script>
</html>
Checkbox.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.form.checkbox.unwatch(property)
Description
The unwatch() method of the Checkbox object is used to turn off the watch for a par-
ticular property specified by property.
14 0672321416 CH08a 7/24/01 12:16 PM Page 633
Client-Side 633
Example
Listing 8.54 shows how the unwatch() method is used to stop watching the value
property of the Checkbox object after its value has changed to “Blue”.
<form name=”myForm”>
<input type=”checkbox” name=”myCheckbox” value=”Red”>
</form>
function alertme(id,oldValue,newValue)
{
document.write(id + “ changed from “ + oldValue + “ to “);
document.write(newValue + “<br>”);
return newValue;
}
// Start watch
document.myForm.myCheckbox.watch(“value”,alertme);
// Stop watch
document.myForm.myCheckbox.unwatch(“value”);
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:16 PM Page 634
Checkbox.value
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+, Opera3+
Syntax
document.form.checkbox.value
Description
The value property provides access to value attribute of the check box. This property
is a read/write value that is sent to the server when the form is submitted.
Example
Listing 8.55 uses the value property of each check box to create instructions for the
customer on how to order her custom pizza.
<h2>Pizza Machine</h2>
<form name=”orderForm”>
<input type=”checkbox”
name=”onion”
value=”hot onion”>Onion<br>
<input type=”checkbox”
name=”bacon”
value=”spicy bacon”>Bacon<br>
Step 2:
<input type=”button”
value=”Order Pizza”
name=”orderButton”
onClick=”alert(‘Your pizza has been ordered.’)”>
</form>
Client-Side 635
// -->
</script>
</html>
Checkbox.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.form.checkbox.watch(property,function)
Description
The watch() method of the Checkbox object is used to turn on the watch for a partic-
ular property specified by property. Any time the specified property is changed after
the watch() method has been called, the specified function is called.
Example
Listing 8.56 shows how the watch() method is used to start watching the value prop-
erty of the Checkbox object.
<form name=”myForm”>
<input type=”checkbox” name=”myCheckbox” value=”Red”>
</form>
function alertme(id,oldValue,newValue)
{
document.write(id + “ changed from “ + oldValue + “ to “);
document.write(newValue + “<br>”);
return newValue;
}
// Start watch
document.myForm.myCheckbox.watch(“value”,alertme);
Document
JavaScript 1.0+, ECMAScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Document object represents a Web page that is displayed in a browser window,
frame, or layer. An instance is created with each document that is loaded by the
browser. This object has many properties and methods that vary greatly between
JavaScript and JScript. Table 8.6 lists all the properties, methods, and event handlers
associated with the Document object.
Client-Side 637
document.alinkColor
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
document.alinkColor
14 0672321416 CH08a 7/24/01 12:16 PM Page 638
Description
The alinkColor property specifies the color of activated links. A link is considered
activated between the time the mouse button is clicked and released over a link. The
color is expressed as a string in hexadecimal digits or as one of the HTML standard
color names. The hexadecimal form is made up of six digits that follow the pattern
“RRGGBB.”
Example
The sample code in Listing 8.57 sets the activated link’s color to green for all links on
the page, even if they are placed before the <script> tags.
// -->
</script>
</html>
document.all
JScript 3.0+
IE4+
Syntax
document.all[index]
Description
The document.all property is an array of all the HTML elements that are in the doc-
ument. The elements appear in the array in the order in which they were created. Table
8.7 lists the methods associated with document.all array.
14 0672321416 CH08a 7/24/01 12:16 PM Page 639
Client-Side 639
Example
Listing 8.58 uses the document.all property array and array notation (brackets) to
access the Paint anchor, which happens to be the fourth HTML element on the page.
Using dot notation, the name of the anchor is used to create a link to the top of the page.
// Create a link using the name associated with the Paint anchor (4th element).
document.write(“<a href=’#”,document.all[4].name,”’>”); // Insert “Paint”
document.write(document.all[4].name,”</a>”); // Insert “Paint”
// -->
</script>
</html>
document.all.item()
JScript 3.0+
IE4+
Syntax
document.all.item(name)
Description
The item() method provides a way to retrieve an HTML element out of the docu-
ment.all array without having to know its position in the array. Instead of using an
index position, the item() method allows you to just pass in the name of the element
as specified by the name or id attribute of HTML tags. Normally, the method returns
14 0672321416 CH08a 7/24/01 12:16 PM Page 640
the element, but, if more than one element is found with the same name, an array of
elements is returned.
Example
Listing 8.59 uses the item() method to access the Paint anchor. Using dot notation,
the name of the anchor is used to create a link to the top of the page.
// -->
</script>
</html>
document.all.tags()
JScript 3.0+
IE4+
Syntax
document.all.tags(tag)
Description
The tags() method provides a way to retrieve all HTML elements of a particular tag
type from the document.all array. The method returns an array of elements.
Example
Listing 8.60 uses the tags() method to create an array of all the anchor tags in the doc-
ument. Using dot notation, the name of the first anchor in the temporary array is used
to create a link to the top of the page.
14 0672321416 CH08a 7/24/01 12:16 PM Page 641
Client-Side 641
Listing 8.60 Using the tags() Method to Find HTML Elements with a
Particular Tag
<html>
// -->
</script>
</html>
document.anchors
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+, Opera5+
Syntax
document.anchors
document.anchors[index]
Description
The anchors property is an array that contains all the Anchor objects that appear within
the HTML document when using the <a name=”string”> tag. The anchors property
has one property of its own, called length, which contains the number of Anchor
objects in the array. The index number ranges from zero to the length of the array
minus one. See “Anchor,” earlier in the chapter, for a detailed explanation of all the
properties associated with anchors.
CAUTION
Although hyperlinks are created using the <a> tag, they are not accessible through
the anchors array. Hyperlinks are stored in the document’s links array.
14 0672321416 CH08a 7/24/01 12:16 PM Page 642
Example
Listing 8.61 demonstrates how to access anchor names using the document’s anchors
array.
// -->
</script>
</html>
document.anchors.length
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+, Opera5+
Syntax
document.anchors.length
Description
The length property contains the number of Anchor objects that are in the document.
Example
Listing 8.62 uses the anchor length property to loop through all the anchors in the doc-
ument. During each pass through the loop, a link to each anchor in the document is cre-
ated.
14 0672321416 CH08a 7/24/01 12:16 PM Page 643
Client-Side 643
<br><a name=”Trumpet”><h4>Trumpet</h4></a>
The trumpet is a brass instrument that can create bright, loud tones. The
trumpet has 3 valves for changing the tone being played.<br>
<br><a name=”Guitar”><h4>Guitar</h4></a>
The guitar is a stringed instrument that has a hollow wooden body with a long
wooden neck. Most guitars have 6 strings each tuned to a different tone.
By pressing different combinations of strings chords can be created.<br>
<br><a name=”Piano”><h4>Piano</h4></a>
The piano has one of the largest tonal ranges of any instrument. Tones
are created by pressing keys which are attached to small wood hammers that
hit strings tuned to specific tones.<br>
// -->
</script>
</html>
document.applets
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
document.applets
document.applets[index]
Description
The applets property is an array that contains all the Applet objects that appear within
the HTML document from using the <applet> tag. The applet property has one prop-
erty of its own, called length, which contains the number of Applet objects in the
14 0672321416 CH08a 7/24/01 12:16 PM Page 644
array. The index number ranges from zero to the length of the array minus one. See
“Applet,” earlier in this chapter, for a detailed explanation of all the properties associ-
ated with applets.
Example
Listing 8.63 includes two fictitious calculator applets that are embedded in the HTML
document. Using the applets array, the names of the calculators are displayed on the
screen.
// -->
</script>
</html>
document.applets.length
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+
Syntax
document.applets.length
Description
The length property contains the number of Applet objects that are in a document.
14 0672321416 CH08a 7/24/01 12:16 PM Page 645
Client-Side 645
Example
Listing 8.64 uses the length property to display the number of applets in a HTML
document.
<applet name=”myAddApplet”
code=”add.class”
width=50
height=50
mayscript></applet>
<applet name=”mySubtractApplet”
code=”subtract.class”
width=50
height=50
mayscript></applet>
</html>
document.bgColor
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.bgColor
Description
The bgColor property specifies the background color of the HTML document. The
color is expressed as a string in hexadecimal digits or as one of the HTML standard
color names. The hexadecimal form is made up of six digits that follow the pattern
“RRGGBB.” The color of the background can also be set with bgcolor attribute of the
<body> tag.
14 0672321416 CH08a 7/24/01 12:16 PM Page 646
Example
Listing 8.65 changes the document’s background color based on which button is cho-
sen.
<form>
<input type=”button”
value=”Yellow”
name=”Yellow”
onClick=”changeBG(‘yellow’)”>
<input type=”button”
value=”Green”
name=”Green”
onClick=”changeBG(‘green’)”>
<input type=”text”
name=”color”>
</form>
// This function changes the background color and fills in the text box.
function changeBG(color)
{
document.bgColor=color; // Change background color
document.myForm.color.value=color; // Display the color
}
// -->
</script>
</html>
document.captureEvents()
JavaScript 1.2+
Nav4+
Syntax
document.captureEvents(eventMask)
Description
The captureEvents() method specifies the type of events that should be passed to the
document rather than to the object for which they were intended. The eventMask argu-
ment(s) specifies what events to capture. The following list shows all the possible event
masks. Multiple events can be captured by using the bitwise OR (|) operator:
14 0672321416 CH08a 7/24/01 12:16 PM Page 647
Client-Side 647
• Event.ABORT
• Event.BLUR
• Event.CHANGE
• Event.CLICK
• Event.DBCLICK
• Event.DRAGDROP
• Event.ERROR
• Event.FOCUS
• Event.KEYDOWN
• Event.KEYPRESS
• Event.KEYUP
• Event.LOAD
• Event.MOUSEDOWN
• Event.MOUSEMOVE
• Event.MOUSEOUT
• Event.MOUSEOVER
• Event.MOUSEUP
• Event.MOVE
• Event.RESET
• Event.RESIZE
• Event.SELECT
• Event.SUBMIT
• Event. UNLOAD
Example
Listing 8.66 attempts to change the background color from yellow to purple when the
mouse button is clicked and released. Before the Event.MOUSEDOWN and
Event.MOUSEUP events can be handled by the button, they are intercepted by
Document’s captureEvent() method and routed to special functions that change the
background colors to red and blue.
Normally the button below would toggle the background color between
yellow and purple but since the mouseup and mousedown events are captured
and handled by the document the events are never allowed to reach the button
level.
<form>
<input type=”button”
value=”Yellow/Purple”
onMouseDown=”document.bgColor=’yellow’”
onMouseUp=”document.bgColor=’purple’”>
</form>
14 0672321416 CH08a 7/24/01 12:16 PM Page 648
// -->
</script>
</html>
document.classes
JavaScript 1.2-1.3
Nav4-4.5
Syntax
document.classes.className.tagName.style
Description
The classes property is an associative array that contains classes associated with
Netscape style sheets. Using dot notation, className specifies the class attribute and
associated HTML tag (tagName) for which the style is applied. When tagName is set
to all, the style is applied to all tags with a class attribute of className. The style
sheet classes are created within <style> or <script> using JavaScript or HTML. The
style specified can be any one of the style properties or methods shown in Table 8.8.
For more information on any of the properties, see the Style object entries in this chap-
ter.
NOTE
When creating a class, make sure that the declaration appears before the new
class is used because many HTML objects cannot be changed after they have been
created in the document.
NOTE
If JavaScript dot notation is used when creating a new class within <style> tags,
document does not have to be specified.
14 0672321416 CH08a 7/24/01 12:16 PM Page 649
Client-Side 649
Table 8.8 Properties and Methods of the Style Object that Can Be
Used with the classes Property
Type Item Description
Property align Alignment of element within its parent
backgroundColor Background color of element
backgroundImage Background image of element
borderBottomWidth Width of bottom border of element
borderColor Color of border of element
borderLeftWidth Width of left border of element
borderRightWidth Width of right border of element
borderStyle Style of border that surrounds element
borderTopWidth Width of top border of element
clear Sides of element where floating elements are
not allowed
color Foreground color of element
display Element to be displayed
fontFamily Font the element should use
fontSize Size of fonts used by element
fontStyle Font style used by element
fontWeight Font weight used by element
lineHeight Distance between two lines that are next to
each other
listStyleType Format of list items elements
marginBottom Distance between bottom border of an
element and top margin border of another
element
marginLeft Distance between left border of an element
and right margin border of another element
marginRight Distance between right border of an element
and left margin border of another element
marginTop Distance between top border of an element
and bottom margin border of another
element
paddingBottom Distance between bottom border of element
and its content
paddingLeft Distance between left border of element and
its content
paddingRight Distance between right border of element
and its content
paddingTop Distance between top border of element and
its content
textAlign Alignment of text within element
textDecoration Type of decoration added to text
textIndent Indenting should appear before text
14 0672321416 CH08a 7/24/01 12:16 PM Page 650
Example
Listing 8.67 demonstrates three different ways to create style sheet classes using
JavaScript and HTML within <style> and <script> tags. Notice how the order in
which the classes are declared and used ultimately affects the style result.
<style type=”text/css”>
all.TEXTFORMAT {font-style: italic;}
</style>
<style type=”text/javascript”>
classes.TEXTFORMAT.all.fontWeight = “bold”;
</style>
<script>
<!--
document.classes.TEXTFORMAT.all.textDecoration = “underline”;
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:16 PM Page 651
Client-Side 651
document.close()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.close()
Description
The close() method closes the output stream to the document. Any output that has not
been written prior to calling the method will be displayed.
CAUTION
The implementation of the close() method varies greatly between browsers and
their versions. In some browsers, output continues to be streamed after calling the
close() method, so it is best to avoid using this method if possible. If you must
use this function, test it carefully on all the browsers you intended to support.
Example
Listing 8.68 uses the close() method to close the output stream to a document.
Listing 8.68 Close Document Output Stream with the close() Method
<html>
// Write some text to the screen and then close the document.
document.write(“This line is a long line that should wrap around the “);
document.write(“browser. If it does not wrap around the screen then “);
document.write(“resize your browser window so that it does wrap and “);
document.write(“reexecute this code.<br>”);
// Close document and write all lines that are currently in the buffer.
document.close();
// Create an alert box so you can see where the close operation takes place.
alert(“Press to continue”);
14 0672321416 CH08a 7/24/01 12:16 PM Page 652
</html>
document.contextual()
JavaScript 1.2-1.4
Nav4
Syntax
document.contextual(context1,...,[contextN], style)
Description
The contextual() method provides a way to apply a style to HTML elements based
on the context of the HTML elements. For example it is possible to specify that the
color of text within an <i> tag that appears in an <h2> tag is set to green. The final argu-
ment passed to the method is the style to be to effected. The context arguments can
also be used to specify other styles in which the final style should exist in order to be
effected.
Example
The code in Listing 8.69 uses the contextual() method to make all italic text that
appears within 2nd level header tags green.
Listing 8.69 Making All Italic Text Green with the contextual() Method
<html>
</html>
document.cookie
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
document.cookie
14 0672321416 CH08a 7/24/01 12:16 PM Page 653
Client-Side 653
Description
The cookie property provides the ability to read and write cookies. A cookie represents
a small amount of data that a Web browser stores to allow information to be shared
among Web pages.
Example
Listing 8.70 creates a cookie and then reads back the result.
Listing 8.70 Create a Cookie and Read It Back Using the cookie Property
<html>
<script>
<!--
// Create a cookie.
document.cookie = “temperature=75”;
// -->
</script>
</html>
document.domain
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.domain
Description
The domain property initially contains the hostname of the server from which the doc-
ument was loaded. The document is allowed to change the value to the domain minus
the subdomain. For example, if a Web page originated from www.example.com, the doc-
ument could change this to example.com. The reason this is allowed is so different
pages that come from various servers within the same Web site can share properties.
The restrictive quality of this property keeps unrelated documents from wrongfully
seeing the data each document might have collected.
Example
No example is provided because the document would have to originate from a server
that has a domain name for this property not to be empty.
14 0672321416 CH08a 7/24/01 12:17 PM Page 654
document.embeds
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.embeds
document.embeds[index]
Description
The embeds property is an array that contains all the embedded objects and plug-ins
that appear within the HTML document when using the <embed> tag. The embeds prop-
erty has one property of its own, called length, which contains the number of items in
the array. The index number ranges from zero to the length minus one.
NOTE
The embeds array property accesses the same data as the document.plugins array
property.
Example
Listing 8.71 uses the length property to display the number of embedded objects in a
HTML document.
Listing 8.71 List the Number of Embedded Objects Using the embeds
Property
<html>
<h2>A Circle</h2>
<embed src=”circle.gif”>
<h2>A Square</h2>
<embed src=”square.gif”>
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 655
Client-Side 655
document.embeds.length
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.embeds.length
Description
The length property contains the number of objects that are in the embeds[] array.
Example
Listing 8.72 uses the length property to display the number of embedded objects in an
HTML document.
Listing 8.72 List the Number of Embedded Objects Using the length
Property
<html>
<h2>A Circle</h2>
<embed src=”circle.gif”>
<h2>A Square</h2>
<embed src=”square.gif”>
// -->
</script>
</html>
document.fgColor
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.fgColor
Description
The fgColor property specifies the default text color of all the text that appears in a
Web document. This is equivalent to assigning the color to the text attribute in the
<body> tag. The color is expressed as a string in hexadecimal digits or as one of the
14 0672321416 CH08a 7/24/01 12:17 PM Page 656
HTML standard color names. The hexadecimal form is made up of six digits that fol-
low the pattern “RRGGBB.”
Example
Listing 8.73 sets the default color of all the text on the page to blue.
Listing 8.73 Set the Text Color with the fgColor Property
<html>
// -->
</script>
<body>
The color of all text on this page is blue.
</body>
</html>
document.formName
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.formName
Description
The formName property is actually the name of any form that exists in the HTML doc-
ument. By simply placing the name of a particular form after the word document., you
gain access to the specified form object. It is also possible to access forms using the
forms property and array notation. See the document.forms entry in this chapter for
more information.
Example
Listing 8.74 accesses the action of each form by simply specifying its name using the
document object and dot notation.
Client-Side 657
value=”Green”
onClick = “document.bgColor=’green’”>
</form>
<form name=”Form2” action=”blue”>
<input type=”button”
value=”Blue”
onClick = “document.bgColor=’blue’”>
</form>
</script>
</html>
document.forms
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.forms
document.forms[index]
Description
The forms property is an array that contains all the forms that exist within the HTML
document from using the <form> tag. The forms property has one property of its own,
called length, which contains the number of items in the array. The index number
ranges from zero to the length minus one.
Example
Listing 8.75 accesses the names of each form using the forms[] array.
<form name=”Form1”>
<input type=”button”
value=”Green”
onClick = “document.bgColor=’green’”>
</form>
14 0672321416 CH08a 7/24/01 12:17 PM Page 658
// -->
</script>
</html>
document.forms.length
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.forms.length
Description
The length property contains the number of Form objects that are in the forms[] array.
Example
Listing 8.76 uses the length property to display the number of Form objects in the doc-
ument.
Listing 8.76 Access the Number of Forms in the Document with the
length Property
<html>
<form name=”Form1”>
<input type=”button”
value=”Green”
onClick = “document.bgColor=’green’”>
</form>
<form name=”Form2”>
14 0672321416 CH08a 7/24/01 12:17 PM Page 659
Client-Side 659
<input type=”button”
value=”Blue”
onClick = “document.bgColor=’blue’”>
</form>
// -->
</script>
</html>
document.getSelection()
JavaScript 1.2+
Nav4+
Syntax
document.getSelection()
Description
The getSelection() method returns the text that is selected within the HTML docu-
ment.
Example
Listing 8.77 uses the getSelection() method to display all captured text in a text box.
The result of selecting “JavaScript is Great!” from the text is shown in Figure 8.3.
The following text area will display any text that you
select within the Web page. Try selecting the phrase
“JavaScript is Great!” with the mouse.<br><br>
<form name=”Form1”>
<input type=”text”
name=”TextArea”>
</form>
// -->
</script>
</html>
Figure 8.3
Selecting a portion of text and displaying it in a text box.
document.handleEvent()
JavaScript 1.2-1.3
Nav4-4.5
Syntax
document.handleEvent(event)
Description
The handleEvent() method provides a way to invoke a document’s event handler,
even though the event never happened. The event argument specifies the Event object
associated with the event handler that is to be invoked.
Example
In Listing 8.78, an event handler is designated to handle all document Click events.
When the user selects the button labeled 9, the clickHandler() method is used to
route the event to the document’s event handler.
<h2>Math Quiz</h2>
What is 6+3?
14 0672321416 CH08a 7/24/01 12:17 PM Page 661
Client-Side 661
<form name=”answerForm”>
<input type=”button”
value=” 8 “
name=”answer8”
onClick=”alert(‘Incorrect. Try again.’)”>
<input type=”button”
value=” 9 “
name=”answer9”
onClick=”document.handleEvent(event)”>
</form>
// -->
</script>
</html>
document.ids
JavaScript 1.2-1.3
Nav4-4.5
Syntax
document.ids.idName.style
Description
The ids property is an associative array that contains IDs associated with Netscape
style sheets. Using dot notation, idName specifies an ID associated with a style. The
style sheet IDs are created within the <style> or <script> tags using JavaScript or
HTML. The style specified can be any one of the style properties or methods shown
in Table 8.9. For more information on any of the properties, see the Style object entries
in this chapter.
14 0672321416 CH08a 7/24/01 12:17 PM Page 662
NOTE
When creating an ID, make sure that the declaration appears before the new ID is
used because many HTML objects cannot be changed after they have been created
in the document.
NOTE
If JavaScript dot notation is used when creating a new ID within <style> tags,
document does not have to be specified.
Table 8.9 Properties and Methods of the Style Object that Can Be
Used with the ids Property
Type Item Description
Property align Alignment of element within its parent
backgroundColor Background color of element
backgroundImage Background image of element
borderBottomWidth Width of bottom border of element
borderColor Color of border of element
borderLeftWidth Width of left border of element
borderRightWidth Width of right border of element
borderStyle Style of border that surrounds element
borderTopWidth Width of top border of element
clear Sides of element where floating elements are
not allowed
color Foreground color of element
display Element to be displayed
fontFamily Font the element should use
fontSize Size of fonts used by element
fontStyle Font style used by element
fontWeight Font weight used by element
lineHeight Distance between two lines that are next to
each other
listStyleType Format of list items elements
marginBottom Distance between bottom border of an
element and top margin border of another
element
marginLeft Distance between left border of an element
and right margin border of another element
marginRight Distance between right border of an element
and left margin border of another element
marginTop Distance between top border of an element
and bottom margin border of another
element
14 0672321416 CH08a 7/24/01 12:17 PM Page 663
Client-Side 663
Example
Listing 8.79 demonstrates three different ways to create style sheet IDs using
JavaScript and HTML within <style> and <script> tags. Notice how the order in
which the IDs are declared and used ultimately affects the style result.
<style type=”text/css”>
#TEXTFORMAT {font-style: italic;}
</style>
<style type=”text/javascript”>
ids.TEXTFORMAT.fontWeight = “bold”;
</style>
</html>
document.images
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.images
document.images[index]
Description
The images property is an array that contains all the objects that appear within the
HTML document from using the <img> tag. The images property has one property of
its own, called length, which contains the number of items in the array. The index
number ranges from zero to the length of the array minus one.
Example
The code in Listing 8.80 accesses the source of each image using the images array.
<h2>A Circle</h2>
<img src=”circle.gif”>
<h2>A Square</h2>
<img src=”square.gif”><br>
Client-Side 665
// -->
</script>
</html>
document.images.length
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera 5+
Syntax
document.images.length
Description
The length property contains the number of objects that are in the images[] array.
Example
The code in Listing 8.81 uses the length property to display the number of images in
the HTML document.
<h2>A Circle</h2>
<img src=”circle.gif”>
<h2>A Square</h2>
<img src=”square.gif”><br>
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 666
document.lastModified
JavaScript 1.0+, JScript 3.0+
Nav2+, IE3+, Opera3+
Syntax
document.lastModified
Description
The lastModified property contains the date and time the document was last modified
on the server. This property can be very useful when dealing with documents that con-
tain information that is very date-specific. Be careful when using this date because Web
servers are not required to provide this timestamp. If the timestamp is not provided,
JavaScript will set the lastModified property to midnight, January 1, 1970 (GMT).
Example
The code in Listing 8.82 lists limited discount prices on clothing, starting with when
the document was last modified.
<table border=ON>
<tr>
<th>Item</th>
<th>Retail Price</th>
<th>Sale Price</th>
</tr>
<tr>
<td>T-shirt</td>
<td>$20.00</td>
<td><font color=”RED”>$10.99</font></td>
</tr>
<tr>
<td>Jeans</td>
<td>$60.00</td>
<td><font color=”RED”>$30.99</font></td>
</tr>
14 0672321416 CH08a 7/24/01 12:17 PM Page 667
Client-Side 667
<tr>
<td>Hats</td>
<td>$25.00</td>
<td><font color=”RED”>$15.00</font></td>
</tr>
</table>
</center>
</html>
document.layers
JavaScript 1.2-1.4
Nav4-4.7
Syntax
document.layers
document.layers[index]
Description
The layers property is an array that contains all the objects that appear within the
HTML document from using the <layer> tag. The layers property has one property
of its own, called length, which contains the number of items in the array. The index
number ranges from zero to the length.
CAUTION
The layers property is no longer supported as of JavaScript 1.5, so this property is
not available in Netscape 6.
Example
The code in Listing 8.83 creates two layers and then displays their names at the bottom
of the page using the layers[] array.
Listing 8.83 Accessing the Layer Objects Using the layers[] Array
<html>
<layer name=”Layer1”
PAGEX=50
PAGEY=50
width=100
height=100
bgcolor=”blue”>Layer 1</layer>
<layer name=”Layer2”
PAGEX=150
PAGEY=150
14 0672321416 CH08a 7/24/01 12:17 PM Page 668
// -->
</script>
</html>
document.layers.length
JavaScript 1.2-1.4
Nav4-4.7
Syntax
document.layers.length
Description
The length property contains the number of objects that are in the layers[] array.
CAUTION
The length property associated with the layers[] array is no longer supported as
of JavaScript 1.5, so this property is not available in Netscape 6.
Example
Listing 8.84 creates two layers and then displays the number of layers on the bottom
of the page using the length property.
Listing 8.84 Display the Number of Layers in the Document Using the
length Property
<html>
<layer name=”Layer1”
pagex=50
pagey=50
14 0672321416 CH08a 7/24/01 12:17 PM Page 669
Client-Side 669
width=100
height=100
bgcolor=”blue”>Layer 1</layer>
<layer name=”Layer2”
pagex=150
pagey=150
width=100
height=100
bgcolor=”red”>Layer 2</layer>
// -->
</script>
</html>
document.linkColor
JavaScript 1.0+, ECMAScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
document.linkColor
Description
The linkColor property specifies the color of unvisited links. The color is expressed
as a string in hexadecimal digits or as one of the HTML standard color names. The
hexadecimal form is made up of six digits that follow the pattern “RRGGBB.”
Example
Listing 8.85 sets all the unvisited links on the page to the color green.
// -->
</script>
</html>
document.links
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.links
document.links[index]
Description
The links property is an array that contains all the Link objects that appear within the
HTML document from using the <a href=”source”> tag. The links property has one
property of its own, called length, which contains the number of Link objects in the
array. The index number ranges from zero to the length minus one. See the Link
object earlier in this chapter for a detailed explanation of all the properties associated
with links.
CAUTION
Although anchors are created using the <a> tag, they are not accessible through
the links array. Anchors are stored in the document’s anchors array.
Example
Listing 8.86 displays the URL of each link using the links[] array.
Listing 8.86 Display the URL of each Link in the Document using the
link array
<html>
Client-Side 671
// -->
</script>
</html>
document.links.length
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.links.length
Description
The length property contains the number of Link objects that are in the
document.links array.
Example
Listing 8.87 uses the length property to display the number of links in the HTML doc-
ument.
Listing 8.87 Display the Number of Links in the Document Using the
length Property
<html>
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 672
document.onClick
JavaScript1.0+, JScript 1.0-3.0
Nav2+, IE3-4
Syntax
document.onClick
Description
The onClick event handler specifies what should happen when the mouse is clicked
within the Document object.
Example
In Listing 8.88, the script in the <head> of the document specifies a function to handle
all Click events in the document. To be able to do this, the document’s
captureEvents() method is used to capture all events of type Event.CLICK. When the
page itself is clicked, Document’s event handler generates an alert box notifying the
user of the event.
Listing 8.88 Handle the Click Event with the onClick Event Handler
<html>
<head>
<script type=”text/javascript” language=”JavaScript1.2”>
<!--
// -->
</script>
</head>
<body>
Any time you click anywhere within this document you will
get a message alerting you that a Click event has taken place.
</body>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 673
Client-Side 673
document.onDblClick
JavaScript1.0+, JScript 1.0-3.0
Nav2+, IE3-4
Syntax
document.onDblClick
Description
The onDblClick event handler specifies what should happen when the mouse is dou-
ble-clicked within the Document object.
Example
In Listing 8.89, the script in the <head> of the document specifies a function to handle
all DblClick events in the document. To be able to do this, the document’s
captureEvents() method is used to capture all events of type Event.DBLCLICK. When
the page itself is double-clicked, Document’s event handler generates an alert box noti-
fying the user of the event.
Listing 8.89 Handle the DblClick Event with the onDblClick Event
Handler
<html>
<head>
// -->
</script>
</head>
<body>
Any time you double-click anywhere within this document, you will
get a message alerting you that a DblClick event has taken place.
</body>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 674
document.onKeyDown
JavaScript1.0+, JScript 1.0-3.0
Nav2+, IE3-4
Syntax
document.onKeyDown
Description
The onKeyDown event handler specifies what should happen when any key is pressed
when the Document object is in focus.
Example
In Listing 8.90, the script in the <head> of the document specifies a function to handle
all KeyDown events in the document. To be able to do this, the document’s
captureEvents() method is used to capture all events of type Event.KEYDOWN. When
any key is pressed within the page, the document’s event handler generates an alert box
notifying the user of the event.
Listing 8.90 Handle the KeyDown Event with the onKeyDown Event Handler
<html>
<head>
// Tell the browser you want to intercept ALL key down events
// on the page and then define a function to handle them.
document.captureEvents(Event.KEYDOWN);
document.onKeyDown = myKeyDownHandler;
// -->
</script>
</head>
<body>
Anytime you press a key within this document, you will
get a message alerting you that a KeyDown event has taken place.
</body>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 675
Client-Side 675
document.onKeyPress
JavaScript1.0+, JScript 1.0-3.0
Nav2+, IE3-4
Syntax
document.onKeyPress
Description
The onKeyPress event handler specifies what should happen when any key is pressed
when the Document object is in focus.
Example
In Listing 8.91, the script in the <head> of the document specifies a function to handle
all KeyPress events in the document. To be able to do this, the document’s
captureEvents() method is used to capture all events of type Event.KEYPRESS. When
any key is pressed within the page, the document’s event handler generates an alert box
notifying the user of the event.
Listing 8.91 Handle the KeyPress Event with the onKeyPress Event
Handler
<html>
<head>
// Tell the browser you want to intercept ALL key press events
// on the page and then define a function to handle them.
document.captureEvents(Event.KEYPRESS);
document.onKeyPress = myKeyPressHandler;
// -->
</script>
</head>
<body>
Anytime you press a key within this document, you will
get a message alerting you that a KeyPress event has taken place.
</body>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 676
document.onKeyUp
JavaScript1.0+, JScript 1.0-3.0
Nav2+, IE3-4
Syntax
document.onKeyUp
Description
The onKeyUp event handler specifies what should happen when any key is pressed and
then released when the Document object is in focus.
Example
In Listing 8.92, the script in the <head> of the document specifies a function to handle
all KeyUp events in the document. To be able to do this, the document’s
captureEvents() method is used to capture all events of type Event.KEYUP. When any
key is pressed and then released within the page, the document’s event handler gener-
ates an alert box notifying the user of the event.
Listing 8.92 Handle the KeyUp Event with the onKeyUp Event Handler
<html>
<head>
// -->
</script>
</head>
<body>
Anytime you press a key and release it within this document, you will
get a message alerting you that a KeyUp event has taken place.
</body>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 677
Client-Side 677
document.onLoad
JavaScript1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
onLoad=”command”
Description
The onLoad event handler of the Document object is fired when the page has finished
loading in that particular window instance. This event handler actually belongs to the
Window object but is accessible through the Document object.
NOTE
The onLoad event in the <body> of a document that is loaded in a frame will fire
before an event loaded in the <frameset> tag that loaded the document.
Example
The sample of code in Listing 8.93 pops up an alert box when the page has finished
loading using the onLoad event handler.
Listing 8.93 Handle the Load Event with the onLoad Event Handler
<html>
<body onLoad=’alert(“The document has completely loaded.”)’>
<h2>The document.onLoad entry</h2>
</body>
</html>
document.onMouseDown
JavaScript1.0+, JScript 1.0-3.0
Nav2+, IE3-4
Syntax
document.onMouseDown
Description
The onMouseDown event handler specifies what should happen when the mouse button
is clicked within the Document object.
Example
In Listing 8.94, the script in the <head> of the document specifies a function to handle
all MouseDown events in the document. To be able to do this, the document’s
captureEvents() method is used to capture all events of type Event.MOUSEDOWN.
When the mouse button is clicked within the page, the document’s event handler gen-
erates an alert box notifying the user of the event.
14 0672321416 CH08a 7/24/01 12:17 PM Page 678
Listing 8.94 Handle the MouseDown Event with the onMouseDown Event
Handler
<html>
<head>
// -->
</script>
</head>
<body>
Anytime you press the mouse button down within this document, you will
get a message alerting you that a MouseDown event has taken place.
</body>
</html>
document.onMouseUp
JavaScript1.0+, JScript 1.0-3.0
Nav2+, IE3-4
Syntax
document.onMouseUp
Description
The onMouseUp event handler specifies what should happen when the mouse button is
clicked and then released within the Document object.
Example
In Listing 8.95, the script in the <head> of the document specifies a function to handle
all MouseUp events in the document. To be able to do this, the document’s
captureEvents() method is used to capture all events of type Event.MOUSEUP. When
the mouse button is clicked and then released within the page, the document’s event
handler generates an alert box notifying the user of the event.
14 0672321416 CH08a 7/24/01 12:17 PM Page 679
Client-Side 679
Listing 8.95 Handle the MouseUp Event with the onMouseUp Event Handler
<html>
<head>
// -->
</script>
</head>
<body>
Anytime you press the mouse button and then release it within this
Document, you will get a message alerting you that a MouseUp
event has taken place.
</body>
</html>
document.onUnLoad
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onUnLoad=”command”
Description
The onUnLoad event handler of a Document object is fired when the page is unloaded
in that particular window instance. This occurs when the user leaves the page for
another page. This event handler actually belongs to the Window object but is accessi-
ble through the Document object. See Window.onUnLoad, later in this chapter, for more
information.
NOTE
The onUnLoad event handler in the <body> of a document that is loaded in a frame
will fire before an event loaded in the <frameset> tag that loaded the document.
14 0672321416 CH08a 7/24/01 12:17 PM Page 680
Example
The code in Listing 8.96 pops up an alert box when the user clicks the bogus link to
leave the current HTML page, thanks to the onUnLoad event handler.
Listing 8.96 Handle the UnLoad Event with the onUnLoad Event Handler
<html>
<body onUnLoad=’alert(“Please do not leave!”)’>
<a href=”nextpage.html”>Press this link to go to the next page.</a>
</body>
</html>
document.open()
JavaScript1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.open()
document.open(mimetype)
Description
The open() method of the Document object clears the current document and opens a
stream for new data to be placed in the document. This method accepts one argument,
mimetype, that specifies what type of data will be written to the document. The argu-
ment can be one of the following standard mimetypes: text/html, text/plain,
image/gif, image/jpeg, or image/x-bitmap.
Example
Listing 8.97 opens a document with the open() method and then writes text to the doc-
ument.
document.open()
document.write(“Stream text to document”);
document.close()
// -->
</script>
14 0672321416 CH08a 7/24/01 12:17 PM Page 681
Client-Side 681
document.plugins
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.plugins
document.plugins[index]
Description
The plugins property is an array that contains all the embedded objects and plug-ins
that appear within the HTML document from using the <embed> tag. The plugins
property has one property of its own, called length, which contains the number of
items in the array. The index number ranges from zero to the length minus one.
NOTE
The plugins[] array property accesses the same data as the document.embeds[]
array property.
Example
Listing 8.98 uses the length property to display the number of embedded objects in the
HTML document.
Listing 8.98 Display the Number of Plug-ins Using the plugins Property
<html>
<h2>Learn Shapes</h2>
<h2>A Circle</h2>
<embed src=”circle.gif”>
<h2>A Square</h2>
<embed src=”square.gif”>
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 682
document.plugins.length
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
document.plugins.length
Description
The length property contains the number of objects that are in the plugins[] array.
Example
Listing 8.99 uses the length property to display the number of embedded objects in the
HTML document.
Listing 8.99 Display the Number of Plug-ins in the Document using the
length property
<html>
<h2>A Circle</h2>
<embed src=”circle.gif”>
<h2>A Square</h2>
<embed src=”square.gif”>
// -->
</script>
</html>>
document.referrer
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+
Syntax
document.referrer
Description
The referrer property contains the URL of the document that was used to reach the
current document. If the URL was typed directly in to the browser’s location field, this
property will be empty.
14 0672321416 CH08a 7/24/01 12:17 PM Page 683
Client-Side 683
Example
In Listing 8.100, the referrer property is used to create a link back to the previous
document from within the current document in the example.
Listing 8.100 Create a Link Back to the Calling Document Using the
referrer Property
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
document.releaseEvents()
JavaScript1.2-1.3
Nav4-4.5
Syntax
document.releaseEvents(event)
document.releaseEvents(event1 | event2 | eventN)
Description
The releaseEvents() method of the Document object releases all previously captured
events of the event type passed. These events can be captured with the
Document.captureEvents() method. The following events can be released:
• Event.ABORT
• Event.BLUR
• Event.CHANGE
• Event.CLICK
• Event.DBLCLICK
• Event.DRAGDROP
• Event.ERROR
• Event.FOCUS
• Event.KEYDOWN
• Event.KEYPRESS
• Event.KEYUP
• Event.LOAD
• Event.MOUSEDOWN
• Event.MOUSEMOVE
• Event.MOUSEOUT
• Event.MOUSEOVER
• Event.MOUSEUP
14 0672321416 CH08a 7/24/01 12:17 PM Page 684
• Event.MOVE
• Event.RESET
• Event.RESIZE
• Event.SELECT
• Event.SUBMIT
• Event. UNLOAD
After one of these events has been captured, you can define a function to replace the
built-in method for handling the event. Use the releaseEvents() method to free the
event after a capture.
Example
Listing 8.101 has a single text box and a button. The script in the <head> of the docu-
ment specifies a function to handle all Click events in the document. To be able to do
this, the captureEvents() method had to be used to capture all events of type
Event.CLICK. When the page itself is clicked, a counter, which is displayed in the text
box, is incremented.
When the mouse button is clicked, the MouseDown event is fired, the Event.CLICK is
released, and the counter no longer increments when the page is clicked.
Client-Side 685
// -->
</script>
</head>
<body>
<form name=”myForm”>
<input type=TEXT size=2 value=”” name=”myText” onClick=”changeText()”>
<input type=BUTTON value=”Release Event” onMouseDown=”releaseClick()”>
</form>
</body>
</html>
document.routeEvent()
JavaScript1.2+
Nav4+
Syntax
document.routeEvent(event)
Description
The routeEvent() method of the Document object passes all previously captured
events of the event type passed through their normal event processes. The events that
can be passed are as follows:
• Event.ABORT
• Event.BLUR
• Event.CHANGE
• Event.CLICK
• Event.DBLCLICK
• Event.DRAGDROP
• Event.ERROR
• Event.FOCUS
• Event.KEYDOWN
• Event.KEYPRESS
• Event.KEYUP
• Event.LOAD
• Event.MOUSEDOWN
• Event.MOUSEMOVE
• Event.MOUSEOUT
• Event.MOUSEOVER
• Event.MOUSEUP
14 0672321416 CH08a 7/24/01 12:17 PM Page 686
• Event.MOVE
• Event.RESET
• Event.RESIZE
• Event.SELECT
• Event.SUBMIT
• Event. UNLOAD
After one of these events has been captured using the Document.captureEvents()
method, you can define a function to replace the built-in method for handling the event.
Use the releaseEvents() method to free the event after a capture, and use
routeEvent() to allow normal processing to take place.
Example
Listing 8.102 has a single text box and a link. The script in the <head> of the document
specifies a function to handle all Click events in the window. To be able to do this, the
captureEvents() method had to be used to capture all events of type Event.CLICK.
When the page itself is clicked, a counter, which is displayed in the text box, is incre-
mented.
When the link is clicked, the MouseDown event is fired, the Event.CLICK is routed
through its normal means, and the counter no longer increments when the page is
clicked.
Client-Side 687
function changeText(){
document.myForm.myText.value = counter++;
}
// -->
</script>
</head>
<body>
<form name=”myForm”>
<input type=”TEXT” size=”2” value=”” name=”myText” onClick=”changeText()”>
<a href=”http://www.purejavascript.com”
onMouseDown=”window.routeEvent(Event.CLICK)”>Click Here!</a>
</form>
</body>
</html>
document.tags
JavaScript 1.2+
Nav4+
Syntax
document.tags.tagName.style
Description
The tags property is an associative array that contains tags associated with Netscape
style sheets. Using dot notation, tagName specifies a tag associated with a style. The
style sheet tags are created within the <style> or <script> tags using JavaScript or
HTML. The style specified can be any one of the style properties or methods shown
in Table 8.10. For more information on any of the properties, see the Style object
entries in this chapter.
NOTE
When creating a tag, make sure that the declaration appears before the new tag is
used because many HTML objects cannot be changed after they have been created
in the document.
NOTE
If JavaScript dot notation is used when creating a new tag within <style> tags,
document does not have to be specified.
14 0672321416 CH08a 7/24/01 12:17 PM Page 688
Table 8.10 Properties and Methods of the Style Object that Can Be
Used with the tags Property
Type Item Description
Property align Alignment of element within its parent
backgroundColor Background color of element
backgroundImage Background image of element
borderBottomWidth Width of bottom border of element
borderColor Color of border of element
borderLeftWidth Width of left border of element
borderRightWidth Width of right border of element
borderStyle Style of border that surrounds element
borderTopWidth Width of top border of element
clear Sides of element where floating elements are
not allowed
color Foreground color of element
display Element to be displayed
fontFamily Font the element should use
fontSize Size of fonts used by element
fontStyle Font style used by element
fontWeight Font weight used by element
lineHeight Distance between two lines that are next to
each other
listStyleType Format of list items elements
marginBottom Distance between bottom border of an ele-
ment and top margin border of another ele-
ment
marginLeft Distance between left border of an element
and right margin border of another element
marginRight Distance between right border of an element
and left margin border of another element
marginTop Distance between top border of an element
and bottom margin border of another ele-
ment
paddingBottom Distance between bottom border of element
and its content
paddingLeft Distance between left border of element and
its content
paddingRight Distance between right border of element
and its content
paddingTop Distance between top border of element and
its content
textAlign Alignment of text within element
textDecoration Type of decoration added to text
textIndent Indenting that should appear before text
14 0672321416 CH08a 7/24/01 12:17 PM Page 689
Client-Side 689
Example
Listing 8.103 demonstrates three different ways to create style sheet tags using
JavaScript and HTML within <style> and <script> tags. Notice that the order in
which the tags are declared and used ultimately affects the style result.
<style type=”text/css”>
P {font-style: italic;}
</style>
<style type=”text/javascript”>
tags.P.fontWeight = “bold”;
</style>
<script>
<!--
document.tags.P.textDecoration = “underline”;
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 690
document.title
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.title
Description
The title property is a read-only string that specifies the title of the document. This
property is commonly set with the <title> tag.
Example
In Listing 8.104, the title of the Web page is written to the screen using the title
property.
<script>
<!--
// -->
</script>
document.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.unwatch(property)
Description
The unwatch() method of the Document object is used to turn off the watch for a par-
ticular property specified by property.
Example
Listing 8.105 shows how the unwatch() method is used to stop watching the fgColor
property of the Document object after its value has changed to “Blue”.
14 0672321416 CH08a 7/24/01 12:17 PM Page 691
Client-Side 691
CAUTION
A bug associated with the watch() and unwatch() methods prevents the actual text
color from changing in the browser even though the document’s fgColor property
does get changed.
function alertme(id,oldValue,newValue)
{
document.write(id + “ changed from “ + oldValue + “ to “);
document.write(newValue + “<br>”);
return newValue;
}
// Start watch
document.watch(“fgColor”,alertme);
// Stop watch
document.unwatch(“fgColor”);
// -->
</script>
</html>
14 0672321416 CH08a 7/24/01 12:17 PM Page 692
document.URL
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
document.URL
Description
The URL property specifies the URL of the document. This property is read-only.
Example
Listing 8.106 uses the URL property to write the document’s URL to the screen.
<script>
<!--
// -->
</script>
</html>
document.vlinkColor
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
document.vlinkColor
Description
The vlinkColor property specifies the color of visited links. The color is expressed as
a string in hexadecimal digits or as one of the HTML standard color names. The hexa-
decimal form is made up of six digits that follow the pattern “RRGGBB.”
Example
Listing 8.107 sets the visited links color to green for all links on the page, that you have
visited, only if they are placed before the <script> tags.
14 0672321416 CH08a 7/24/01 12:17 PM Page 693
Client-Side 693
Listing 8.107 Setting the Visited Links Color with the vLinkColor
Property
<html>
// -->
</script>
</html>
document.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
document.watch(property,function)
Description
The watch() method of the Document object is used to turn on the watch for a partic-
ular property specified by property. Any time the specified property is changed after
the watch() method has been called, the specified function is called.
Example
Listing 8.108 shows how the watch() method is used to start watching the fgColor
property of the Document object.
CAUTION
A bug associated with the watch() and unwatch() methods prevents the actual text
color from changing in the browser even though the document’s fgColor property
does get changed.
function alertme(id,oldValue,newValue)
{
document.write(id + “ changed from “ + oldValue + “ to “);
document.write(newValue + “<br>”);
return newValue;
}
// Start watch
document.watch(“fgColor”,alertme);
// -->
</script>
</html>
document.write()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.write(value,....)
Description
The write() method appends the comma-separated argument(s) (value) to the docu-
ment as a string. If any of the arguments are not strings, they are converted to strings
before being appended to the document.
Example
Listing 8.109 writes some text, as well as the value of a property, to the current
document using the write() method.
14 0672321416 CH08a 7/24/01 12:17 PM Page 695
Client-Side 695
// -->
</script>
</html>
document.writeln()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
document.writeln(value,....)
Description
The writeln() method appends the comma-separated argument(s) (value) to the doc-
ument as a string. Unlike the write() method, the writeln() method appends a new-
line character to the document after the last argument has been written. If any of the
arguments are not strings, they are converted to strings before being appended to the
document.
Example
Listing 8.110 writes some text, as well as the value of a property, to the current docu-
ment using the writeln() method. The <pre> tag is used to make the newline charac-
ter, which was created by the writeln() method, appear in the Web page.
// -->
</script>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 697
Client-Side 697
Embed
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Embed object references any object that is embedded within a Web page using the
HTML <embed> tag. It is inherited from the document object. Embed is typically used
for audio and video files, but can be used for any type of embedded file. Embedded
objects are referenced by either the embeds array or by name.
Example
Listing 8.111 shows an example of how an embedded midi file can be referenced using
the embeds array.
When this HTML code is loaded in a browser, the AUTOSTART option for the <embed>
tag will start playing the midi file automatically. The stopsong() function calls the
stop method, which is part of browser audio plug-in, to stop playing the midi file.
<body>
<script “type=”text/javascript” language=”JavaScript”>
<!--
// function stops the playing of the midi song.
function stopsong(){
document.embeds[0].stop();
}
// -->
</script>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 698
Event
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
Core client-side JavaScript object.
Description
The Event object is a built-in object that handles the passing of properties to an event
handler. The available properties are shown in Table 8.11.
In addition to the Event properties, events exist that get handled. The available events
are shown in Table 8.12.
Client-Side 699
Events Description
KEYPRESS A key is pressed.
KEYUP A key is released after being pressed down.
LOAD Load the document within a browser.
MOUSEDOWN The left mouse button is pressed down.
MOUSEMOVE The mouse cursor is moved.
MOUSEOUT The mouse cursor is moved away from a specific object.
MOUSEOVER The mouse cursor is moved over a specific object.
MOUSEUP The pressed mouse button is released.
MOVE Object is moved on the screen.
RESET Reset button is pressed.
RESIZE Window or frame has been resized.
SELECT Document object is selected.
SUBMIT Submit button is pressed.
UNLOAD Document is unloaded from the browser.
Example
Without using the Event properties, Event is used only as an argument to functions for
event capturing. An example of this is shown in Listing 8.112. The example captures
all KEYPRESS and DBLCLICK events for the Window object and captures SUBMIT events for
the document. After the events are captured, they are passed to event handlers that per-
form specific functions on them. In two of the event handlers, event properties are
returned.
<body>
// -->
</script>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 701
Client-Side 701
event.data
JavaScript 1.2+
Nav4+
Syntax
event.data
Description
The data property of the Event object references an array of strings for events of
objects that have been dragged and dropped. Each string in the array contains a URL
representing the dropped object. The data property can be read-only if the script has
the UniversalBrowserRead privilege.
Example
Listing 8.113 shows an example of how the data property can be used to determine the
URL of objects that have been dragged and dropped. The example captures all
DRAGDROP events and passes them to a function called handleDragDrop(). The function
extracts the data property from the event and outputs it.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleDragDrop(evnt){
// Declare a temporary array to hold the URL data from the event.data
// property.
tmp = new Array();
tmp = evnt.data;
// Informs the user of the URL for the dragged and dropped object.
alert(“The URL for the dragdrop object is: “ + tmp);
return true;
}
15 0672321416 CH08b 7/24/01 12:21 PM Page 702
// -->
</script>
event.height
JavaScript 1.2+
Nav4+
Syntax
event.height
Description
The height property of the Event object controls the height of a window or frame dur-
ing the RESIZE event.
Example
Listing 8.114 shows how the height property can be accessed when an event such as
RESIZE occurs. The RESIZE event means that the corresponding window or frame has
changed size, thereby changing the height property.
<body>
Client-Side 703
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“A RESIZE event has occurred. The new height of the window is: “
➥ + evnt.height);
return true;
}
// This registers the handle function as the event handler for the
// RESIZE event.
window.onResize = handle;
// -->
</script>
<form name=”form1”>
Click button to change the window size:
<input type=”button” value=”Resize window” onClick = ‘changeSize()’>
</form>
</body>
</html>
event.layerX
JavaScript 1.2+
Nav4+
Syntax
event.layerX
Description
The layerX property of the Event object controls the horizontal (x coordinate) posi-
tioning within the layer in which the event occurred.
Example
Listing 8.115 shows an example of a function that is listening for a RESIZE event. When
one occurs, a variable stores the new x-coordinate position of the window in the layerX
property. In the example, when the user resizes the window, an alert box appears
informing her of the new X value.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
15 0672321416 CH08b 7/24/01 12:21 PM Page 704
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The new width (X value) after the resize is: “ + evnt.layerX);
return true;
}
// This registers the handle function as the event handler for the
// RESIZE event.
window.onResize = handle;
// -->
</script>
<form name=”form1”>
Click button to resize:
<input type=”Button” value=”Resize Window” onClick=’changeSize()’>
</form>
</body>
</html>
event.layerY
JavaScript 1.2+
Nav4+
Syntax
event.layerY
Description
The layerY property of the Event object controls the vertical (y coordinate) position-
ing within the layer in which the event occurred. When a window or frame is resized,
the new value for the vertical coordinate is stored in the layerY property.
Example
Listing 8.116 shows an example of how the layerY property is used. When a RESIZE
event occurs, it invokes the event handler that displays an alert box indicating the new
Y value. The Y value is obtained from the layerY property of the event object.
15 0672321416 CH08b 7/24/01 12:21 PM Page 705
Client-Side 705
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The new height (Y value) of the window object after the resize is: “
➥+
evnt.layerY);
return true;
}
// This registers the handle function as the event handler for the
// RESIZE event.
window.onResize = handle;
// -->
</script>
<form name=”form1”>
Click button to resize:
event.modifiers
JavaScript 1.2+
Nav4+
Syntax
event.modifiers
15 0672321416 CH08b 7/24/01 12:21 PM Page 706
Description
The modifiers property of the Event object refers to any keyboard modifier that
occurs during an event. Modifiers are in the form of a bitmask object and might con-
sist of the following values: ALT_MASK, CONTROL_MASK, META_MASK, and SHIFT_MASK.
Example
Listing 8.117 shows how the modifiers property can be accessed when some sort of
modifier, such as a mouse or keyboard event, has occurred. The KEYPRESS event is cap-
tured and the modifiers property checked to see which type of key was pressed. If a
match is found, a message is sent to the user so indicating.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Sets up the window to capture KEYPRESS events.
document.captureEvents(Event.KEYPRESS);
if(evnt.modifiers == “0”){
alert(“The Meta key was pressed”);
}
if(evnt.modifiers == “2”){
alert(“The Ctrl key was pressed”);
}
if(evnt.modifiers == “4”){
alert(“The Shift key was pressed”);
}
return true;
}
15 0672321416 CH08b 7/24/01 12:21 PM Page 707
Client-Side 707
// This registers the handlePress function as the event handler for the
// KEYPRESS event.
document.onKeyPress = handlePress;
// -->
</script>
To access a specific modifier value, simply reference it using the Event object. Listing
8.118 shows how to access the ALT_MASK modifier.
event.pageX
JavaScript 1.2+
Nav4+
Syntax
event.pageX
Description
The pageX property of the Event object controls the horizontal (x coordinate) posi-
tioning within a Web page in which the event occurred.
Example
Listing 8.119 shows an example of how you can find the x-coordinate positioning of
where the click event occurred within the browser. Simply click in the browser win-
dow and an alert box will appear indicating the x-coordinate value of where the mouse
was clicked.
15 0672321416 CH08b 7/24/01 12:21 PM Page 708
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The X coordinate of where the click event occurred is: “
➥ + evnt.pageX);
return true;
}
// This registers the handle function as the event handler for the
// CLICK event.
window.onClick = handle;
// -->
</script>
<form>
This example shows you how to access the <b>pageX</b>
property of the <i>event</i> object. As you click in the
web browser, an alert box will pop up indicating the value of
the X-coordinate of where you clicked.
</form>
</body>
</html>
event.pageY
JavaScript 1.2+
Nav4+
Syntax
event.pageY
Description
The pageY propertyof the Event object controls the vertical (y coordinate) positioning
within the Web page in which the event occurred.
15 0672321416 CH08b 7/24/01 12:21 PM Page 709
Client-Side 709
Example
Listing 8.120 shows an example of how to determine the y-coordinate cursor position-
ing by using the pageY event property. The JavaScript code listens for a CLICK event to
occur. When this happens, it calls the handle() function that is defined to handle any
captured click events. The handle() function simply pops up an alert box indicating
the y-coordinate value of where the click occurred.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The Y coordinate of where the click event occurred is: “
➥+ evnt.pageY);
return true;
}
// This registers the handle function as the event handler for the
// CLICK event.
window.onClick = handle;
// -->
</script>
This example shows you how to access the <b>pageY</b> property of the
<i>event</i> object. As you click in the web browser, an alert box will
pop up indicating the value of the Y-coordinate of where you clicked.
</body>
</html>
event.screenX
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
event.screenX
15 0672321416 CH08b 7/24/01 12:21 PM Page 710
Description
The screenX property of the event object controls the horizontal (x coordinate) posi-
tioning within the computer screen in which the event occurred.
Example
Listing 8.121 shows an example of how to determine the x coordinate of the cursor rel-
ative to the screen of where the click event occurred. The code captures the CLICK
event. When captured, control is passed to the handle() function, which determines
the x-coordinate position using the screenX property.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The X coordinate relative to the computer screen of where the
➥ click occurred is: “ + evnt.screenX);
return true;
}
// This registers the handle function as the event handler for the
// CLICK event.
window.onClick = handle;
// -->
</script>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 711
Client-Side 711
event.screenY
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
event.screenY
Description
The screenY property of the Event object controls the vertical (y coordinate) position-
ing within the computer screen in which the event occurred.
Example
Listing 8.122 shows an example of how to determine the y coordinate of the cursor
positioning relative to the computer screen when the CLICK event occurs. The code cap-
tures the CLICK event. When captured, control is passed to the handle() function,
which determines the y-coordinate position using the screenY property.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The Y coordinate relative to the computer screen of where the
➥ click occurred is: “ + evnt.screenY);
return true;
}
// This registers the handle function as the event handler for the
// CLICK event.
window.onClick = handle;
// -->
</script>
</body>
</html>
event.target
JavaScript 1.2+
Nav4+
Syntax
event.target
Description
The target property of the Event object refers to the object on which the event takes
place.
Example
Listing 8.123 shows an example of how the target property can be used to determine
to which object an event occurred. In the HTML document, there are three buttons.
When the button is clicked, a JavaScript function catches the click event and, using
the target property, tells the user which button was clicked.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Informs the user which mouse button was pressed.
function whichButton(evnt){
window.captureEvents(evnt.CLICK);
alert(“The button you pressed was:” + evnt.target.value);
}
// -->
</script>
<form name=”form1”>
Choose a button and click on it.
<br><br>
<input type=”button” value=”Button1” name=”Button1”
➥ onClick = whichButton(event)>
<input type=”button” value=”Button2” name=”Button2”
➥ onClick = whichButton(event)>
15 0672321416 CH08b 7/24/01 12:21 PM Page 713
Client-Side 713
</body>
</html>
event.type
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
event.type
Description
The type property of the Event object refers to the type of event that occurred. The
value assigned to type is a string representing the name of the event. See Table 8.12
for the valid event types.
Example
Listing 8.124 shows how the type property can be used to figure out what type of event
is being set. This example checks for a few different events. When an event is detected,
a message is displayed in the message box indicating to the user which type of event
occurred. This example can be expanded to include many different events.
<body>
<form>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
//alert(evnt.type)
if(evnt.type == “click”){
document.form1.msg.value += “The click event occurred.\n”
}
15 0672321416 CH08b 7/24/01 12:21 PM Page 714
if(evnt.type == “keypress”){
document.form1.msg.value += “The keypress event occurred.\n”
}
return true;
}
// This registers the handle function as the event handler for the
// multiple events.
document.onKeyPress = handle;
document.onClick = handle;
document.onMouseDown = handle;
// -->
</script>
<form name=”form1”>
This page demonstrates a few different events. Upon events occurring,
a message will be displayed in the textarea indicating which event occurred.
<br><br><br>
<ul>
<li><input type=”Button” value=”Click Me”></li>
<br><br>
<li>
Dummy text area.
<input type=”text” size=”20”>
<br>
Click mouse in text field.
<br><br>
</li>
<br><br>
<b>Message output:</b>
<textarea name=”msg” rows=”10” cols=”60”></textarea>
<br><br>
<input type=”reset” value=”Clear”>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 715
Client-Side 715
event.unwatch()
JavaScript 1.2+
Nav4+
Syntax
event.unwatch(prop)
Description
The unwatch() method of the Event object is used to remove a watchpoint set on a
property by the unwatch() method. It takes one parameter, prop, which is the property
to unwatch.
Example
Listing 8.125 shows how the unwatch() method is used to turn off the watchpoint set
on the height property of the event object. When the resize button is clicked, the
RESIZE event is captured. The event handler then alerts the user that the window size
has changed and sets the watchpoint. A new value is then assigned to the height prop-
erty, the watchpoint removed, and the result is displayed in the browser.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue + “</b>”
➥ + “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“A RESIZE event has occurred. The new height of the window is: “
➥ + evnt.height);
15 0672321416 CH08b 7/24/01 12:21 PM Page 716
setWatch();
return true;
}
// This registers the handle function as the event handler for the
// RESIZE event.
window.onResize = handle;
// -->
</script>
<form name=”form1”>
Click button to change the window size:
<input type=”button” value=”Resize window” onClick = ‘changeSize()’>
</form>
</body>
</html>
event.watch()
JavaScript 1.2+
Nav4+
Syntax
event.watch(prop,handler)
Description
The watch()method of the Event object is used to watch for changes to Event proper-
ties. When one of the properties, prop, is assigned a value, a handler is used to call a
user-defined function.
Example
Listing 8.126 shows how the watch() method is used to see when the height property
of the event object has changed. When the resize button is clicked, the RESIZE event
is captured. The event handler then alerts the user that the window size has changed
and sets the watchpoint. A new value is then assigned to the height property and then
is displayed in the browser.
15 0672321416 CH08b 7/24/01 12:21 PM Page 717
Client-Side 717
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” +
➥oldValue + “</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“A RESIZE event has occurred. The new height of the window is: “
➥ + evnt.height);
function setWatch(){
myProp = evnt.height;
watch(“myProp”,alertme);
myProp = 200;
}
setWatch();
return true;
}
// This registers the handle function as the event handler for the
// RESIZE event.
window.onResize = handle;
// -->
</script>
<form name=”form1”>
Click button to change the window size:
<input type=”button” value=”Resize window” onClick = ‘changeSize()’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 718
event.which
JavaScript 1.2+
Nav4+
Syntax
event.which
Description
The which property of the Event object refers to which key or mouse button was
pressed or clicked. The value returned for mouse events is a numeric value 1, 2, or 3,
representing the left, middle, and right mouse buttons, respectively. The value returned
for keyboard events is a character representation for the key that was pressed.
Example
Listing 8.127 shows how the which property can be used to determine which mouse
button was pressed. When the user clicks the radio button, an alert box is shown
informing her of the corresponding number for the mouse button clicked.
<body>
<form>
This example uses the which property of the event object to determine
which mouse button is pressed.
<br><br>
<input type=”radio” onClick = ‘alert(“Mouse button Number “ + event.which
➥ + “was pressed.”)’>
</form>
</body>
</html>
event.width
JavaScript 1.2+
Nav4+
Syntax
event.width
Description
The width property of the Event object refers to the width of a window or frame. It is
set during the RESIZE event to the new width of the window or frame being resized.
15 0672321416 CH08b 7/24/01 12:21 PM Page 719
Client-Side 719
Example
Listing 8.128 shows an example using the width property. The RESIZE event is cap-
tured and passed to the handle() function. This function informs the user that a RESIZE
event has occurred and outputs the new width of the window.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“A RESIZE event has occurred. The new width of the window is: “
➥ + evnt.height);
return true;
}
// This registers the handle function as the event handler for the
// RESIZE event.
window.onResize = handle;
// -->
</script>
<form name=”form1”>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 720
Event.ABORT
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Event.ABORT
Description
The ABORT property of the Event object is used by images and refers to the event in
which a transfer is interrupted or aborted by a user.
Example
Listing 8.129 shows an example in which an HTML document might have a large .gif
file embedded within it, but, during the document loading process, the loading of the
.gif file is aborted (by clicking the Stop button in the browser). The captureEvents()
method catches the ABORT event and passes it to the handleAbort() method, which
handles it accordingly.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object. In this case the function is handling any type of
// ABORT events.
function handleAbort(evnt){
alert(“An ABORT event has occurred.”);
return true;
}
// This registers the handle function as the event handler for the
// ABORT event.
document.onAbort = handleAbort;
// -->
</script>
This page loads the sample.gif image. Assuming this is a large image
and takes some time to load, if the user clicks the stop button on
the browser, an <b>abort</b> event will be captured.
<br><br><br>
15 0672321416 CH08b 7/24/01 12:21 PM Page 721
Client-Side 721
</body>
</html>
Event.BLUR
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Event.BLUR
Description
The BLUR property of the Event object is used by all windows, frames, and form ele-
ments when focus is removed from a particular object.
Example
Listing 8.130 shows an example in which the user wants to be alerted when the focus
had been removed from the text area. A function is created to capture the BLUR event
that occurs when focus is removed from an object. When the event is captured, the
handlerBlur() function alerts the user of the event.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleBlur(evnt){
document.form1.msg.value += “A BLUR event has occurred.\n”;
return true;
}
// This registers the handle function as the event handler for the
// BLUR event.
document.onBlur = handleBlur;
15 0672321416 CH08b 7/24/01 12:21 PM Page 722
<form>
Set focus to the first text box. Then click in the second
text box to remove focus from text 1.
<br><br>
Text 1:<input type=”text” size=”20” onBlur=’’>
<br><br>
Text 2:<input type=”text” size=”20”>
<br><br>
<b>Message box:</b>
<textarea name=”msg” rows=”5” cols=”50”></textarea>
</form>
</body>
</html>
Event.CHANGE
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Event.CHANGE
Description
The CHANGE property of the Event object is used by any text-related and select-box
form elements to indicate a change in the element settings.
Example
Listing 8.131 shows an example of a function checking for any occurrences of the
CHANGE event. When a CHANGE event occurs, it is captured by the Document object and
then passed to the handleChange() function, which alerts the user.
<body>
Client-Side 723
// This registers the handle function as the event handler for the
// CHANGE event.
document.onChange = handleChange;
// -->
</script>
Event.CLICK
JavaScript 1.0+
Nav2+, Opera3+
Syntax
Event.CLICK
Description
The CLICK property of the Event object is used by all button objects, documents, and
links to indicate a single mouse button click.
Example
Listing 8.132 shows how the CLICK property is used to determine whether the mouse
was clicked or not. When you click the browser window, the captureEvents() method
captures the CLICK event. The event handler then alerts you that a click has been per-
formed.
15 0672321416 CH08b 7/24/01 12:21 PM Page 724
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleClick(evnt){
alert(“A CLICK event has occurred in this window.”);
return true;
}
// This registers the handleClick function as the event handler for the
// CLICK event.
window.onClick = handleClick;
// -->
</script>
<form>
<input type=”button” value=”Click Here” onClick = ‘handleClick(event)’>
</form>
</body>
</html>
Event.DBLCLICK
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
Event.DBLCLICK
Description
The DBLCLICK property of the Event object is used by documents and links to indicate
a double mouse click.
Example
Listing 8.133 shows an example of the onDblClick event handler being used to handle
the DBLCLICK event. When the user double-clicks the button or anywhere in the win-
dow, an alert box appears indicating that she double-clicked.
15 0672321416 CH08b 7/24/01 12:21 PM Page 725
Client-Side 725
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“A DBLCLICK event has occurred in this window.”);
return true;
}
// This registers the handle function as the event handler for the
// DBLCLICK event.
window.onDblClick = handle;
// -->
</script>
<form>
<input type=”button” value=”Double-click me” onDblClick=’’>
</form>
</body>
</html>
Event.DRAGDROP
JavaScript 1.2+
Nav4+
Syntax
Event.DRAGDROP
Description
The DRAGDROP property of the Event object is used by the window to indicate the
event in which an object has been dragged and dropped.
15 0672321416 CH08b 7/24/01 12:21 PM Page 726
Example
Listing 8.134 shows the how the DRAGDROP event is used to check for any object that
has been dragged and dropped into the browser window. If this occurs, an alert box is
shown indicating that the DRAGDROP event has occurred.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleDragDrop(evnt){
alert(“An object has been dragged and dropped.”);
return true;
}
// This registers the handle function as the event handler for the
// DRAGDROP event.
window.onDragDrop = handleDragDrop;
// -->
</script>
</body>
</html>
Event.ERROR
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera3+
Syntax
Event.ERROR
15 0672321416 CH08b 7/24/01 12:21 PM Page 727
Client-Side 727
Description
The ERROR property of the Event object is used by windows and images to indicate any
errors that occurred during the loading of the Web page.
Example
Listing 8.135 shows an example of how ERROR events can be handled. When an ERROR
event is captured, it is passed to the handle() function, which informs the user of the
error.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“ERROR: The image was unable to be loaded.”);
return true;
}
// This registers the handle function as the event handler for the
// ERROR event.
window.onerror = handle;
// -->
</script>
This page only contains a gif image. However since this gif doesn’t
exist there will be an error loading the page. This error event will
be captured and alerted to the user.
<br><br>
<img src=”nothing.gif” onerror=’’>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 728
Event.FOCUS
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Event.FOCUS
Description
The FOCUS property of the Event object is used by windows, frames, and form elements
to indicate when focus is applied to an object.
Example
Listing 8.136 shows an example of how the FOCUS property is used to determine when
focus is set on a certain object. As you click each object, a message is displayed in the
message box indicating which object has focus. The onFocus event handler handles all
Event.FOCUS events by default.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function showMsg1(){
document.form1.msg.value += “Focus set on Text 1.\n”;
}
function showMsg2(){
document.form1.msg.value += “Focus set on Text 2.\n”;
}
function showMsg3(){
document.form1.msg.value += “Focus set on Button 1.\n”;
}
function showMsg4(){
document.form1.msg.value += “Focus set on the Message Box.\n”;
}
// -->
</script>
<form name=”form1”>
Set focus to an object.
<br><br>
Text 1:<input type=”text” size=”20” onFocus=’showMsg1()’>
<br><br>
15 0672321416 CH08b 7/24/01 12:21 PM Page 729
Client-Side 729
</body>
</html>
Event.KEYDOWN
JavaScript 1.2+
Nav4+
Syntax
Event.KEYDOWN
Description
The KEYDOWN property of the Event object is used by documents, images, links, and text
area form elements to indicate when a key is pressed by the user.
Example
Listing 8.137 shows an example of how a JavaScript function can use the KEYDOWN
event to determine if a key was pressed down. When the KEYDOWN event is captured, the
handle() function processes the event and informs the user that a key has been pressed
down.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
document.form1.msg.value += “ A key was pressed down.\n”;
return true;
}
15 0672321416 CH08b 7/24/01 12:21 PM Page 730
</body>
</html>
Event.KEYPRESS
JavaScript 1.2+
Nav4+
Syntax
Event.KEYPRESS
Description
The KEYPRESS property of the Event object is used by documents, images, links, and
text area form elements to indicate when a key is pressed and held by the user.
Example
Listing 8.138 shows how the KEYPRESS property is used to determine when a key has
been pressed. When the KEYPRESS event is captured, it is sent to the handle() function,
which informs the user that a key has been pressed.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
Client-Side 731
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
document.form1.msg.value += “ A key was pressed.\n”;
return true;
}
// This registers the handle function as the event handler for the
// KEYPRESS event.
window.onKeyPress = handle;
// -->
</script>
<form name=”form1”>
Press a key. When a key is pressed, a message is displayed in the message box
indicating that a key has been pressed.
<br><br>
<b>Message box:</b>
<textarea name=”msg” rows=”5” cols=”50”></textarea>
</form>
</body>
</html>
Event.KEYUP
JavaScript 1.2+
Nav4+
Syntax
Event.KEYUP
Description
The KEYUP property of the Event object is used by documents, images, links, and text
area form elements to indicate when a pressed key is released by the user.
Example
Listing 8.139 shows how to determine when a key has been released. The KEYUP event
is captured. When this occurs, the handle() function is invoked, informing the user
that a key which had been pressed down has been released.
<body>
<script type=”text/javascript” language=”JavaScript”>
15 0672321416 CH08b 7/24/01 12:21 PM Page 732
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
document.form1.msg.value += “ A key was pressed down and let up.\n”;
return true;
}
// This registers the handle function as the event handler for the
// KEYPRESS event.
window.onKeyUp = handle;
// -->
</script>
<form name=”form1”>
Press a key down. When a key is pressed down and let back up, a message is
displayed in the message box indicating that the <b>KEYUP</b> event has
occurred.If you press a key down and hold it down, no message displayed.
Only when the key
is let back up is a message displayed.
<br><br>
<b>Message box:</b>
<textarea name=”msg” rows=”5” cols=”50”></textarea>
<br><br>
<input type=”reset” value=”Clear Message Box”>
</form>
</body>
</html>
Event.LOAD
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
Event.LOAD
Description
The LOAD property of the Event object is used by the Document object to indicate when
a page is loaded by the browser.
15 0672321416 CH08b 7/24/01 12:21 PM Page 733
Client-Side 733
Example
Listing 8.140 shows an example of how to inform the user when a Web page has
loaded. The LOAD event is captured. When this occurs, the handle() function is
invoked, which informs the user that the page has finished being loaded.
<body>
<script type=”text/javascript” language=”JavaScript”>
// Sets up the window to capture LOAD events.
window.captureEvents(Event.LOAD);
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The page is finished being loaded.”);
return true;
}
// This registers the handle function as the event handler for the
// LOAD event.
window.onload = handle;
// -->
</script>
This page only contains a gif image. When the page is finished loading,
a message is displayed indicating so.
<br><br>
<img src=”mypic.gif” onload=’’>
</body>
</html>
Event.MOUSEDOWN
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
Event.MOUSEDOWN
Description
The MOUSEDOWN property of the Event object is used by button objects, documents, and
links to indicate when the mouse button is pressed by the user.
15 0672321416 CH08b 7/24/01 12:21 PM Page 734
Example
Listing 8.141 shows how to use the MOUSEDOWN property to determine when the mouse
has been pressed down. The onMouseDown event handler is used to catch the MOUSEDOWN
event. When it is caught, an alert box is used to inform the user that the event has just
occurred.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The mouse button has been pressed down.”);
return true;
}
// This registers the handle function as the event handler for the
// MOUSEDOWN event.
window.onMouseDown = handle;
// -->
</script>
This example uses the <b>MOUSEDOWN</b> event. When the mouse button
is pressed down, an alert box is shown.
</body>
</html>
Event.MOUSEMOVE
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
Event.MOUSEMOVE
Description
The MOUSEMOVE property of the Event object indicates when the mouse cursor is moved
by the user.
15 0672321416 CH08b 7/24/01 12:21 PM Page 735
Client-Side 735
Example
Listing 8.142 shows how the MOUSEMOVE event is used to determine when the user is
moving the mouse. As the mouse cursor is moved, the coordinates are displayed in the
text boxes.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object. The function sets the x and y coordinates into the text
// areas.
function handle(evnt){
document.form1.x.value=evnt.pageX;
document.form1.y.value=evnt.pageY;
return true;
}
// This registers the handle function as the event handler for the
// MOUSEMOVE event.
window.onMouseMove = handle;
// -->
</script>
<form name=”form1”>
This example uses the <b>MOUSEMOVE</b> event. When the mouse is moved,
then the coordinates are changed.
<br><br>
Mouse x-Coordinate value:<input type=”text” name=”x” size=”3”><br><br>
Mouse y-Coordinate value:<input type=”text” name=”y” size=”3”>
</form>
</body>
</html>
Event.MOUSEOUT
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera3+
Syntax
Event.MOUSEOUT
15 0672321416 CH08b 7/24/01 12:21 PM Page 736
Description
The MOUSEOUT property of the Event object is used by links and document layers to
indicate when the focus of the mouse cursor is moved away from an object.
Example
Listing 8.143 shows how the onMouseOut event handler is used to catch the MOUSEOUT
event that occurs when the mouse cursor is removed from a HTML link.
<body>
</body>
</html>
Event.MOUSEOVER
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
property of the Event object is used by links and document layers to indicate when the
mouse cursor is moved over an object.
Example
Listing 8.144 shows an example of how the MOUSEOVER event property can be used to
modify form element values. As the user moves the mouse cursor over the link, the
MOUSEOVER event is captured and the user is alerted.
<body>
Client-Side 737
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“Your mouse cursor is over the Netscape link.”);
return true;
}
// This registers the handle function as the event handler for the
// MOUSEOVER event.
window.onMouseOver = handle;
// -->
</script>
<form name=”form1”>
Move the mouse cursor over the link to Netscape. When you do,
it will trigger a <b>MOUSEOVER</b> event which is captured.
An alert box will then appear indicating that the mouse cursor
is over the link.
<br><br><br>
<a href=”http://www.netscape.com” onMouseOver = ‘’>
Link to Netscape Website</a>
<br>
<br<br<br</form>
</body>
</html>
Event.MOUSEUP
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
Event.MOUSEUP
Description
The MOUSEUP property of the Event object is used by button objects, documents, and
links to indicate when a mouse button is released.
Example
Listing 8.145 shows how the onMouseUp event handler is used to determine when the
mouse button is released after being pressed. The user clicks the button and, when the
mouse button is released, a message is displayed indicating the action.
15 0672321416 CH08b 7/24/01 12:21 PM Page 738
<body>
<form>
This example demonstrates the MOUSEUP event. When you click the
button and let the mouse up, an alert message is
</body>
</html>
Event.MOVE
JavaScript 1.2+
Nav4+
Syntax
Event.MOVE
Description
The MOVE property of the Event object is used by windows and frames to indicate when
movement by the window or frame occurs.
Example
Listing 8.146 shows the syntax for accessing the MOVE property. When you begin to
move the browser window, the MOVE event will be captured, and the coordinates for the
upper-left of the window will be displayed.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object. The function sets the x and y coordinates into the text
// areas.
15 0672321416 CH08b 7/24/01 12:21 PM Page 739
Client-Side 739
function handleMove(evnt){
document.form1.msg.value=”The window has been moved to coordinates: “
➥ + evnt.screenX + “,” + screenY;
document.form1.x.value=evnt.screenX;
document.form1.y.value=evnt.screenY;
return true;
}
// This registers the handleMove function as the event handler for the
// MOVE event.
window.onMove = handleMove;
// -->
</script>
<form name=”form1”>
This example uses the <b>MOVE</b> event. When the browser window is moved,
then the coordinates are displayed and updated in the field.
<br><br>
Upper-Left Corner X-Coordinate value:
<input type=”text” name=”x” size=”3”><br><br>
Upper-Left Corner Y-Coordinate value:
<input type=”text” name=”y” size=”3”>
<br><br><br>
Message Box:
<br>
<textarea name=”msg” rows=”3” cols=”60”></textarea>
<br>
<input type=”reset” value=”Clear”>
</form>
</body>
</html>
Event.RESET
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
Event.RESET
Description
The RESET property of the Event object is used solely by forms to indicate when the
Reset button is clicked.
15 0672321416 CH08b 7/24/01 12:21 PM Page 740
Example
Listing 8.147 shows an example of how to determine if a Reset button has been
pressed. When the RESET event is captured, the function handle() alerts the user that
the button has been clicked.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“You have clicked the Reset button”);
return true;
}
// This registers the handle function as the event handler for the
// RESET event.
window.onReset = handle;
// -->
</script>
Client-Side 741
Event.RESIZE
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
Event.RESIZE
Description
TheRESIZE property of the Event object is used by windows and frames to indicate the
event of resizing the window or frame.
Example
Listing 8.148 shows how to determine when the window has been resized using the
RESIZE event. When the RESIZE event is captured, the handle() function outputs the
height and width properties of the window.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“You have resized the window to: “ + evnt.height + “x” + evnt.width);
return true;
}
// This registers the handle function as the event handler for the
// RESIZE event.
window.onResize = handle;
// -->
</script>
<form name=”form1”>
Click button to resize:
<input type=”Button” value=”Resize” onClick=window.resizeTo(250,400)>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 742
Event.SELECT
JavaScript 1.0+
Nav2+, Opera3+
Syntax
Event.SELECT
Description
TheSELECT property of the Event object is used by text objects and select-box form ele-
ments to indicate when an element is selected by the user.
Example
Listing 8.149 shows how the SELECT event can be used to determine which form object
has been selected. When some text in the textarea is selected, the SELECT event is
invoked. The document will then capture the event and call the handleSelect() func-
tion, which informs the user that the SELECT event occurred.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// This registers the handle function as the event handler for the
// SELECT event.
document.onSelect = handleSelect;
// -->
</script>
<form name=”form1”>
Message:
<input type=”text” size=”25” name=”txtbox” value=”” onSelect=’’>
<br><br><br>
Display text:<br>
<textarea name=”msg” rows=”5” cols=”60” onSelect=’’>
15 0672321416 CH08b 7/24/01 12:21 PM Page 743
Client-Side 743
</body>
</html>
Event.SUBMIT
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Event.SUBMIT
Description
The SUBMIT property of the Event object is used solely by forms to indicate the click-
ing of the Submit button.
Example
Listing 8.150 shows an example of how JavaScript can be used to process a form when
the Submit button is clicked. The Window listens for the SUBMIT event. When captured,
it will call the handle() function. This function informs the user that the Submit but-
ton was clicked.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“You have clicked the Submit button”);
return true;
}
15 0672321416 CH08b 7/24/01 12:21 PM Page 744
This example demonstrates the submit event. Click the different buttons below.
Only the Submit button will trigger the submit event.
<br><br>
<form>
<input type=”button” value=”Click Me”>
<br><br>
<input type=”Submit” value=”Submit” onsubmit=’’>
<br><br>
<input type=”button” value=”Click on Me too”>
</form>
</body>
</html>
Event.UNLOAD
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Event.UNLOAD
Description
The UNLOAD property of the Event object is used by documents to indicate when a new
document is loaded in a browser or when the browser window is closed.
Example
Listing 8.151 shows how the UNLOAD property can be used to find out when a browser
has finished unloading a Web page. When the UNLOAD event has been captured, the
handle() function is called, which informs the user that the page has been unloaded.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
Client-Side 745
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The page has been unloaded.”);
return true;
}
// This registers the handle function as the event handler for the
// LOAD event.
window.onunload = handle;
// -->
</script>
</body>
</html>
FileUpload
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The FileUpload object represents a file upload box within an HTML form. An upload
box is created by using the HTML <input> tag and specifying the type attribute as
file. The FileUpload object has specific properties and methods associated with it,
which are shown in Table 8.13.
Example
Listing 8.152 shows how an upload box is created and then how the name property is
accessed using the FileUpload object.
A FileUpload object in the HTML page contains a Browse button that allows you to
browse the computer for a file to upload. After this is chosen, normally it would be sent
to a server to be uploaded. However, this example only demonstrates how to get the full
pathname for the file to be uploaded.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Function demonstrates how to obtain property values of the
// FileUpload object.
function showname(){
// Declare a variable to hold the name of the upload box.
var file = document.form1.uploadBox.value ;
document.form1.filename.value = file ;
}
// -->
</script>
<form name=”form1”>
Click on browse to choose a file to send.
<br>
Click on the Send button to see the full path for the file sent.
<br><br>
File to send: <input type=”file” name=”uploadBox”>
<br><br>
<input type=”button” value=”Send” name=”get” onClick=’showname()’>
<br><br>
<input type=”text” name=”filename” size=”40”>
15 0672321416 CH08b 7/24/01 12:21 PM Page 747
Client-Side 747
</form>
</body>
</html>
FileUpload.blur()
JavaScript 1.1+
Nav3+, Opera3+
Syntax
fileupload.blur()
Description
The blur()method of the FileUpload object is used to remove focus from the
FileUpload box.
Example
Listing 8.153 shows how the blur() method is used to remove focus from the upload
box. When the OK button is clicked, the focus is removed from the upload box and a
message is displayed.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function showMessage(){
// Removes focus from the upload box and writes text.
document.form1.uploadbox.blur();
document.form1.textbox.value = “File Submitted”;
}
// -->
</script>
<form name=”form1”>
Enter Filename:
<input type=”file” name=”uploadbox”>
<input type=”button” value=”Okay” onClick=showMessage()>
<br><br>
Confirmation:
<input type=”text” name=”textbox”>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 748
FileUpload.focus()
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera3+
Syntax
fileupload.focus()
Description
The focus()()method is used to set focus to the FileUpload object.
Example
Listing 8.154 shows how to set the focus on the FileUpload object. When the user
clicks the OK button, the JavaScript function checkFile() is called to reset the focus
to the upload box and display a message.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function checkFile(){
// Sets focus to the upload box.
document.form1.uploadbox.focus();
document.form1.textbox.value = “Verify that filename is correct”;
}
// -->
</script>
<form name=”form1”>
Enter Filename:
<input type=”file” name=”uploadbox”>
<input type=”button” value=”Okay” onClick=checkFile()>
<br><br>
Confirmation Message:
<input type=”text” name=”textbox” size=”35”>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:21 PM Page 749
Client-Side 749
FileUpload.form
JavaScript 1.0+, JScript 3.0+
Nav2+, IE4+, Opera3+
Syntax
fileupload.form
Description
The form property()of the FileUpload object is used to reference the form object that
contains the FileUpload box.
Example
Listing 8.155 shows an example of how the form property can be used to extract any
attributes of the form containing the FileUpload box. The page contains two boxes in
which a file can be specified to be uploaded. The checkFiles() function verifies
whether a file has been chosen for each upload box. If a file hasn’t been chosen, the
script will alert the user.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Function verifies whether a file has been chosen for each FileUpload box.
function checkFiles(){
if (document.secret.file1.value == “”){
alert(“You did not enter anything for file 1”);
}
if (document.secret.file2.value == “”){
alert(“You did not enter anything for file 2”);
}
else {
alert(“The files are okay and will be uploaded”);
}
}
// -->
</script>
<form name=”secret”>
</body>
</html>
The first example shows one method of referencing the upload box. There is a second
way, though. It can also be referenced by using the form elements array. An example
of this is in Listing 8.156.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function showUploadName(){
alert(“The FileUpload box name is: “ + document.secret.elements[0].name);
}
// -->
</script>
<form name=”secret”>
Please choose a file to be uploaded.
<br><br>
<input type=”file” name=”mybox” >
<br><br>
Click the button to get the name of the form containing the FileUpload box.
<br><br>
<input type=”button” value=”Get Form Name” onClick=’showUploadName()’>
</form>
</body>
</html>
FileUpload.handleEvent()
JavaScript 1.2+
Nav4+
Syntax
fileupload.handleEvent(event)
15 0672321416 CH08b 7/24/01 12:21 PM Page 751
Client-Side 751
Description
The handleEvent()method of the FileUpload object invokes the event handler for the
specific event.
Example
Listing 8.157 shows how the handleEvent() method is used to handle all CHANGE
events. When the user chooses or enters a filename in the FileUpload box and then
changes the information, the CHANGE event occurs and is captured. The handleChange
function processes the CHANGE event and passes it to the handleEvent() method of the
upload box. So the event handler for the upload box will handle all CHANGE events.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleChange(evnt){
window.document.uploadbox.handleEvent(evnt);
}
function displayText(){
document.form1.msg.value += “Change made to object\n”;
}
// This registers the handle function as the event handler for the
// CHANGE event.
window.onChange = handleChange;
// -->
</script>
Choose a file:
<br>
<form name=”form1”>
<input type=”file” size=”40” name=”uploadbox” onChange=’displayText()’>
<br><br>
<textarea name=”msg” rows=”10” cols=”50”></textarea>
15 0672321416 CH08b 7/24/01 12:22 PM Page 752
</body>
</html>
FileUpload.name
JavaScript 1.0+
Nav2+, Opera3+
Syntax
fileupload.name
Description
The name property of the FileUpload object represents the name attribute of the HTML
<input> tag that creates the FileUpload box. This allows you to reference a
FileUpload object directly by name.
Example
Listing 8.158 shows how the name of the upload box is used to access its properties.
The function getname() uses the form object and the name of the upload box to access
the name property.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Function alerts the user to what the name of the upload box is.
function getname(){
var boxname = document.form1.myUploadbox.name;
alert(“The name of the FileUpload box is: “ + boxname);
}
// -->
</script>
<form name=”form1”>
Click on the button below to get the name of the upload box.
<br><br>
<input type=”file” name=”myUploadbox”>
<br><br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 753
Client-Side 753
</form>
</html>
FileUpload.onBlur
JavaScript 1.1+
Nav3+, Opera3+
Syntax
onBlur=”command”
Description
The onBlur event handler is an event handler for the FileUpload object that notifies
you when the focus is removed from an upload box.
Example
Listing 8.159 shows how the onBlur event handler is used to detect when the focus is
removed from the specified upload box. The user chooses a file from the FileUpload
box and then clicks the text box that removes the focus from the FileUpload box, caus-
ing the Blur event to be thrown.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function inform(){
document.form1.msg.value=”File submitted and focus removed from
➥FileUpload object”;
}
// -->
</script>
<form name=”form1”>
Please choose a file to upload to the server.
<br><br>
<input type=”file” onBlur= ‘inform()’>
<br><br>
Click on the text box.
<br><br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 754
</body>
</html>
FileUpload.onChange
JavaScript 1.1+
Nav3+, Opera3+
Syntax
onChange=”command”
Description
The onChange event handler of the FileUpload object is an event handler that notifies
you when the upload box information has been changed.
Example
Listing 8.160 uses the onChange event handler to check for a user entering information
into an upload box. When the filename entered has been changed, the onChange event
handler is triggered and a message is displayed in the text box.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that informs the user that the filename in the FileUpload box
// has been changed.
function inform(){
document.form1.msg.value = “Filename has been changed”;
}
// -->
</script>
<form name=”form1”>
Client-Side 755
Message:
<input type=”text” name=”msg” size=”40”>
</form>
</body>
</html>
FileUpload.onFocus
JavaScript 1.1+
Nav3+, Opera3+
Syntax
onFocus=”command”
Description
The onFocus event handler of the FileUpload object notifies you when the focus is set
on the upload box.
Example
In Listing 8.161, the onFocus event handler is used to notify the user when the focus is
moved to the upload box. If the user sets the focus to the FileUpload box, a message
is displayed. If the user removes the focus from the FileUpload box, another message
is displayed.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that displays a message whenever focus is set on the FileUpload
// box.
function showMsg1(){
document.form1.msg.value = “Focus on the FileUpload box\n”;
}
// Function displays a message when focus is removed from the FileUpload box.
function showMsg2(){
document.form1.msg.value = “Focus removed from FileUpload box\n”;
}
// -->
</script>
<form name=”form1”>
15 0672321416 CH08b 7/24/01 12:22 PM Page 756
</body>
</html>
FileUpload.select()
JavaScript 1.0+
Nav2+, Opera3+
Syntax
fileupload.select()
Description
The select() method of the FileUpload box is used to select the input area of the
upload field.
Example
Listing 8.162 shows an example of how the select() method is used to select the input
text box of the FileUpload box.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function enterName(){
// Selects the input area of upload box when button is clicked.
document.form1.uploadbox.select();
}
// -->
</script>
<form name=”form1”>
<input type=”file” name=”uploadbox”>
<br><br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 757
Client-Side 757
</body>
</html>
FileUpload.type
JavaScript 1.1+
Nav3+, Opera3+
Syntax
fileupload.type
Description
The type propertyof the FileUpload object represents the type attribute of the HTML
<input> tag used to create the upload box.
Example
Listing 8.163 shows how to access the type property. When the user clicks the Get
Type button, an alert box appears indicating the type of input.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Function informs the user what type of input the first element is.
function getType(){
var mytype = document.form1.uploadbox.type;
<form name=”form1”>
<input type=”file” name=”webfile”>
<br><br>
Interested in finding out what type of input box is above?
Click on the button below.
<br>
<input type=”button” value=”Get Type” onClick=’getType()’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 758
FileUpload.unwatch()
JavaScript 1.2+
Nav4+
Syntax
fileupload.unwatch(prop)
Description
The unwatch()method of the FileUpload object is used to remove a watchpoint set on
a property by the watch() method. It takes one parameter, prop, which is the property
to unwatch.
Example
Listing 8.164 shows how the unwatch() method is used to disable the watchpoint set
on the name property.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.form1.uploadbox.name;
watch(“myProp”,alertme);
myProp = “yahoo”;
unwatch(“myProp”);
myProp = “ebay”;
}
// -->
</script>
<body>
<form name=”form1”>
Please select a file.
<input type=”file” name=”uploadbox”>
<br><br>
Click on the button to change the FileUpload name property
<br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 759
Client-Side 759
</body>
</html>
FileUpload.value
JavaScript 1.0+
Nav2+, Opera3+
Syntax
fileupload.value
Description
The value property of the FileUpload object specifies either the filename of the file
selected or input by the user.
Example
Listing 8.165 shows how to access the value property. The form object is used in con-
junction with the upload box name to get the value attribute of the FileUpload box.
<body>
<script type=text/javascript” language=”JavaScript”>
<!--
function showFile(){
var input = document.form1.uploadbox.value;
alert(“The filename entered is: “ + input);
}
// -->
</script>
<form name=”form1”>
Please select a file.
<input type=”file” name=”uploadbox”>
<br><br>
Click on the button to see the value of the FileUpload object.
<br>
<input type=”button” value=”Submit” onClick=showFile()>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 760
FileUpload.watch()
JavaScript 1.2+
Nav4+
Syntax
fileupload.watch(prop, handler)
Description
The watch() method of the FileUpload object is used to watch for changes to
FileUpload properties. When one of the properties, prop, is assigned a value, a han-
dler is used to call a user-defined function.
Example
Listing 8.166 shows how the watch() method is used to set a watchpoint on the name
property. When the upload box name is changed, the alertme function is called to
display the change to the user.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥ “</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.form1.uploadbox.name;
watch(“myProp”,alertme);
myProp = “yahoo”;
myProp = “ebay”;
}
// -->
</script>
<body>
<form name=”form1”>
Please select a file.
<input type=”file” name=”uploadbox”>
<br><br>
Click on the button to change the FileUpload name property
<br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 761
Client-Side 761
</body>
</html>
Form
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Form object represents an HTML property created by the <form> tag. The Form
object can be used to access all the properties of the specified form. Forms can be ref-
erenced either by the forms array or directly by name. Table 8.14 shows the different
Form methods and properties.
Example
Listing 8.167 uses the method of accessing the Form object directly by name.
15 0672321416 CH08b 7/24/01 12:22 PM Page 762
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Function shows the name entered by the user to verify that
// the information is correct.
function checkName(){
<form name=”formEx”>
First Name:
<input type=”text” name=”first” size=”20”>
Last Name:
<input type=”text” name=”last” size=”25”>
<br><br>
Click the button to check that the information is correct.
<br>
<input type=”button” value=”verify” name=”check” onClick=’checkName()’>
</form>
</body>
</html>
Listing 8.168 accesses the Form object by using the forms array. The form simply con-
tains one text box. Clicking the button shows an alert box containing the name of the
form. Because it is the first form in the document, it is index 0 in the forms array.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function showFormName(){
var name = document.forms[0].name;
Client-Side 763
// -->
</script>
<form name=”form1”>
This text box belongs to a form.
<input type=”text” name=”street”>
<br><br>
Click on the button to get the name of the form.
<br>
<input type=”button” value=”Get Form name” onClick=’showFormName()’>
</form>
<form name=”form2”>
This is the second form in the document. It contains a FileUpload object.
<input type=”file” name=”uploadbox” size=”25”>
</form>
</body>
</html>
Form.action
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.action
Description
The action property represents the action attribute of the HTML <form> tag. It is typ-
ically the URL to which the form is being submitted.
Example
Listing 8.169 shows one method of how to use the Form object to access the action
property of the HTML form. The action property specifies the server and program to
which the form is submitted.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function getAction(){
var actionValue = document.form1.action;
document.form1.msg.value =
“Your form was submitted to the following URL:\n “ + actionValue;
15 0672321416 CH08b 7/24/01 12:22 PM Page 764
Form.elements
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.elements
Description
The elements property of the Form object represents the elements array, which is used
to access each element within a form. The order of the form elements in the elements
array is the order in which they appear in the HTML source.
Example
Listing 8.170 shows how to access form elements using the elements array. Because it
is accessing the first element in the form, the index 0 is used. The second element in
the form can be accessed with elements[1].
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function getName(){
var textName = document.form1.elements[0].name;
alert(“The textbox name is: “ + textName);
}
// -->
</script>
<form name=”form1”>
15 0672321416 CH08b 7/24/01 12:22 PM Page 765
Client-Side 765
Form.elements.length
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.elements.length
Description
The elements.length property of the Form object specifies the number of items in the
elements array. Each item in the array refers to an object in the HTML form.
Example
Listing 8.171 shows how to use the elements.length property. When the user clicks
the Get Elements button, an alert box is displayed indicating the number of elements
in the form.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function uses the elements.length property to get the number
// of elements in the form.
function getNum(){
var numOfElements = document.form1.elements.length;
alert(“The number of elements in this document are:” + numOfElements);
}
// -->
</script>
<form name=”form1”>
Dummy text box:
<input type=”text” name=”textbox1” size=”25”>
<br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 766
Form.encoding
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.encoding
Description
The encoding property of the Form object represents the type of encoding used by the
form. It can be specified in the HTML <form> tag as the enctype attribute.
NOTE
Setting the encoding property will override the HTML enctype attribute.
Example
In Listing 8.172, the encoding property of the Form object is used to get the type of
encoding being used by the form.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// This function returns the encoding type for the specified form.
function getEncoding(){
var encodingType = document.form1.encoding;
return encodingType;
}
// -->
</script>
Client-Side 767
Form.handleEvent()
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
form.handleEvent(event)
Description
The handleEvent() method of the Form property invokes the handler for the specified
event. It takes one parameter, which is the event to be handled.
Example
In Listing 8.173, the handleEvent() method is being used to handle the event being
passed. The script captures the CLICK event. When this occurs, the handleMyClick()
function calls the handleEvent() method to handle the CLICK event.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleMyClick(evnt){
window.document.button1.handleEvent(evnt);
}
function displayMsg(){
document.form1.msg.value += “Click event occurred.\n”;
}
// This registers the handle function as the event handler for the
// CLICK event.
document.onClick = handleMyClick;
15 0672321416 CH08b 7/24/01 12:22 PM Page 768
<form name=”form1”>
<input type=”button” value=”Click on Me” name=”button1” onClick=’displayMsg()’>
<br><br>
<textarea name=”msg” rows=”10” cols=”50” onClick=’displayMsg()’></textarea>
</form>
</body>
</html>
Form.length
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.length
Description
The length property of the Form object represents the number of elements within a
form.
NOTE
This property works the same as the elements.length property.
Example
Listing 8.174 shows an example of how the length property is used to determine the
number of elements in the document. The showNumElements() function informs the
user of the form length, which represents the number of form elements.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// function displays an alert box indicating the number of elements
// in the form.
function showNumElements(){
alert(“There are “ + document.form1.length +
➥ “ elements in this document”);
}
15 0672321416 CH08b 7/24/01 12:22 PM Page 769
Client-Side 769
// -->
</script>
<form name=”form1”>
Enter First Name:
<input type=”text” size=”15”><br>
Enter Last Name:
<input type=”text” size=”20”><br>
Enter address:
<input type=”text” size=”40”><br><br>
<input type=”button” value=”Submit” onClick=’showNumElements()’>
</form>
</body>
</html>
Form.method
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.method
Description
The method property of the Form object represents the type of submission, GET or POST,
being used by the form.
Example
In Listing 8.175, the method property is used to get the type of method being used by
the form. The informMethod() function alerts the user of the method, GET or POST,
being used by the form.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function informMethod(){
alert(“The form method is:” + document.form1.method);
}
// -->
</script>
15 0672321416 CH08b 7/24/01 12:22 PM Page 770
Form.name
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.name
Description
The name property of the Form object represents the name of the form as specified in
the HTML <form> tag.
Example
Listing 8.176 shows how the name property is used to get the HTML name attribute of
the form. The showName function uses the Form object to access the name attribute of
the form.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function showName(){
// Alert box tells what the name of the form is
alert(“Form Name is: “ + document.form1.name);
}
// -->
</script>
Client-Side 771
</form>
</body>
</html>
Form.onReset
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
onReset=”command”
Description
The onReset method of the Form object executes JavaScript code when a reset event
occurs.
Example
Listing 8.177 demonstrates the use of the onReset event handler. The JavaScript func-
tion checks to see if the Reset button has been clicked. If so, all the text values are reset
to a specified value.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Function displays a message when the onReset event handler determines that
// the reset button has been pressed.
function showMsg(){
document.form2.msg.value = “You have cleared the Entry Fields.”;
}
// -->
</script>
<form name=”form2”>
Message:<input type=”text” name=”msg” size=”50”>
<br><br>
</form>
</body>
</html>
Form.onSubmit
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onSubmit=”command”
Description
The onSubmit method of the Form property executes JavaScript code when a submit
event occurs.
Example
Listing 8.178 shows how the onSubmit event handler is used for a Form object. A user
would enter her comments in the text area provided. When finished, she clicks the
Submit button to submit the form. Using the onSubmit event handler, you can display
a thank you note when the user has submitted her comments.
<body>
Client-Side 773
Form.reset()
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
form.reset()
Description
The reset method of the Form object resets all the form elements to their default val-
ues. It operates the same as a mouse click on a Reset button for the calling form.
Example
Listing 8.179 shows how the reset method is used to reset a form. When the Reset but-
ton is clicked, all values in the form object are reset (text boxes are cleared of their val-
ues).
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function resetForm(form){
document.form1.reset(form);
}
// -->
</script>
<form name=”form1”>
Field 1:<input type=”text” size=”20” name=”text1”><br>
Field 2:<input type=”text” size=”20” name=”text2”><br>
Field 3:<input type=”text” size=”20” name=”text3”><br>
<input type=”button” name=”reset” value=”reset” onClick=’resetForm(this.form)’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 774
Form.submit()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.submit()
Description
The submit() method of the Form object is used to submit a form. It operates the same
as if a Submit button was clicked.
Example
Listing 8.180 shows how you would submit a form using the submit() method. The
form is submitted to the value specified in the action attribute of the HTML <form>
tag. In this specific example, a made up script processes the form.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// Function submits a form to a server specified in the <form> tag
function submitForm(form){
document.form1.submit(form);
}
// -->
</script>
Client-Side 775
Form.target
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
form.target
Description
The target property of the Form object represents the target window or frame in which
the form results will be displayed. This can also reflect the target attribute of the
HTML <form> tag. Valid target attributes are: _blank, _parent, _self, and _top.
Example
In Listing 8.181, a sample form is created for submission. When the Submit button is
clicked, the show() function is called to inform the user whether the target property
has been specified or not.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
function show(){
if(tar == “_self”){
alert(“The target for this form submission is this window”);
}
else{
alert(“The target has not been specifically specified”);
}
}
// -->
</script>
</body>
</html>
Form.unwatch()
JavaScript 1.2+
Nav4+
Syntax
form.unwatch(prop)
Description
The unwatch() method of the Form object is used to remove a watchpoint set on a prop-
erty by the watch() method. It takes one parameter, prop, which is the property to
unwatch.
Example
Listing 8.182 shows how the unwatch() method is used to disable the watchpoint on
the form name.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.forms[0].name;
watch(“myProp”,alertme);
myProp = “red_form”;
unwatch(“myProp”);
myProp = “blue_form”;
}
// -->
</script>
<body>
15 0672321416 CH08b 7/24/01 12:22 PM Page 777
Client-Side 777
<form name=”form1”>
<input type=”button” value=”Click Here” onClick=’setWatch()’>
</form>
</body>
</html>
Form.watch()
JavaScript 1.2+
Nav4+
Syntax
form.watch(prop, handler)
Description
The watch() method of the Form object is used to watch for changes to Form proper-
ties. When one of the properties, prop, is assigned a value, a handler is used to call a
user defined function.
Example
Listing 8.183 shows how the watch() method is set on the form name property. When
the button is clicked, the watchpoint is set and then the property is changed. Each time
it is changed, the alertme function is called to display the changes.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.forms[0].name;
watch(“myProp”,alertme);
myProp = “red_form”;
myProp = “blue_form”;
}
// -->
</script>
<body>
15 0672321416 CH08b 7/24/01 12:22 PM Page 778
</body>
</html>
Frame
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
A window can display multiple, independently scrollable frames on a single screen,
each with its own distinct URL. The Frame object, which has an instance created with
each occurrence of the <frame> tag, is a convenience for thinking about the objects that
make up these frames. However, JavaScript actually represents a frame using a Window
object. Every Frame object is a Window object, and has all the methods and properties
of a Window object. Table 8.15 shows the available methods and properties of Frames.
NOTE
The majority of examples for the Frame object assume that top.html and
bottom.html files exist. Some examples also only display the JavaScript code that
would be contained in a document.
Client-Side 779
Example
Listing 8.184 shows the code to create an HTML frame and access its properties. This
example assumes that the files top.html and bottom.html already exist.
<frameset rows=”100,*”>
<frame src=”top.html” name=”upper”>
<frame src=”bottom.html” name=”bottom” scrolling=”yes”>
</frameset>
</html>
Frame.blur()
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
frame.blur()
15 0672321416 CH08b 7/24/01 12:22 PM Page 780
Description
The blur() method of the Frame object removes focus from the frame.
Example
Listing 8.185 uses the blur() method to remove focus from the frame.
<frameset rows=”100,*”>
<frame src=”top.html” name=”upper” onDblClick=’removeFocus()’>
<frame src=”bottom.html” name=”bottom” scrolling=”yes”>
</frameset>
</html>
Frame.clearInterval()
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
frame.clearInterval()
Description
The clearInterval() method of the Frame object is used to cancel a repeated execu-
tion.
Example
Listing 8.186 shows the syntax for accessing the clearInterval() method. For a more
detailed example, see window.clearInterval().
Client-Side 781
}
// -->
</script>
Frame.clearTimeout()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.clearTimeout()
Description
The clearTimeout() method of the Frame object is used to cancel a delayed execu-
tion. For a more detailed example, see window.clearTimeout().
Example
Listing 8.187 shows the syntax for accessing the clearTimeout() method.
Frame.document
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.document
Description
The document property of the Frame object contains information about the current
document. The document property is created by the HTML <body> tag and is available
in every Frame or Window object. The document property is used to access other aspects
of the HTML document.
Example
Listing 8.188 shows how the document property can be used to access document ele-
ments within a specific frame. For a more detailed example, see window.document.
15 0672321416 CH08b 7/24/01 12:22 PM Page 782
Frame.focus()
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
frame.focus()
Description
The focus() method of the Frame object is used to set the focus to a specific frame.
Example
Listing 8.189 shows the syntax for using the focus() method. When the document is
loaded, the focus is automatically set to the bottom frame.
</html>
Frame.frames
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
15 0672321416 CH08b 7/24/01 12:22 PM Page 783
Client-Side 783
Syntax
frame.frames[num]
Description
The frames property of the Frame object represents an array that stores child frame
objects. Array entries of the child frame can be referenced either by index number or
by the name assigned from the name attribute.
Example
In Listing 8.190, the frames array is used to access the length of the child frame.
Frame.length
JavaScript 1.0+, ECMAScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.length
Description
The length property of the frames object represents the length of the frames array,
which is the number of child frames.
Example
Listing 8.191 shows a simple function call that uses the length property to set a vari-
able for the number of child frames.
Frame.name
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.name
Description
The name property of the Frame object represents the name given to a frame as speci-
fied from the name attribute of the HTML <frame> tag.
Example
In Listing 8.192, the name property is used to inform the user of the active frame.
Frame.onBlur
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
onBlur=”command”
Description
The onBlur event handler specifies what happens when the focus has been removed
from a frame.
Example
In Listing 8.193, the onBlur event handler is used to change the color of the upper
frame when the focus is set on it.
Client-Side 785
<!--
function change(){
frames[0].onblur=new Function(“document.bgColor=’green’”)
}
// -->
</script>
</html>
Frame.onFocus
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
onFocus=”command”
Description
The onFocus event handler is used to specify when the focus is brought to a frame.
The user can set the focus either by pressing the mouse button or by using the Tab key.
Example
The syntax for accessing the onFocus event handler is shown in Listing 8.194. When
the focus is set on the top frame, an alert box is displayed.
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 786
Frame.onMove
JavaScript 1.2+, ECMAScript 1.0+, JScript 1.0+
Nav4+, IE3+
Syntax
onMove=”command”
Description
The onMove frame event handler is used to specify what happens when a move event
occurs within a frame.
Example
Listing 8.195 shows the onMove event handler being used to inform the user when the
frame is being moved.
</html>
Frame.onResize
JavaScript 1.2+, ECMAScript 1.0+
Nav4+
Syntax
onResize=”command”
Description
The onResize frame event handler is used to specify when a frame has been resized.
Example
Listing 8.196 shows how you would use the onResize event handler to check for when
a frame has been resized.
Client-Side 787
</html>
Frame.parent
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.parent
Description
The parent property of the Frame object specifies the frame containing the current
frame.
Example
Listing 8.197 shows a small example of how the name of the Frame parent can be
accessed.
Frame.print()
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
frame.print(options)
Description
Theprint method of the Frame object is used to send the document output of a partic-
ular frame to a printer. This works the same as executing the Print command from a
browser menu.
15 0672321416 CH08b 7/24/01 12:22 PM Page 788
Example
Listing 8.198 shows an example of the print method. Using the onClick event han-
dler, the print() method is executed when the bottom frame is clicked.
</html>
Frame.self
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.self
Description
The self property of the Frame object is used as a keyword to reference the current
frame.
Example
Listing 8.199 shows an example of the self property being used to get the name for
the current frame.
Frame.setInterval()
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
15 0672321416 CH08b 7/24/01 12:22 PM Page 789
Client-Side 789
Syntax
frame.setInterval(exp,num)
Description
ThesetInterval() method of the Frame object is used to schedule a function for
repeated execution. It takes two parameters. The first parameter, exp, is the expression
being executed. The second parameter, num, is the time in milliseconds that elapses
before the expression is executed again. The function being executed is stopped by call-
ing the clearInterval() method.
Example
Listing 8.200 shows a simple example of a setInterval() method call. For a more
detailed example, see window.setInterval.
Frame.setTimeout()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.setTimeout(str,num)
Description
The setTimeout() method of the Frame object is used to schedule a function for
delayed execution. The method accepts two parameters. The first parameter, str, is the
function or expression being evaluated. The second parameter, num, is a numeric value
specifying the millisecond units that elapse before the function or expression is exe-
cuted.
Example
Listing 8.201 shows a example of the setTimeout() method being used to delay the
printing of text.
<frameset rows=”100,*”>
<frame src=”top.html” name=”upper”>
<frame src=”bottom.html” name=”bottom” scrolling=”yes”>
</frameset>
</html>
Frame.top
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.top
Description
The top property of the Frame object specifies the top-most browser window contain-
ing frames.
Example
Listing 8.202 shows an example of how the top property is used to get the name of the
top frame.
Frame.unwatch()
JavaScript 1.2+
Nav4+
Syntax
frame.unwatch(prop)
15 0672321416 CH08b 7/24/01 12:22 PM Page 791
Client-Side 791
Description
The unwatch() method of the Frame object is used to remove a watchpoint set on a
property by the watch() method. It takes one parameter, prop, which is the property to
unwatch.
Example
Listing 8.203 shows how the unwatch() method is used to remove the watchpoint set
on the frame name. The setWatch method sets the watchpoint on the frame name ini-
tially. When the name is changed, the alertme function is called. The watchpoint is
then removed using the unwatch()method.
// -->
</script>
Frame.watch()
JavaScript 1.2+
Nav4+
Syntax
frame.watch(prop, handler)
Description
The watch() method of the Frame object is used to watch for changes to Frame prop-
erties. When one of the properties, prop, is assigned a value, a handler is used to call
a user-defined function.
15 0672321416 CH08b 7/24/01 12:22 PM Page 792
Example
Listing 8.204 shows how the watch() method is used to set a watchpoint on the frame
name. The setWatch method sets the watchpoint on the frame name initially. When the
name is changed, the alertme function is called.
// -->
</script>
Frame.window
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
frame.window
Description
The window property of the Frame object is used to reference the current frame. This
works the same as using the self property.
Example
Listing 8.205 shows an example of the syntax of the window property.
Client-Side 793
<!--
//Sets focus to the upper frame.
document.upper.window.focus();
// -->
</script>
<frameset rows=”100,*”>
<frame src=”top.html” name=”upper”>
<frame src=”bottom.html” name=”bottom”>
</frameset>
</html>
Hidden
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Hidden object is created using the HTML <input> tag. Specifying the type para-
meter of the <input> tag as hidden creates the Hidden object. It is a text object that is
not visible in an HTML form. The Hidden object is primarily used for passing
name/value pairs from a form. Table 8.16 shows the properties of the Hidden object.
Example
Listing 8.206 shows how a Hidden object is created and how some of its properties are
accessed.
15 0672321416 CH08b 7/24/01 12:22 PM Page 794
<body>
<form name=”form1”>
<input type=”hidden” name=”hide1” value=”Test”>
<p>
<input type=”button” value=”Get Hidden Attributes”
onClick=’alert(“The Hidden object Name is: “ + form1.hide1.name +
➥ “ The Hidden Type is: “ + form1.hide1.type + “ The Hidden Value is: “
➥ + form1.hide1.value)’>
</form>
</body>
</html>
Hidden.form
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
hidden.form
Description
The form property of the Hidden object is used to reference the form containing the
Hidden object.
Example
Listing 8.207 shows how the form property is used to store the name of the form.
<body>
<form name=”form1”>
Form name:<input type=”hidden” name=”hide1” value=”Test”>
<p>
<input type=”button” value=”Form Name”
onClick=”this.form.hide1.value=this.form.name”>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 795
Client-Side 795
Hidden.name
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
hidden.name
Description
The name property of the Hidden object is used to get the name of the Hidden object.
This is the HTML name attribute for the Hidden object.
Example
Listing 8.208 shows an example of how the name property is used. The form object is
used to access the name property.
<body>
<form name=”form1”>
Form name:<input type=”hidden” name=”hide1” value=”Test”>
<p>
<input type=”button” value=”Hidden Name”
onClick=’alert(“The Hidden object name is: “ + form1.hide1.name)’>
</form>
</body>
</html>
Hidden.type
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera3+
Syntax
hidden.type
Description
The type property of the Hidden object specifies the hidden type. For all Hidden
objects, the type value is Hidden.
Example
Listing 8.209 shows an example of how the type property is used to get the hidden
type. The form object is used to access the type property.
15 0672321416 CH08b 7/24/01 12:22 PM Page 796
<body>
<form name=”form1”>
Form name:<input type=”hidden” name=”hide1” value=”Test”>
<p>
<input type=”button” value=”Hidden Type”
onClick=’alert(“The Hidden object type is: “ + form1.hide1.type)’>
</form>
</body>
</html>
Hidden.unwatch()
JavaScript 1.2+
Nav4+
Syntax
hidden.unwatch(prop)
Description
The unwatch() method of the Hidden object is used to remove a watchpoint set on a
property by the watch() method. It takes one parameter, which is the property to
unwatch.
Example
Listing 8.210 shows how the unwatch() method is used to turn off the watch point set
on the Hidden object value.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.form1.hide1.value;
watch(“myProp”,alertme);
myProp = “joe”;
15 0672321416 CH08b 7/24/01 12:22 PM Page 797
Client-Side 797
unwatch(“myProp”);
myProp = “jane”;
}
// -->
</script>
<body>
<form name=”form1”>
Hidden Input<input type=”hidden” name=”hide1” value=”Test”>
<p>
<input type=”button” value=”Click Here” onClick=’setWatch()’>
</form>
</body>
</html>
Hidden.value
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
hidden.value
Description
The value property of the hidden object reflects the HTML value attribute of the
Hidden object.
Example
Listing 8.211 shows how the value property of the Hidden object is used. The onClick
event handler is used to display an alert box to the user indicating the value of the
Hidden object.
<body>
<form name=”form1”>
Form name:<input type=”hidden” name=”hide1” value=”Test”>
<p>
<input type=”button” value=”Get Hidden Value”
onClick=’alert(“The Hidden object value is: “ + form1.hide1.value)’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 798
Hidden.watch()
JavaScript 1.2+
Nav4+
Syntax
hidden.watch(prop, handler)
Description
The watch() method of the Hidden object is used to watch for changes to Hidden prop-
erties. When one of the properties, prop, is assigned a value, a handler is used to call
a user-defined function.
Example
Listing 8.212 shows how the watch() method is used to check for assignments to the
hidden object value. If an assignment is made, the alertme function is called to notify
the user.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue + “</b>”
➥+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.form1.hide1.value;
watch(“myProp”,alertme);
myProp = “joe”;
myProp = “jane”;
}
// -->
</script>
<body>
<form name=”form1”>
Hidden Input<input type=”hidden” name=”hide1” value=”Test”>
<p>
<input type=”button” value=”Click Here” onClick=’setWatch()’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 799
Client-Side 799
History
JavaScript 1.0+, ECMAScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The History object is a predefined JavaScript object that allows you to navigate
through the history of Web sites that a browser has displayed. The browser stores a his-
tory of visited URLs in a list, which the History object references. Table 8.17 shows
the methods and properties of the History object.
Example
Listing 8.213 shows an example of how the History object is used. A for loop is used
to loop through the history list and outputs the Web site entries in the list.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
// code loops though the history list and outputs a history list
// of web sites visited.
for (i=0; i<history.length; i++){
document.writeln(window.history.previous);
}
//-- End Hide>
</script>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 800
History.back()
JavaScript 1.0+, ECMAScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
history.back()
Description
The back() method of the History object is used to load the URL for the previously
visited Web site.
Example
Listing 8.214 shows an example of how a JavaScript button can use the back() method
to simulate the browser’s back functionality.
<body>
<form name=”form1”>
Click on the button to go back to the previous page.
<input type=”button” value=”Go Back” onClick=’window.history.back()’>
</form>
</body>
</html>
History.current
JavaScript 1.1+, ECMAScript 1.0+, JScript 3.0+
Nav3+, IE4+
Syntax
history.current
Description
The current property of the History object contains a string that specifies the com-
plete URL of the current history entry.
NOTE
In Navigator 4 and higher, getting the current value requires the
UniversalBrowserRead privilege.
15 0672321416 CH08b 7/24/01 12:22 PM Page 801
Client-Side 801
Example
Listing 8.215 shows an example of how the current property is used. For this exam-
ple, the UniversalBrowserRead privilege must be set. When this is done, the onClick
event handler alerts the user of the History current property.
<body>
// -->
</script>
<form name=”form1”>
<input type=”button” value=”Get Current”
➥ onClick=’alert(window.history.current)’>
</form>
</body>
</html>
History.forward()
JavaScript 1.0+, ECMAScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
history.forward()
Description
The forward() method of the History object is used to load the URL for the next Web
site in the history list.
Example
Listing 8.216 shows an example of how the forward() method is used to simulate the
forward functionality of the browser.
15 0672321416 CH08b 7/24/01 12:22 PM Page 802
<body>
<form name=”form1”>
Click on the button to go to the forward browser page.
<input type=”button” value=”Go Forward” onClick=’window.history.forward()’>
</form>
</body>
</html>
History.go()
JavaScript 1.0+, ECMAScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
history.go(num)
Description
The go() method of the History object loads a URL from the history list.
Example
Listing 8.217 shows how the go() method can be used to navigate to another Web site
in the history list.
<body>
<form name=”form1”>
Click on the button to go back 2 pages.
<input type=”button” value=”Go” onClick=’window.history.go(-2)’>
</form>
</body>
</html>
History.length
JavaScript 1.0+, ECMAScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
history.length
15 0672321416 CH08b 7/24/01 12:22 PM Page 803
Client-Side 803
Description
The length property of the History object is used to get the number of URLs in the
history list.
Example
Listing 8.218 shows an example of how the length property is used to determine how
many URLs are in the history list.
<body>
</body>
</html>
History.next
JavaScript 1.1+, ECMAScript 1.0+, JScript 3.0+
Nav3+, IE4+
Syntax
history.next
Description
The next property of the History object is used to get the URL for the next entry in
the history list.
NOTE
In Navigator 4 and later, getting the next value requires the UniversalBrowserRead
privilege.
Example
Listing 8.219 shows an example of how the next property is used to get the next URL
in the history list. If nothing is displayed for the nextURL, you are at the end of the
history list.
15 0672321416 CH08b 7/24/01 12:22 PM Page 804
<body>
</body>
</html>
History.previous
JavaScript 1.1+, ECMAScript 1.0+, JScript 3.0+
Nav3+, IE4+
Syntax
history.previous
Description
The previous property of the History object is used to get the URL for the previous
entry in the history list.
NOTE
In Navigator 4 and later, getting the previous value requires the
UniversalBrowserRead privilege.
Example
Listing 8.220 shows an example of how the previous property is used to get the pre-
vious URL in the history list.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
15 0672321416 CH08b 7/24/01 12:22 PM Page 805
Client-Side 805
<form name=”form1”>
<input type=”button” value=”Get Previous”
➥ onClick=’alert(window.history.previous)’>
</form>
</body>
</html>
History.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
history.unwatch(prop)
Description
The unwatch() method of the History object is used to remove a watchpoint set on a
property by the watch() method. It takes one parameter, which is the property to
unwatch.
Example
Listing 8.221 shows how the unwatch() method is used to remove the watchpoint set
on the History object.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myRes = window.history.previous;
watch(“myRes”,alertme);
15 0672321416 CH08b 7/24/01 12:22 PM Page 806
// -->
</script>
<body>
<form name=”form1”>
<input type=”button” value=”Get Previous” onClick=’setWatch()’>
</form>
</body>
</html>
History.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
history.watch(prop, handler)
Description
The watch() method of the History object is used to watch for changes to History
properties. When one of the properties, prop, is assigned a value, a handler is used to
call a user-defined function.
Example
Listing 8.222 shows how the watch() method is used to watch for changes to the
history property.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myRes = window.history.previous;
watch(“myRes”,alertme);
15 0672321416 CH08b 7/24/01 12:22 PM Page 807
Client-Side 807
myRes = “something”;
myRes = “otherthing”;
}
// -->
</script>
<body>
<form name=”form1”>
<input type=”button” value=”Get Previous” onClick=’setWatch()’>
</form></body>
</html>
Image
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Image object represents an image that was created with the <img> tag. Images can
be downloaded and cached dynamically by using the Image() constructor, but they
cannot be displayed using the constructor. The constructor takes two optional argu-
ments, width and height. The argument width specifies the width of the image in pix-
els, whereas the argument height specifies the height of the image in pixels. If these
arguments are larger than the actual image, the image will be stretched to these dimen-
sions. You have probably noticed that there is no argument specifying the image to
load. The image to load is specified using dot notation and the src property after the
image constructor has been called. Table 8.18 lists all the properties, methods, and
events associated with Image object.
Example
Listing 8.223 demonstrates how to use the <img> tag and the Image() constructor to
alternate images in a document.
//Alternate flag
alternate=0;
function changeImage()
{
if(alternate==0)
{
document.magic.src=circle.src;
alternate=1;
}
else
{
document.magic.src=square.src;
15 0672321416 CH08b 7/24/01 12:22 PM Page 809
Client-Side 809
alternate=0;
}
}
// -->
</script>
<center>
<h2>Magic Trick</h2>
<form>
<input type=”button”
value=”Change Image”
onClick=”changeImage()”>
</form>
</html>
Image.border
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.border
Description
The border property of the Image object specifies the width of the border around an
image in pixels. This property can only be set by the border attribute of the <img> tag.
Example
Listing 8.224 shows how the border property is used.
<img name=”circle”
src=”circle.gif”
border=10>
<br>
// -->
</script>
</html>
Image.complete
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.complete
Description
The complete property of the Image object is a boolean value that specifies if an image
has finished loading. After an image has completely loaded, the property is changed to
false. If the load is aborted or an error occurs during the loading process, the property
will be set to true.
Example
Listing 8.225 displays a message based on the value of the complete property.
// -->
</script>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 811
Client-Side 811
Image.handleEvent()
JavaScript 1.2+,
Nav4+
Syntax
image.handleEvent(event)
Description
ThehandleEvent() method provides a way to invoke an image’s event handler, even
though the event never happened. The event argument associated with this method can
be any of the events handled by the Image object.
Example
Listing 8.226 shows how to force an image to handle a KEYDOWN event.
Image.height
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.height
Description
The height property of the Image object specifies the height of the image in pixels.
This property can only be set by the height attribute of the <img> tag.
Example
Listing 8.227 displays the value of the height property.
<img name=”circle”
src=”circle.gif”
height=”200”>
15 0672321416 CH08b 7/24/01 12:22 PM Page 812
// -->
</script>
</html>
Image.hspace
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.hspace
Description
The hspace property of the Image object specifies the number of extra pixels that
should appear on the left and right of the image. This property can only be set by the
hspace attribute of the <img> tag.
Example
Listing 8.228 demonstrates the hspace property. When the code sample is loaded, the
JavaScript code will write to the screen the value of the Image hspace property.
Client-Side 813
// -->
</script>
</html>
Image.lowsrc
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.lowsrc
Description
The lowsrc property of the Image object specifies the URL of an alternate image to use
on low-resolution displays. This property can only be set by the lowsrc attribute of the
<img> tag.
Example
Listing 8.229 displays the URL of the low-resolution image. When the code sample is
loaded into a browser, the JavaScript code will output the value of the lowsrc property.
<img name=”circle”
src=”circle.gif”
LOWsrc=”circle_low.gif”>
<br>
// -->
</script>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 814
Image.name
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.name
Description
The name property of the Image object specifies the name of the image. This property
can only be set by the name attribute of the <img> tag.
Example
Listing 8.230 displays the name of the image. When the code sample is loaded into a
browser, the JavaScript code will output the value of the name property.
// -->
</script>
</html>
Image.onAbort
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
onAbort=”command”
Description
TheonAbort event defines a handler when the loading of the image is aborted.
Example
Listing 8.231 creates an alert box when the loading of the image is aborted.
15 0672321416 CH08b 7/24/01 12:22 PM Page 815
Client-Side 815
Image.onError
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+
Syntax
onError=”command”
Description
The onError event handler is triggered when an error occurs while loading the image.
Example
Listing 8.232 creates an alert box if an error occurs while loading the image.
Image.onKeyDown
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
onKeyDown=”command”
Description
The onKeyDown event handler is triggered when a key is pressed down while the image
is selected.
Example
Listing 8.233 defines an event handler for the onKeyDown event within an image.
Image.onKeyPress
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
onKeyPress=”command”
Description
The onKeyPress event defines a handler when a key is pressed down while the image
is selected.
Example
Listing 8.234 defines an event handler for the onKeyPress event within an image.
Image.onKeyUp
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
onKeyUp=”command”
Description
The onKeyUp event defines a handler when a key is pressed and then released while the
image is selected.
Example
Listing 8.235 defines an event handler for the onKeyUp event within an image.
Image.onLoad
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
onLoad=”command”
15 0672321416 CH08b 7/24/01 12:22 PM Page 817
Client-Side 817
Description
The onLoad event handler defines what should happen once the image has finished
loading.
Example
Listing 8.236 displays a message once the image has finished loading.
Image.src
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.src
Description
The src property of the Image object specifies the URL of the image. This property can
only be set by the src attribute of the <img> tag.
Example
Listing 8.237 displays the URL of the image.
// -->
</script>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 818
Image.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
image.unwatch(prop)
Description
The unwatch() method of the Image object is used to remove a watchpoint set on a
property by the watch() method. It takes one parameter, which is the property to
unwatch.
Example
Listing 8.238 shows how the unwatch() method is used to remove the watchpoint set
on myImg.
myImg = document.myhome.name;
watch(“myImg”,alertme);
myImg = “Yourhome”;
unwatch(“myImg”);
myImg = “theirhome”;
// -->
</script>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 819
Client-Side 819
Image.vspace
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.vspace
Description
The vspace property of the Image object specifies the number of extra pixels that
should appear on the top and bottom of the image. This property can only be set by the
vspace attribute of the <img> tag.
Example
Listing 8.239 demonstrates the vspace property. When the code sample is loaded into
a browser, the JavaScript code will output the value of the vspace property.
// -->
</script>
</html>
Image.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
image.watch(prop, handler)
Description
The watch() method of the Image object is used to watch for changes to Image prop-
erties. When one of the properties, prop, is assigned a value, a handler is used to call
a user-defined function.
15 0672321416 CH08b 7/24/01 12:22 PM Page 820
Example
Listing 8.240 shows how the watch() method is used to determine when the name
property has been modified.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” +
➥oldValue + “</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
myImg = document.myhome.name;
watch(“myImg”,alertme);
myImg = “Yourhome”;
myImg = “theirhome”;
// -->
</script>
</html>
Image.width
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
image.width
Description
The width property of the Image object specifies the width of the image in pixels. This
property can only be set by the width attribute of the <img> tag.
Example
Listing 8.241 displays the value of the width property.
15 0672321416 CH08b 7/24/01 12:22 PM Page 821
Client-Side 821
<img name=”circle”
src=”circle.gif”
width=150>
<br>
// -->
</script>
</html>
Layer
JavaScript 1.2+
Nav4+
Syntax
Core client-side JavaScript object.
Description
The Layer object represents an object that contains a single document. A document can
contain multiple layers, and thereby contain multiple documents. Layers are useful for
displaying graphics which overlay each other within a browser. The Layer object has
specific properties and methods associated with it, as shown in Table 8.19.
Client-Side 823
Example
Listing 8.242 creates a layer. When the mouse cursor is moved over the Layer object,
an alert message is displayed informing which layer the cursor was moved over.
<body>
<layer id=”layer1” width=”150” height=”200” bgcolor=”yellow” top=”170”
left=”200” visibility=”show” onMouseOut=’alert(“This is layer 1”)’>
<center>Layer 1</center>
</layer>
</body>
</html>
Layer.above
JavaScript 1.2+
Nav4+
Syntax
layer.above
Description
The above property of the Layer object refers to the layer immediately above the layer
in the zIndex. If this does not exist, the value is null.
Example
Listing 8.243 shows how the above property is used. Two layers are created and when
the Get Above button is clicked, an alert box is displayed with the value of the above
attribute.
<body>
<form name=”form1”>
<input type=”button” value=”Get Above” onClick=’alert(document.layers.above)’>
</form>
</body>
</html>
Layer.background
JavaScript 1.2+
Nav4+
Syntax
layer.background
Description
The background property of the Layer object refers to the background attribute of the
<layer> tag. The background images for the layer object can be changed by setting the
background.src property.
Example
Listing 8.244 shows an example of how to change the layer background image. Two
layers are created and when the Change Background button is clicked, the change()
function is called. The change() function sets the background property of layer1 to
water.gif.
<body>
Client-Side 825
<center>Layer 1</center>
</layer>
<form name=”form1”>
<input type=”button” value=”Change Background” onClick=’change()’>
</form>
</body>
</html>
Layer.below
JavaScript 1.2+
Nav4+
Syntax
layer.below
Description
The below property of the Layer object specifies the layer object immediately below
the layer in the zIndex. If this does not exist, the below value is null.
Example
Listing 8.245 shows an example of the below property. Two layers are created using the
<layer> tag. When the Get Below button is clicked, an alert box is displayed showing
the value of the below property.
<body>
<form name=”form1”>
<input type=”button” value=”Get Below” onClick=’alert(document.layers.below)’>
</form>
</body>
</html>
Layer.bgColor
JavaScript 1.2+
Nav4+
Syntax
layer.bgColor
Description
The bgColor property of the Layer object represents the bgcolor attribute of the
<layer> tag. The background color for the Layer object can be changed by setting the
bgColor.src property. The color can only be changed if the background property is
not set.
Example
Listing 8.246 shows how the bgColor property is used to change the background col-
ors of the layer’s objects.
<body>
Client-Side 827
// -->
</script>
<form name=”form1”>
<input type=”button” value=”Change Layer 1 Background” onClick=’change1()’>
<br><br>
<input type=”button” value=”Change Layer 2 Background” onClick=’change2()’>
</form>
</body>
</html>
Layer.captureEvents()
JavaScript 1.2+
Nav4+
Syntax
layer.captureEvents(event.type)
Description
ThecaptureEvents() method of the Layer object is used to handle all events of a spe-
cific type.
Example
Listing 8.247 shows how the captureEvents() method is used. The captureEvents()
method is used for layer2 to listen for the RESIZE event. When this occurs, the
resize2() function is called, which displays a message to the user.
<body>
// function resizes layer2 and upon the resize event alerts the
// user that the layer was resized.
function resize2(){
document.layer2.resizeTo(300,100);
onResize=alert(“Layer2 has been resized.”);
}
// -->
</script>
<form>
Click the button to resize Layer 2
<br>
<input type=”button” value=”Resize Layer2” onClick=’resize2()’>
</form>
</body>
</html>
Layer.clip.bottom
JavaScript 1.2+
Nav4+
Syntax
layer.clip.bottom
Description
The clip.bottom property of the Layer object refers to the bottom of the layer’s clip-
ping area.
Example
Listing 8.248 shows an example of how clip.bottom is used. Two layers are created
using the <layer> tag. When the button is clicked, the clip1 function is called, which
clips the bottom of layer1 by 100 pixels.
15 0672321416 CH08b 7/24/01 12:22 PM Page 829
Client-Side 829
<body>
<form name=”form1”>
<input type=”button” value=”Clip bottom of Layer 1” onClick=’clip1()’>
</form>
</body>
</html>
Layer.clip.height
JavaScript 1.2+
Nav4+
Syntax
layer.clip.height
Description
The clip.height property of the Layer object refers to the height of the layer’s clip-
ping area.
Example
Listing 8.249 shows how the clip.height property is used. Two layers are created
using the <layer> tag. When the button is clicked, the clip1() function is called,
which clips the height of layer1 by 75 pixels.
15 0672321416 CH08b 7/24/01 12:22 PM Page 830
<body>
<form name=”form1”>
<input type=”button” value=”Clip Height of Layer 1” onClick=’clip1()’>
</form>
</body>
</html>
Layer.clip.left
JavaScript 1.2+
Nav4+
Syntax
layer.clip.left
Description
The clip.left property of the Layer object represents the left of the layer’s clipping
area.
Example
Listing 8.250 shows how the clip.left property is used. Two layers are created using
the <layer> tag. When the button is clicked, the clip1() function is called, which clips
the left side of layer1 by 90 pixels.
15 0672321416 CH08b 7/24/01 12:22 PM Page 831
Client-Side 831
<body>
<form name=”form1”>
<input type=”button” value=”Clip Left of Layer 1” onClick=’clip1()’>
</form>
</body>
</html>
Layer.clip.right
JavaScript 1.2+
Nav4+
Syntax
layer.clip.right
Description
The clip.right property of the Layer object represents the right of the layer’s clip-
ping area.
Example
Listing 8.251 shows how the clip.right property is used to shorten the right side of
the layer. Two layers are created using the <layer> tag. When the button is clicked, the
clip1() function is called, which clips the right side of layer1 by 110 pixels.
15 0672321416 CH08b 7/24/01 12:22 PM Page 832
<body>
<form name=”form1”>
<input type=”button” value=”Clip Right of Layer 1” onClick=’clip1()’>
</form>
</body>
</html>
Layer.clip.top
JavaScript 1.2+
Nav4+
Syntax
layer.clip.top
Description
The clip.top property of the Layer object represents the top part of the layer’s clip-
ping area.
Example
Listing 8.252 uses the clip.top property to shorten the height of the layer. Two layers
are created using the <layer> tag. When the button is clicked, the clip1() function is
called, which clips the top of layer1 by 88 pixels.
15 0672321416 CH08b 7/24/01 12:22 PM Page 833
Client-Side 833
<body>
<form name=”form1”>
<input type=”button” value=”Clip Top of Layer 1” onClick=’clip1()’>
</form>
</body>
</html>
Layer.clip.width
JavaScript 1.2+
Nav4+
Syntax
layer.clip.width
Description
The clip.width property of the Layer object represents the width of the layer’s clip-
ping area.
Example
Listing 8.253 shows how the clip.width property is used to shorten the width of the
layer. Two layers are created using the <layer> tag. When the button is clicked, the
clip1() function is called, which clips the width of layer1 by 60 pixels.
15 0672321416 CH08b 7/24/01 12:22 PM Page 834
<body>
<form name=”form1”>
<input type=”button” value=”Clip Width of Layer 1” onClick=’clip1()’>
</form>
</body>
</html>
Layer.document
JavaScript 1.2+
Nav4+
Syntax
layer.document
Description
The document property of the Layer object references the Document object contained
in the layer.
Example
Listing 8.254 shows how the document property is used. When the button is clicked,
the getInfo() function is called. This displays the name of the document in layer1.
15 0672321416 CH08b 7/24/01 12:22 PM Page 835
Client-Side 835
<body>
<form name=”form1”>
<input type=”button” value=”Get Layer1 document info” onClick=’getInfo()’>
</form>
</body>
</html>
Layer.handleEvent()
JavaScript 1.2+
Nav4+
Syntax
layer.handleEvent(event)
Description
The handleEvent method of the Layer object determines what type of event occurred
and passes the event to the object’s appropriate event handler.
Example
Listing 8.255 shows how to use the handleEvent method. The document is set up to
capture any FOCUS events. When one occurs, it is sent to the handle() function, which
15 0672321416 CH08b 7/24/01 12:22 PM Page 836
passes it to the default handler for layer2 object. This calls the displayMsg() function
for any FOCUS events that occur.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
window.document.layer2.handleEvent(evnt);
}
function displayMsg(){
alert(“Focus event occurred.”);
}
// This registers the handle function as the event handler for the
// FOCUS event.
document.onFocus = handle;
// -->
</script>
<form name=”form1”>
<input type=”button” value=”Get Layer1 document info” onClick=’getInfo()’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 837
Client-Side 837
Layer.left
JavaScript 1.2+
Nav4+
Syntax
layer.left
Description
The left property of the Layer object represents the x-coordinate position of the layer
within the document. Changing this property can move the layer left or right.
Example
Listing 8.256 shows how the left property is used to move the layer from left to right
across the screen. When the button is clicked, the move() function is called, which
moves layer1 to the left by 60 pixels.
<body>
<form name=”form1”>
<input type=”button” value=”Move layer 1” onClick=’move()’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 838
Layer.load()
JavaScript 1.2+
Nav4+
Syntax
layer.load(src, width)
Description
The load() method of the Layer object is used to load a new document in the layer.
As described in the syntactical definition, this method takes the URL of the source of
the layer and the width.
Example
Listing 8.257 shows how to use the load() method. When the button is clicked, the
onClick event handler loads the tmp.html file.
<form name=”form1”>
<input type=”button” value=”Load Layer 2”
➥ onClick=’document.layer2.load(“tmp.html”, 400)’>
</form>
</body>
</html>
Layer.moveAbove()
JavaScript 1.2+
Nav4+
Syntax
layer.moveAbove(layername)
15 0672321416 CH08b 7/24/01 12:22 PM Page 839
Client-Side 839
Description
The moveAbove() method of the Layer object is used to move the current layer above
another specified layer. The parameter, layername, is the Layer object that gets moved
back.
Example
Listing 8.258 an example of how the moveAbove() method is used. When the button is
clicked, the onClick event handler handles the CLICK event and moves Layer1 above
Layer2.
<body>
<form name=”form1”>
<input type=”button” value=”Move layer 1 above layer 2”
onClick=’document.layer1.moveAbove(document.layer2)’>
</form>
</body>
</html>
Layer.moveBelow()
JavaScript 1.2+
Nav4+
Syntax
layer.moveBelow(layername)
Description
The moveBelow() method of the Layer object is used to move a Layer object below
another specified layer. The function takes a single parameter, layername, representing
the Layer object that gets moved forward.
15 0672321416 CH08b 7/24/01 12:22 PM Page 840
Example
Listing 8.259 shows how the moveBelow() method is used to move Layer2 below
Layer1.
<form name=”form1”>
<input type=”button” value=”Move layer 2 below layer 1”
onClick=’document.layer2.moveBelow(document.layer1)’>
</form>
</body>
</html>
Layer.moveBy()
JavaScript 1.2+
Nav4+
Syntax
layer.moveBy(x,y)
Description
The moveBy() method of the Layer object moves the layer object to the right and down
from its current position. The method takes two parameters, x and y. The x parameter
refers to the number of pixels the layer is moved to the right. The y parameter refers to
the number of pixels the layer is moved down.
Example
Listing 8.260 shows how the moveBy() method is used. When the button is clicked, the
onClick event handler uses the moveBy method to move layer2 50 pixels to the right
and 30 pixels down.
15 0672321416 CH08b 7/24/01 12:22 PM Page 841
Client-Side 841
<body>
<form name=”form1”>
<input type=”button” value=”Move layer 2”
➥ onClick=’document.layer2.moveBy(50,30)’>
</form>
</body>
</html>
Layer.moveTo()
JavaScript1.2+
Nav4+
Syntax
Layer.moveTo(x,y)
Description
The moveTo() method of the Layer object moves the top-left corner of the Layer object
to the specified screen coordinates. The x parameter refers to an integer representing
the top edge of the window in screen coordinates. The y parameter refers to an integer
representing the left edge of the window in screen coordinates.
Example
Listing 8.261 shows how the moveTo() method is used. Two layers are created using
the <layer> tag. When the button is clicked, the onClick event handler for layer2
invokes the moveTo method, which moves the layer to the screen coordinates 100, 200.
<form name=”form1”>
<input type=”button” value=”Move layer 2”
➥ onClick=’document.layer2.moveTo(100,200)’>
</form>
</body>
</html>
Layer.moveToAbsolute()
JavaScript 1.2+
Nav4+
Syntax
layer.moveToAbsolute(x,y)
Description
The moveToAbsolute() method of the Layer object moves the upper-left corner of the
layer to the specified position. This position is relative to the top-level document. The
method takes two parameters, x and y. The x parameter refers to the number of pixels
the layer is moved to the right. The y parameter refers to the number of pixels the layer
is moved down.
Example
Listing 8.262 an example of how the moveToAbsolute() method is used. When the but-
ton is clicked, the upper-left corner of the second layer is moved to position 350x 400y.
Client-Side 843
<form name=”form1”>
<input type=”button” value=”Move layer 2”
onClick=’document.layer2.moveToAbsolute(350,400)’>
</form>
</body>
</html>
Layer.name
JavaScript 1.2+
Nav4+
Syntax
layer.name
Description
Thename property of the Layer object refers to the name or ID attribute of the <layer>
tag.
Example
Listing 8.263 shows how to access the layer’s name.
<form name=”form1”>
<input type=”button” value=”Get Layer 1 Name”
onClick=’alert(“The name of this layer is: “ + document.layer1.name)’>
<br><br><br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 844
</body>
</html> >
Layer.onBlur
JavaScript 1.2+
Nav4+
Syntax
onBlur=”command”
Description
The onBlur event handler of the Layer object handles the event when the focus is
removed from the Layer object.
Example
Listing 8.264 shows how the onBlur event handler is used. When focus is removed
from layer1, the onBlur event handler calls the showMsg() function.
Client-Side 845
<form name=”form1”>
Click on Layer 1 and the click on Layer 2.
<br><br>
<input type=”text” name=”text1” size=”40”>
</form>
</body>
</html>
Layer.onFocus
JavaScript 1.2+
Nav4+
Syntax
onFocus=”command”
Description
The onFocus event handler for the Layer object notifies you when the focus is set on a
layer object.
Example
Listing 8.265 shows how the onFocus event handler is used to detect when focus is set
on Layer 1.
</body>
</html>
Layer.onLoad
JavaScript 1.2+
Nav4+
Syntax
onLoad=”command”
Description
The onLoad property of the Layer object is an event handler that notifies you when the
layer’s contents are being loaded.
Example
Listing 8.266 shows how the onLoad event handler is used.
<body>
Client-Side 847
<form name=”form1”>
<input type=”text” name=”text1” size=”40”>
<br><br>
<input type=”button” value=”Load Layer 1”
➥ onClick=’document.layer1.load(“tmp.html”,300)’>
</form>
</body>
</html>
Layer.onMouseOut
JavaScript 1.2+
Nav4+
Syntax
onMouseOut=”command”
Description
The onMouseOut property of the Layer object is an event handler that notifies you when
the mouse cursor has moved out of the layer region.
Example
Listing 8.267 shows how the onMouseOut event handler is used. When the the mouse
cursor is moved over Layer 1 and then is moved out of the Layer 1 region, the event
handler invokes the showMsg1() function to alert the user.
<body>
<form name=”form1”>
<input type=”text” name=”text1” size=”40”>
<br><br>
</form>
</body>
</html>
Layer.onMouseOver
JavaScript 1.2+
Nav4+
Syntax
onMouseOver=”command”
Description
The onMouseOver event handler of the Layer object handles the events when the mouse
cursor is moved over the layer area.
Example
Listing 8.268 shows an example of the onMouseOver event handler. When the mouse
cursor is moved over Layer 2, the event handler invokes the showMsg1() function to
alert the user.
Client-Side 849
<center>Layer 1</center>
</layer>
<form name=”form1”>
<input type=”text” name=”text1” size=”40”>
<br><br>
</form>
</body>
</html>
Layer.pageX
JavaScript 1.2+
Nav4+
Syntax
layer.pageX
Description
The pageX property of the Layer object represents the x-coordinate position of the
layer relative to the top-level document.
Example
Listing 8.269 shows how to use the pageX property. When the button is clicked, the
value of the pageX property is displayed.
<form name=”form1”>
<input type=”button” value=”Change Layer 1 X-coordinate” onClick=size()>
</form>
</body>
</html>
Layer.pageY
JavaScript 1.2+
Nav4+
Syntax
layer.pageY
Description
The pageY property of the Layer object represents the y-coordinate position of the
layer relative to the top-level document.
Example
Listing 8.270 shows how to manipulate the pageY property. When the button is clicked,
the size function is called, which adds 20 pixels to the pageY attribute of layer1.
<body>
Client-Side 851
// -->
</script>
<form name=”form1”>
<input type=”button” value=”Change Layer 1 Y-coordinate” onClick=’size()’>
</form>
</body>
</html>
Layer.parentLayer
JavaScript 1.2+
Nav4+
Syntax
layer.parentLayer
Description
The parentLayer property of the Layer object represents the window or Layer object
that contains the current Layer object.
Example
Listing 8.271 shows how to use the parentLayer. The function getname() gets and
returns the name of the parent layer.
<body>
<form name=”form1”>
<input type=”button” value=”Get Layer 1 parent name” onClick=’getname()’>
<br><br>
<input type=”text” name=”text1” size=”40”>
</form>
</body>
</html>
Layer.releaseEvents()
JavaScript 1.2+
Nav4+
Syntax
layer.releaseEvents(event)
Description
The releaseEvents() method of the Layer object specifies that the Layer object
should no longer capture events of the specified type.
Example
Listing 8.272 is an example of how the releaseEvents() method is used. When the
FOCUS event is captured, it is handled by the handle() method. After this is done, exe-
cuting the event is released using the releaseEvents() method.
15 0672321416 CH08b 7/24/01 12:22 PM Page 853
Client-Side 853
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The layer got a FOCUS event and calls releaseEvents”);
return true;
}
function releaseFocus(){
document.layer2.releaseEvents(Event.FOCUS);
}
// This registers the handle function as the event handler for the
// FOCUS event.
document.onFocus = handle;
// -->
</script>
</body>
</html>
Layer.resizeBy()
JavaScript 1.2+
Nav4+
Syntax
layer.resizeBy(x,y)
15 0672321416 CH08b 7/24/01 12:22 PM Page 854
Description
The resizeBy() method of the Layer object resizes the layer by a relative size. The x
parameter refers to the number of pixels the layer width is increased. The y parameter
refers to the number of pixels the layer height is increased.
Example
Listing 8.273 shows how to resize a Layer object. When the button is clicked, the
onClick event handler executes the resizeBy() method to resize layer2.
<body>
<form name=”form1”>
<input type=”button” value=”Resize Layer 2”
➥ onClick=’document.layer2.resizeBy(30, 50)’>
<br>
</form>
</body>
</html>
Layer.resizeTo()
JavaScript 1.2+
Nav4+
Syntax
layer.resizeTo(x,y)
Description
The resizeTo() method of the Layer object resizes the Layer object to the specified
value. The x parameter refers to the number of pixels by which the layer width is
increased. The y parameter refers to the number of pixels by which the layer height is
increased.
15 0672321416 CH08b 7/24/01 12:22 PM Page 855
Client-Side 855
Example
Listing 8.274 shows how to resize a layer. When the button is clicked, the onClick
event handler uses the resizeTo() method to resize layer2.
<body>
<form name=”form1”>
<input type=”button” value=”Resize Layer 2”
➥ onClick=’document.layer2.resizeTo(100, 300)’>
<br>
</form>
</body>
</html>
Layer.routeEvent()
JavaScript 1.2+
Nav4+
Syntax
layer.routeEvent(event)
Description
The routeEvent() method of the Layer object reroutes a captured event to another
event handler. The method takes a single parameter representing the event to be routed.
Example
Listing 8.275 shows an example of the routeEvent() method. When the focus event
occurs, it is captured and the event is rerouted.
15 0672321416 CH08b 7/24/01 12:22 PM Page 856
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
alert(“The layer got a FOCUS event and executes routeEvent”);
document.routeEvent(evnt);
alert(“Event has been routed”);
return true;
}
// This registers the handle function as the event handler for the
// FOCUS event.
document.onFocus = handle;
// -->
</script>
</body>
</html>
Layer.siblingAbove
JavaScript 1.2+
Nav4+
Syntax
layer.siblingAbove
15 0672321416 CH08b 7/24/01 12:22 PM Page 857
Client-Side 857
Description
The siblingAbove property of the Layer object refers to the sibling layer immediately
above the current layer in the zIndex. If this doesn’t exist, null is returned.
NOTE
Any child of a parent layer is considered a sibling.
Example
Listing 8.276 shows how to get the siblingAbove property value. When the button is
clicked, the siblingAbove value is displayed.
<body>
<form name=”form1”>
<input type=”button” value=”Get Sibling Above Layer 1”
onClick=’alert(document.layer1.siblingAbove)’>
<br>
</form>
</body>
</html>
Layer.siblingBelow
JavaScript 1.2+
Nav4+
Syntax
layer.siblingBelow
Description
The siblingBelow property of the Layer object refers to the sibling layer immediately
below the current layer in the zIndex. If this doesn’t exist, null is returned.
15 0672321416 CH08b 7/24/01 12:22 PM Page 858
Example
Listing 8.277 shows the siblingBelow property. When the button is clicked, the
siblingBelow value is displayed.
<body>
<form name=”form1”>
<input type=”button” value=”Get Sibling Above Layer 1”
onClick=’alert(document.layer1.siblingBelow)’>
<br>
</form>
</body>
</html>
Layer.src
JavaScript 1.2+
Nav4+
Syntax
layer.src
Description
The src property of the Layer object represents the source URL of a particular layer.
Example
Listing 8.278 shows how the src property is used. When the button is clicked, the src
property is displayed.
15 0672321416 CH08b 7/24/01 12:22 PM Page 859
Client-Side 859
<body>
<form name=”form1”>
<input type=”button” value=”Get Layer 1 src”
➥onClick=’alert(document.layer1.src)’>
</form>
</body>
</html>
Layer.top
JavaScript 1.2+
Nav4+
Syntax
layer.top
Description
The top property of the Layer object represents the y-coordinate position of the layer
relative to the top-level document. Increasing or decreasing this value can move the
Layer object up or down.
Example
Listing 8.279 uses the top property to move the layer up. When the button is clicked,
the move() function is executed, which will move the layer up by 10 pixels.
<body>
<form name=”form1”>
<input type=”button” value=”Move layer 1 Up” onClick=’move()’>
</form>
</body>
</html>
Layer.unwatch()
JavaScript 1.2+
Nav4+
Syntax
layer.unwatch(prop)
Description
The unwatch() method of the Layer object is used to remove a watchpoint set on a
property by the watch() method. It takes one parameter, which is the property to
unwatch.
Example
Listing 8.280 shows how the unwatch() method is used to disable the watchpoint set
on the name property of the Layer object.
function alertme(id,oldValue,newValue)
{
15 0672321416 CH08b 7/24/01 12:22 PM Page 861
Client-Side 861
function setWatch(){
myProp = document.layers.name;
watch(“myProp”,alertme);
myProp = “red_layer”;
unwatch(“myProp”);
myProp = “blue_layer”;
}
// -->
</script>
<body>
<form name=”form1”>
<input type=”button” value=”Enable/Disable watchpoint” onClick=’setWatch()’>
</form>
</body>
</html>
Layer.visibility
JavaScript 1.2+
Nav4+
Syntax
layer.visibility
Description
The visibility property of the Layer object controls whether the layer is displayed
or hidden. Valid values for this property are: hide, show, and inherit. This property also
represents the HTML visibility attribute of the <layer> tag.
15 0672321416 CH08b 7/24/01 12:22 PM Page 862
Example
Listing 8.281 shows how the visibility property is used to hide a Layer object.
<body>
<form name=”form1”>
<input type=”button” value=”Hide Layer 2” onClick=’hide()’>
</form>
</body>
</html>
Layer.watch()
JavaScript 1.2+
Nav4+
Syntax
layer.watch(prop, handler)
Description
The watch() method of the Layer object is used to watch for changes to Layer prop-
erties. When one of the properties, prop, is assigned a value, a handler is used to call
a user-defined function.
15 0672321416 CH08b 7/24/01 12:22 PM Page 863
Client-Side 863
Example
Listing 8.282 shows how the watch() method is used to set a watchpoint on the name
property. When the name is changed, the alertme function is called to display the
changes to the browser.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.layers.name;
watch(“myProp”,alertme);
myProp = “red_layer”;
myProp = “blue_layer”;
}
// -->
</script>
<body>
<form name=”form1”>
<input type=”button” value=”Enable watchpoint” onClick=’setWatch()’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 864
Layer.zIndex
JavaScript 1.2+
Nav4+
Syntax
layer.zIndex
Description
The zIndex property of the Layer object represents the stacking order of the layers.
Example
Listing 8.283 shows an example of the zIndex property. When the button is clicked, an
alert box is displayed showing the value of zIndex.
<body>
<form name=”form1”>
<input type=”button” value=”Get Layer 2 zIndex”
➥ onClick=’alert(document.layer2.zIndex)’>
</form>
</body>
</html>
Link
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
15 0672321416 CH08b 7/24/01 12:22 PM Page 865
Client-Side 865
Description
The Link object represents an HTML hypertext link. This can be an image, text, or pre-
defined area within the Web page. All HTML links are stored in a links[] array. The
Link object has specific properties and methods associated with it, as shown in Table
8.20.
Example
Listing 8.284 shows how to use the Link object. When the link is clicked, the text of
the link is displayed.
15 0672321416 CH08b 7/24/01 12:22 PM Page 866
<body>
</body>
</html>
Link.handleEvent()
JavaScript 1.2+
Nav4+
Syntax
link.handleEvent(event)
Description
The handleEvent() method invokes the event handler for the Link object.
Example
Listing 8.285 shows how to access the handleEvent() method. All click events are
handled by the first link in the document.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handle(evnt){
document.form1.links[0].handleEvent(Event.CLICK);
}
function displayMsg(){
alert(“Click event occurred.”);
}
15 0672321416 CH08b 7/24/01 12:22 PM Page 867
Client-Side 867
// This registers the handle function as the event handler for the
// CLICK event.
document.onClick = handle;
// -->
</script>
<form name=”form1”>
<a href=”http://www.samspublishing.com:80/foo?something#foobar”
onClick=’displayMsg()’>
http://www.samspublishing.com:80/foo?something#foobar</a>
<br>
</form>
</body>
</html>
Link.hash
JavaScript 1.0+
Nav2+, Opera3+
Syntax
link.hash
Description
The hash property represents a portion of the currently displayed URL.
Example
Listing 8.286 shows an example of how the hash property is used. When the button is
clicked, the showHash() function displays the value of the hash property for the link.
<body>
</body>
</html>
Link.host
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
link.host
Description
The host property represents the host portion of the URL.
Example
Listing 8.287 shows how to use the host property. When the button is clicked, the
showHost() function is called to show the value of the host property.
<body>
Client-Side 869
http://www.samspublishing.com:80/foo?something#foobar</a>
<br><br>
Host value: <input type=”text” name=”text1” size=”20”>
<br><br>
<input type=”button” name=”host” value=”Get Host Value” onClick=’showHost()’>
<br>
</form>
</body>
</html>
Link.hostname
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
link.hostnamename
Description
The hostname property of the Link object represents the hostname portion of the link’s
URL.
Example
Listing 8.288 shows an example of how the hostname property is used. When the but-
ton is clicked, the showHostname() function is called, which displays the value of the
hostname property for the link.
<body>
</body>
</html>
Link.href
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
link.href
Description
The href property of the Link object represents the whole URL for the link.
Example
Listing 8.289 shows how to use the href property. When the button is clicked, the
showhref() function displays the value of the href property of the link.
<body>
Click the button to see the href property for the URL
<form name=”form1”>
<a href=”http://www.samspublishing.com:80/foo?something#foobar”>
http://www.samspublishing.com:80/foo?something#foobar</a>
<br><br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 871
Client-Side 871
</body>
</html>
Link.onClick
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onClick=”command”
Description
The onClick event handler for the Link object is used to handle the event when the
mouse cursor is clicked on the link.
Example
Listing 8.290 shows how to determine a mouse click using the onClick event handler.
<body>
</body>
</html>
Link.onDblClick
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
onDblClick=”command”
15 0672321416 CH08b 7/24/01 12:22 PM Page 872
Description
The onDblClick event handler of the Link object is used to handle the event when the
mouse cursor is double-clicked on the link.
Example
Listing 8.291 shows how to use the onDblClick event handler. When the link is
double-clicked, the event handler alerts the user indicating that the double-click action
occurred.
<body>
</body>
</html>
Link.onKeyDown
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
onKeyDown=”command”
Description
The onKeyDown event handler for the Link object is used to handle the event when a
key is pressed down while the focus is on the link.
Example
Listing 8.292 shows how the onKeyDown event handler operates. When a key is pressed
down, the event handler alerts the user about the action that occurred.
<body>
Client-Side 873
<form name=”form1”>
<a href=”http://www.samspublishing.com:80/foo?something#foobar”
onKeyDown=’alert(“You pressed the key DOWN on the link”)’>
http://www.samspublishing.com:80/foo?something#foobar</a>
<br><br>
</form>
</body>
</html>
Link.onKeyPress
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
onKeyPress=”command”
Description
The onKeyPress event handler for the Link object is used to handle the event if a key
is pressed when the focus is set on the link.
Example
Listing 8.293 shows how the onKeyPress event handler is used. The onKeyPress event
handler is invoked any time a key is pressed on the link.
<body>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 874
Link.onKeyUp
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
onKeyUp=”command”
Description
The onKeyUp event handler for the Link object is used to handle events in which a key
is pressed and then released.
Example
Listing 8.294 shows an example of how the onKeyUp event handler is used. The
onKeyUp event handler is invoked any time a key is pressed and released on the link.
<body>
</body>
</html>
Link.onMouseDown
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
onMouseDown=”command”
Description
The onMouseDown event handler of the Link object is used to handle the event when the
mouse button is pressed down while the mouse pointer is over the link.
Example
Listing 8.295 shows how the onMouseDown event handler is used. The onMouseDown
event handler is invoked any time the mouse button is pressed down while the cursor
is on the link.
15 0672321416 CH08b 7/24/01 12:22 PM Page 875
Client-Side 875
<body>
</body>
</html>
Link.onMouseOut
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
onMouseOut=”command”
Description
The onMouseOut event handler of the Link object is used to handle the event when the
mouse cursor is moved away from the link.
Example
Listing 8.296 shows how the onMouseOut event handler is used.
<body>
</body>
</html>
Link.onMouseOver
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onMouseOver=”command”
Description
The onMouseOver event handler of the Link object handles the event when the mouse
cursor is moved over the HTML link.
Example
Listing 8.297 shows how the onMouseOver event handler is used to display a message
when the mouse cursor is moved over the link.
<body>
// -->
</script>
Client-Side 877
http://www.samspublishing.com:80/foo?something#foobar</a>
<br><br>
<input type=”text” name=”text1” size=”50”>
</form>
</body>
</html>
Link.onMouseUp
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
onMouseUp=”command”
Description
The onMouseUp event handler for the Link object is used to handle the event when the
mouse button is pressed on the link and then released.
Example
Listing 8.298 shows how the onMouseUp event handler is used.
<body>
</body>
</html>
Link.pathname
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
link.pathname
15 0672321416 CH08b 7/24/01 12:22 PM Page 878
Description
The pathname property of the Link object represents the pathname portion of the link
URL.
Example
Listing 8.299 shows how the pathname property is used. When the button is clicked,
the showpathname function is executed. This displays the pathname for the link.
<body>
</body>
</html>
Link.port
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
link.port
15 0672321416 CH08b 7/24/01 12:22 PM Page 879
Client-Side 879
Description
The port property of the Link object represents the port number in the URL. This is
not always present in all URLs.
Example
Listing 8.300 shows how to obtain the port number if available. When the button is
clicked, the port number for the link is displayed.
<body>
Click the button to see the port number for the URL
<form name=”form1”>
<a href=”http://www.samspublishing.com:80/foo?something#foobar”>
http://www.samspublishing.com:80/foo?something#foobar</a>
<br><br>
Port value: <input type=”text” name=”text1” size=”20”>
<br><br>
<input type=”button” name=”port” value=”Get Port Number” onClick=’showport()’>
<br>
</form>
</body>
</html>
Link.protocol
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
link.protocol
Description
The protocol property of the Link object represents the protocol being used in the cur-
rent Web browser. This is the first piece of text in the URL.
15 0672321416 CH08b 7/24/01 12:22 PM Page 880
Example
Listing 8.301 shows how you can get the protocol type being used. When the button
is clicked, the protocol for the link is displayed.
<body>
Click the button to see the protocol used for the URL
<form name=”form1”>
<a href=”http://www.samspublishing.com:80/foo?something#foobar”>
http://www.samspublishing.com:80/foo?something#foobar</a>
<br><br>
Protocol value: <input type=”text” name=”text1” size=”20”>
<br><br>
<input type=”button” name=”proto” value=”Get Protocol” onClick=’showproto()’>
<br>
</form>
</body>
</html>
Link.search
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
link.search
Description
The search property of the Link object represents the query portion of the URL (if
available). This includes the leading question mark (?).
Example
Listing 8.302 shows how the search property can be determined. When the button is
clicked, the showsearch() function displays the search value of the link.
15 0672321416 CH08b 7/24/01 12:22 PM Page 881
Client-Side 881
<body>
</body>
</html>
Link.target
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
link.target
Description
The target property of the Link object represents the name of the window in which
the URL is to be displayed.
Example
Listing 8.303 shows how the target property is used. When the button is clicked, the
showtarget() function displays the target value of the link.
15 0672321416 CH08b 7/24/01 12:22 PM Page 882
<body>
// displays the name of the window in which the link will be displayed.
function showtarget(){
document.form1.text1.value = document.links[0].target;
}
// -->
</script>
</body>
</html>
Link.text
JavaScript 1.2+
Nav4+
Syntax
link.text
Description
The text property of the Link object is used to get the text value of the link.
Example
Listing 8.304 shows how to use the text property. When the button is clicked, the
showtext function displays the text value of the link.
<body>
15 0672321416 CH08b 7/24/01 12:22 PM Page 883
Client-Side 883
</body>
</html>
Link.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
link.unwatch(prop)
Description
The unwatch() method of the Link object will remove a watchpoint on a property,
prop, set by the watch() method.
Example
Listing 8.305 shows how the unwatch() method is used to disable the alert when the
href property has been changed.
Listing 8.305 Using the unwatch() Method for the Link Object
<html>
<script type=”text/javascript” a language=”JavaScript”>
<!--
function alertme(id,oldValue,newValue)
{
15 0672321416 CH08b 7/24/01 12:22 PM Page 884
myLink = document.links.href;
watch(“myLink”,alertme);
myLink = “http://www.bmw.com”;
unwatch(“myLink”);
myLink = “http://www.amazon.com”;
watch(“myLink”,alertme);
myLink = “http://www.buy.com”;
// -->
</script>
<body>
<form name=”form1”>
<a href=”http://www.samspublishing.com:80/foo?something#foobar”>
➥Link to Something</a>
</form>
</body>
</html>
Link.watch()
JavaScript 1.2+
Nav4+
Syntax
watch(prop, handler)
Description
The watch() method of the Link object is used to watch for changes to Link proper-
ties. When one of the properties, prop, is assigned a value, a handler is used to call a
user-defined function.
Example
Listing 8.306 shows how the watch() method is used to determine when the href prop-
erty of the link has changed.
Client-Side 885
<!--
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue + “</b>”+ “ to “ +
➥”<b>” + newValue + “</b><br>”)
return newValue;
}
myLink = document.links.href;
watch(“myLink”,alertme);
myLink = “http://www.bmw.com”;
myLink = “http://www.amazon.com”;
// -->
</script>
<body>
<form name=”form1”>
<a href=”http://www.samspublishing.com:80/foo?something#foobar”>
➥Link to Something</a>
</form>
</body>
</html>
Location
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Location object represents the current Web address displayed in the browser. The
Location object has specific properties and methods associated with it, as shown in
Table 8.21.
Example
Listing 8.307 shows how to access the Location object.
<body>
<form name=”form1”>
Click the button to get the current location value.
<br><br><br>
<input type=”button” name=”getLoc” value=”Get Location”
onClick=’alert(“The current location is: “ + document.location)’>
<br>
</form>
</body>
</html>
Location.hash
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
location.hash
Description
The hash property of the Location object refers to the anchor portion of the URL,
including the hash symbol (#).
15 0672321416 CH08b 7/24/01 12:22 PM Page 887
Client-Side 887
Example
Listing 8.308 shows an example of how to get the hash value.
<body>
<form name=”form1”>
Click the button to get the current location.hash
➥value of the following address:
<br>
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
Location.hash value: <input type=”text” name=”text1” size=”20”>
<br>
<input type=”button” name=”getLoc”
➥ value=”Get hash value” onClick=’show()’>
<br>
</form>
</body>
</html>
Location.host
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
location.host
15 0672321416 CH08b 7/24/01 12:22 PM Page 888
Description
The host property of the Location object represents the host portion of the URL.This
is composed of the hostname and the port number (if available).
In the following fictitious Web address:
http://www.samspublishing.com:80/foo?something#foobar
Example
Listing 8.309 shows the how the host property is used.
<body>
<form name=”form1”>
Click the button to get the current location.host value of
the following address:
<br>
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
Location.host value: <input type=”text” name=”text1” size=20>
<br>
<input type=”button” name=”getLoc” value=”Get host” onClick=’show()’>
<br>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 889
Client-Side 889
Location.hostname
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
location.hostname
Description
The hostname property of the Location object represents the hostname portion of the
URL.
In the following fictitious Web address:
http://www.samspublishing.com:80/foo?something#foobar
Example
Listing 8.310 shows an example of how the hostname property is used. When the but-
ton is clicked, the show() function is called, which displays the value of hostname in
the text box.
<body>
<form name=”form1”>
Click the button to get the current location.hostname
➥value of the following address:
<br>
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
Location.hostname value: <input type=”text” name=”text1” size=”20”>
<br>
<input type=”button” name=”gethost”
➥value=”Get hostname” onClick=’show()’>
15 0672321416 CH08b 7/24/01 12:22 PM Page 890
</body>
</html>
Location.href
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
location.href
Description
The href property of the Location object represents the entire URL string for the cur-
rent page displayed in the browser.
In the following fictitious Web address:
http://www.samspublishing.com:80/foo?something#foobar
Example
An example of how to get the href value is shown in Listing 8.311.
<body>
<form name=”form1”>
Click the button to set the current location.href
➥value of the following address:
<br>
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 891
Client-Side 891
</body>
</html>
Location.pathname
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
location.pathname
Description
The pathname property of the Location object represents the pathname portion of the
URL.
In the following fictitious Web address:
http://www.samspublishing.com:80/foo?something#foobar
Example
Listing 8.312 shows an example of how to get the pathname.
<body>
<form name=”form1”>
Click the button to get the current location.pathname
➥value of the following address:
15 0672321416 CH08b 7/24/01 12:22 PM Page 892
</body>
</html>
Location.port
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
location.port
Description
The port property of the Location object represents the port portion of the URL. This
normally follows the hostname, but is not always available.
In the following fictitious Web address:
http://www.samspublishing.com:80/foo?something#foobar
Example
Listing 8.313 shows how to get the port number.
<body>
Client-Side 893
<form name=”form1”>
Click the button to get the current location.port
➥value of the following address:
<br>
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
Location.port value: <input type=”text” name=”text1” size=”20”>
<br>
<input type=”button” name=”getport” value=”Get port”
➥onClick=’show()’>
<br>
</form>
</body>
</html>
Location.protocol
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
location.protocol
Description
The protocol property of the Location object represents the protocol portion of the
URL. This is located in the beginning of the URL address (the text before ://).
In the following fictitious Web address:
http://www.samspublishing.com:80/foo?something#foobar
Example
The protocol property is used in Listing 8.314.
<body>
<form name=”form1”>
Click the button to get the current location.protocol
➥value of the following address:
<br>
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
Location.protocol value: <input type=”text” name=”text1” size=”20”>
<br>
<input type=”button” name=”getproto” value=”Get protocol”
➥onClick=’show()’>
<br>
</form>
</body>
</html>
Location.reload()
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera3+
Syntax
location.reload()
Description
The reload() method is used to reload the current page displayed in the browser.
Example
Listing 8.315 shows an example of how the reload() method is used.
<body>
<form name=”form1”>
Click the button to reload the current page.
<br><br>
Location.hash value: <input type=”text” name=”text1” size=”20”>
<br>
<input type=”button” name=”load” value=”Reload page”
➥ onClick=’document.location.reload()’>
<br>
</form>
15 0672321416 CH08b 7/24/01 12:22 PM Page 895
Client-Side 895
</body>
</html>
Location.replace()
JavaScript 1.1+, JScript 3.0+
Nav3+, IE4+, Opera3+
Syntax
location.replace(URL)
Description
The replace() method is used to load a new page, specified by URL, in the current
browser window. The new page replaces the previous page’s position in the history list.
Example
Listing 8.316 shows the replace() method being used to load the new Web site.
<body>
<form name=”form1”>
Click the button to load the new page: http://www.samspublishing.com
<br>
<br>
<input type=”button” name=”load” value=”Load new page”
onClick=’document.location.replace(“http://www.samspublishing.com”)’>
<br>
</form>
</body>
</html>
Location.search
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
location.search
Description
The search property of the Location object represents the query portion of the URL,
including the preceding question mark.
15 0672321416 CH08b 7/24/01 12:22 PM Page 896
Example
Listing 8.317 shows how to use the search property. When the button is clicked, the
show function displays the value of the search property in the text box.
<body>
<form name=”form1”>
Click the button to get the current location.search
➥value of the following address:
<br>
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
Location.search value: <input type=”text” name=”text1” size=”20”>
<br>
<input type=”button” name=”getsearch” value=”Get search”
➥onClick=’show()’>
<br>
</form>
</body>
</html>
Location.unwatch()
JavaScript 1.2+
Nav4+
Syntax
location.unwatch(prop)
15 0672321416 CH08b 7/24/01 12:22 PM Page 897
Client-Side 897
Description
The unwatch() method of the Location object is used to remove a watchpoint set on
a property by the watch() method. It takes one parameter, which is the property to
unwatch.
Example
Listing 8.318 shows how the unwatch() method is used to disable the watchpoint on
the location host property.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue
➥ + “</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.location.host;
watch(“myProp”,alertme);
myProp = “amazon”;
unwatch(“myProp”);
myProp = “google”;
}
// -->
</script>
<body>
<form name=”form1”>
Click the button to get the current location.host
value of the following address:
<br>
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
Location.host value: <input type=”text” name=”text1” size=”20”>
<br>
<input type=”button” name=”gethost” value=”set watch” onClick=’setWatch()’>
<br>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 898
Location.watch()
JavaScript 1.2+
Nav4+
Syntax
watch(prop, handler)
Description
The watch() method of the Location object is used to watch for changes to Location
properties. When one of the properties, prop, is assigned a value, a handler is used to
call a user-defined function.
Example
Listing 8.319 shows how the watch() method is used to determine when the port value
has been altered.
origPort = document.location.port;
newPort = document.form1.myNewPort.value;
watch( origPort, informChange(newPort) );
origPort = newPort;
// -->
</script>
</head>
<body>
<form name=”form1”>
Click the button to get the current location.port
value of the following address:
<br>
15 0672321416 CH08b 7/24/01 12:22 PM Page 899
Client-Side 899
http://www.samspublishing.com:80/foo?something#foobar
<br><br>
Enter New Location.port value: <input type=”text” name=”myNewPort” size=”20”>
<br>
<input type=”button” name=”port” value=”Change port” onClick=’changeValue()’>
<br>
</form>
</body>
</html>
MimeType
JavaScript 1.1+
Nav3+
Syntax
Core client-side JavaScript object.
Description
The MimeType object is a predefined JavaScript object that you access through the
mimeTypes array of the Navigator or Plugin object. MIME stands for multipart
Internet mail extensions. Table 8.22 shows the different methods and properties of the
MimeType object.
Example
Listing 8.320 shows an example of accessing a MimeType though the mimeTypes array.
It prints out a few mimeTypes to the browser window.
<body>
<script type=”text/javascript” language=”JavaScript”>
<!--
15 0672321416 CH08b 7/24/01 12:22 PM Page 900
</body>
</html>
MimeType.description
JavaScript 1.1+
Nav3+
Syntax
mimetype.description
Description
The description property of the MimeType object is used to obtain a description of the
data type described by the MimeType object.
Example
Listing 8.321 shows an example of how the description property is used. A for loop
is used to output the suffixes of the first three MimeTypes.
<body>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 901
Client-Side 901
MimeType.enabledPlugin
JavaScript 1.1+
Nav3+
Syntax
mimetype.enabledPlugin
Description
The enabledPlugin property of the MimeType object is used to determine which plug-
in is configured for a specific MIME type.
Example
Listing 8.322 shows how the enabledPlugin property is used. A for loop is used to
output the first three enabledPlugin values.
<body>
</body>
</html>
MimeType.suffixes
JavaScript 1.1+
Nav3+
Syntax
mimetype.suffixes
Description
Thesuffixes property of the MimeType object is used to obtain a string listing the pos-
sible file suffixes or filename extensions for the MIME type.
15 0672321416 CH08b 7/24/01 12:22 PM Page 902
Example
Listing 8.323 shows an example of how the suffixes property is used. A for loop is
used to output the first three suffix values.
<body>
</body>
</html>
MimeType.type
JavaScript 1.1+
Nav3+
Syntax
mimetype.type
Description
The type property of the MimeType object is used to obtain a string specifying the name
of the MIME type.
Example
Listing 8.324 shows how the type property is used. A for loop is used to output the
first three MIME types.
<body>
Client-Side 903
</body>
</html>
MimeType.unwatch()
JavaScript 1.2+
Nav4+
Syntax
unwatch(prop)
Description
The unwatch() method of the MimeType object is used to remove a watchpoint on a
property set by the watch() method. It takes a single parameter, prop, which specifies
the property on which to remove the watchpoint.
Example
All MimeType properties are read-only, hence no example is provided.
MimeType.watch()
JavaScript 1.2+
Nav4+
Syntax
watch(prop, handler)
Description
The watch() method of the MimeType object is used to watch for changes to MimeType
properties. When one of the properties, prop, is assigned a value, a handler is used to
call a user-defined function.
Example
All MimeType properties are read-only, hence no example is provided.
15 0672321416 CH08b 7/24/01 12:22 PM Page 904
navigator
JavaScript 1.0+
Nav2+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The navigator object is a built-in object that is used to obtain information related to
the Navigator browser. Table 8.23 shows the different methods and properties of the
navigator object.
Example
Listing 8.325 shows an example for the navigator object.
15 0672321416 CH08b 7/24/01 12:22 PM Page 905
Client-Side 905
<body>
</body>
</html>
navigator.appCodeName
JavaScript 1.0+
Nav2+, Opera3+
Syntax
navigator.appCodeName
Description
The appCodeName property of the navigator object refers to the internal code name of
the browser.
Example
Listing 8.326 shows an example of how the appCodeName property is used.
<body>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 906
navigator.appName
JavaScript 1.0+
Nav2+, Opera3+
Syntax
navigator.appName
Description
The appName property of the navigator object refers to the browser name.
Example
Listing 8.327 shows an example of how the appName property is used.
<body>
</body>
</html>
navigator.appVersion
JavaScript 1.0+
Nav2+, Opera3+
Syntax
navigator.appVersion
Description
The appVersion property of the navigator object is used to get the browser version.
The returned property contains the browser version, platform on which the browser is
running, and the country (either international or domestic).
Example
Listing 8.328 shows an example of how the appVersion property is used.
15 0672321416 CH08b 7/24/01 12:22 PM Page 907
Client-Side 907
<body>
</body>
</html>
navigator.javaEnabled()
JavaScript 1.1+
Nav3+, Opera3+
Syntax
navigator.javaEnabled()
Description
The javaEnabled() method is used to test whether the browser supports Java.
Example
Listing 8.329 shows an example of how the javaEnabled() method is used. A check
is made to determine whether Java is enabled on the browser. If so, a message is out-
put indicating that to be the case.
<body>
</body>
</html>
navigator.language
JavaScript 1.2+
Nav4+
Syntax
navigator.language
Description
The language property of the navigator object is used to determine what language the
browser supports. The return value is a string.
Example
Listing 8.330 shows an example of how the language property is used.
<body>
</body>
</html>
navigator.mimeTypes
JavaScript 1.1+
Nav3+, Opera3+
Syntax
navigator.mimeTypes
15 0672321416 CH08b 7/24/01 12:22 PM Page 909
Client-Side 909
Description
The mimeTypes property of the navigator object is used to obtain a list of all the
MIME types supported by the browser. The returned object is an array containing all
supported MIME types. The mimetypes array contains all the properties of the Array
object.
Example
Listing 8.331 shows an example of how the mimeTypes property is used.
<body>
</body>
</html>
navigator.platform
JavaScript 1.2+
Nav4+
Syntax
navigator.platform
Description
The platform property of the navigator object returns a string representing the plat-
form on which the browser is running. Valid platform values are: Win32, Win16, Mac68k,
MacPPCa.
Example
Listing 8.332 shows an example of how the platform property is used.
<body>
15 0672321416 CH08b 7/24/01 12:22 PM Page 910
</body>
</html>
navigator.plugins
JavaScript 1.1+
Nav3+
Syntax
navigator.plugins[num]
Description
The plugins property of the navigator object returns an array of the Plugins object
representing all the plug-ins installed on a particular browser. These can be accessed
by the indexed num passed.
Example
Listing 8.333 shows an example of how the plugins property is used. A loop is used
to output a list of all the plug-ins for the browser.
<body>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 911
Client-Side 911
navigator.plugins.refresh()
JavaScript 1.1+
Nav3+
Syntax
navigator.plugins.refresh()
Description
The plugins.refresh() method of the navigator object is used to check for any new
plug-ins installed on the browser.
Example
Listing 8.334 shows an example of how the plugins.refresh() method is used. When
the document is loaded, the plugins.refresh() method.
<body>
</body>
</html>
navigator.preference()
JavaScript 1.2+
Nav4+, Opera3+
Syntax
navigator.preference(name)
navigator.preference(name, value)
Description
The preference()method of the navigator object is used to read or set any user pref-
erences in the browser. For security reasons, reading a preference with the
preference() method requires the UniversalPreferencesRead privilege. Setting a
preference with this method requires the UniversalPreferencesWrite privilege.
15 0672321416 CH08b 7/24/01 12:22 PM Page 912
Example
Listing 8.335 shows an example of how the preference() method can be used to set
a preference.
<body>
</body>
</html>
navigator.taintEnabled()
JavaScript 1.1+
Nav3
Syntax
navigator.taintEnabled()
Description
The taintEnabled() method of the navigator specifies whether data tainting is
enabled.
NOTE
This method is removed in Navigator 4 and later releases.
Example
Listing 8.336 shows an example of how the taintEnabled() method is used.
<body>
Client-Side 913
</body>
</html>
navigator.userAgent
JavaScript 1.0+
Nav2+, Opera3+
Syntax
navigator.userAgent
Description
The userAgent property of the navigator object returns a string identifying the
browser. This value is often sent to servers during HTTP data requests.
Example
Listing 8.337 shows an example of how the userAgent property is used.
<body>
document.write(navigator.userAgent);
// -->
</script>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 914
navigator.unwatch()
JavaScript 1.2+
Nav4+
Syntax
unwatch(prop)
Description
The unwatch() method of the navigator object is used to remove a watchpoint on a
property set by the watch() method. It takes a single parameter, prop, which specifies
the property on which to remove the watchpoint.
Example
All navigator properties are read-only, hence no example is provided.
navigator.watch()
JavaScript 1.2+
Nav4+
Syntax
watch(prop, handler)
Description
The watch() method of the navigator object is used to watch for changes to naviga-
tor properties. When one of the properties, prop, is assigned a value, a handler is used
to call a user-defined function.
Example
All navigator properties are read-only, hence no example is provided.
Option
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
Core client-side JavaScript object.
Description
The Option object is used to reference a property of an HTML select list. An Option
object can be created by using the option constructor and specifying the appropriate
values. Table 8.24 shows the different properties and methods of the Option object.
15 0672321416 CH08b 7/24/01 12:22 PM Page 915
Client-Side 915
Example
Listing 8.338 shows an example of how a select list is populated.
<body>
<script
<script type=”text/javascript” language=”JavaScript”>
<!--
// function adds the options to the select list.
function add(myForm) {
history.go(0)
}
// -->
</script>
<form>
<select name=”people” multiple></select><p>
<input type=”button” value=”Add People” onClick=”add(this.form)”>
</form>
</body></html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 916
Option.defaultSelected
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+
Syntax
option.defaultSelected
Description
The defaultSelected property of the Option object specifies the initial option selec-
tion of the select list.
Example
Listing 8.339 shows an example of how the defaultSelected property is used. The
check function checks for the default selected option.
<body>
<form name=form1>
<select name=”myList” multiple>
<option value=1>One
<option value=2 selected>Two
<option value=3>Three
<option value=4>Four
</select><p>
<input type=”button” value=”Get Default Value” onClick=’check(this.form)’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 917
Client-Side 917
Option.selected
JavaScript 1.2+
Nav4+
Syntax
option.selected
Description
The selected property of the Option object specifies the current selected option of the
select list.
Example
Listing 8.340 shows an example of how the selected property is used. The check
function checks to see what the selected property is.
<body>
<form name=form1>
<select name=”myList” multiple>
<option value=1>One
<option value=2>Two
<option value=3>Three
<option value=4>Four
</select><p>
<input type=”button” value=”Get Value” onClick=’check(this.form)’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 918
Option.text
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
option.text
Description
The text property of the Option object specifies the text for the selected option of the
select list.
Example
Listing 8.341 shows an example of how the text property is used. The check function
determines what the text is for the selected value.
<body>
<form name=form1>
<select name=”myList” multiple>
<option value=1>One
<option value=2>Two
<option value=3>Three
<option value=4>Four
</select><p>
<input type=”button” value=”Get Text Value” onClick=’check(this.form)’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:22 PM Page 919
Client-Side 919
Option.unwatch()
JavaScript 1.2+
Nav4+
Syntax
option.unwatch(prop)
Description
The unwatch() method of the Option object will remove a watchpoint on a property,
prop, set by the watch() method.
Example
Listing 8.342 shows how the unwatch() method is used to remove the watchpoint set
on the Option value. When the submit button is clicked, the setWatch() method is
called, which sets the watchpoint and then changes the Option value. This causes the
alertme function to be executed, which displays the results of the change to the
browser.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.form.myList.value;
watch(“myProp”,alertme);
myProp = 6;
myProp = 9;
}
// -->
</script>
<body>
<form name=”form”>
<select name=”myList” multiple>
<option value=1>One
<option value=2 selected>Two
15 0672321416 CH08b 7/24/01 12:23 PM Page 920
</body>
</html>
Option.value
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
option.value
Description
The value property of the Option object specifies the value that is returned to the
server when the option is selected and the form is submitted.
Example
Listing 8.343 shows an example of how the value property is used. The function
getValue gets the value of the selected option.
<body>
<script
<script type=”text/javascript” language=”JavaScript”>
<!--
// Function gets the value of the selected option
function getValue(myForm){
for (var i = 0; i < document.form1.myList.length; i++) {
if (document.form1.myList.options[i].selected == true) {
alert(“The selected value is: “
➥+ document.form1.myList.options[i].value);
}
}
}
// -->
</script>
15 0672321416 CH08b 7/24/01 12:23 PM Page 921
Client-Side 921
<form name=”form1”>
<select name=”myList” multiple>
<option value=1>One
<option value=2>Two
<option value=3>Three
<option value=4>Four
</select><p>
<input type=”button” value=”Get Value” onClick=’getValue(this.form)’>
</form>
</body>
</html>
Option.watch()
JavaScript 1.2+
Nav4+
Syntax
watch(prop, handler)
Description
The watch() method of the Option object is used to watch for changes to Option prop-
erties. When one of the properties, prop, is assigned a value, a handler is used to call
a user-defined function.
Example
Listing 8.344 shows how the watch() method is used to monitor when the value prop-
erty of the Option object is modified.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myProp = document.form.myList.value;
watch(“myProp”,alertme);
15 0672321416 CH08b 7/24/01 12:23 PM Page 922
</head>
<body>
<form name=”form”>
<select name=”myList” multiple>
<option value=1>One
<option value=2 selected>Two
<option value=3>Three
</select>
<br>
Password
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Password object refers to the HTML element created with the <input> tag, setting
the type to specify password. It operates similarly to a standard HTML text input box
because input is entered into the box. Instead of displaying the input in cleartext,
input is displayed using the * symbol. Table 8.25 shows the different methods and
properties of the Password object.
Client-Side 923
Example
Listing 8.345 shows an example of how the Password object is used to read the value
entered in a password box.
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Show Password”
➥ onClick=’alert(document.form1.pass.value)’>
</form>
</body>
</html>
Password.blur()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
password.blur()
Description
The blur method for the Password object is used to remove the focus from the pass-
word box.
Example
Listing 8.346 shows an example of how the focus is removed from the password box.
15 0672321416 CH08b 7/24/01 12:23 PM Page 924
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”Text” name=”txt” size=”10”>
<br>
<input type=”BUTTON” value=”Show Password” onClick=’shift()’>
</form>
</body>
</html>
Password.defaultValue
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+
Syntax
password.defaultValue
Description
The defaultValue property of the Password object is used to get the HTML value
attribute of the password box.
Example
Listing 8.347 shows an example of how the defaultValue is used to get the password
value.
<body>
<form name=”form1”>
15 0672321416 CH08b 7/24/01 12:23 PM Page 925
Client-Side 925
</body>
</html>
Password.focus()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
password.focus()
Description
The focus() method of the Password object sets the focus to the password box.
Example
Listing 8.348 shows an example of how the focus() method is used to move the focus
back to the password box.
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Show Password”
➥ onClick=’document.form1.pass.focus()’>
</form>
</body>
</html>
Password.form
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
password.form
15 0672321416 CH08b 7/24/01 12:23 PM Page 926
Description
The form property of the Password object is used to access the Form object in which
the password box resides.
Example
Listing 8.349 shows an example of how the form property is used to get the form name.
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Show Formname”
➥ onClick=’alert(document.form1.pass.form.name)’>
</form>
</body>
</html>
Password.handleEvent()
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+, Opera3+
Syntax
password.handleEvent(event)
Description
The handleEvent() method of the Password object is used to handle events of the type
of event passed.
Example
Listing 8.350 shows an example of how the handleEvent() method is used to handle
the Click event when the button is clicked.
<body>
Client-Side 927
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleChange(evnt){
window.document.pass.handleEvent(evnt);
}
function showMsg(){
alert(“Password Changed.”);
}
// This registers the handle function as the event handler for the
// CHANGE event.
document.onChange = handleChange;
// -->
</script>
<form name=”form1”>
Enter password:
<input type=”PASSWORD” name=”pass” size=”15” onChange=’showMsg()’>
</form>
</body>
</html>
Password.name
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
password.name
Description
The name property of the Password object is used to get the HTML name attribute of
the password box.
Example
Listing 8.351 shows an example of how the name property is used. When the button is
clicked, an alert box is displayed showing the password object name.
15 0672321416 CH08b 7/24/01 12:23 PM Page 928
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Show Formname”
➥ onClick=’alert(document.form1.pass.name)’>
</form>
</body>
</html>
Password.onBlur
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onBlur=”command”
Description
The onBlur event handler of the Password object is used to handle the event that occurs
when the focus is removed from the password box.
Example
Listing 8.352 shows an example of how the onBlur event handler is used. When the
focus is removed from the Password object, the setTxt() function is called to display
a message in the text box.
<body>
Client-Side 929
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10” onBlur=’setTxt()’>
<br>
<input type=”Text” name=”txt” size=”10” >
</form>
</body>
</html>
Password.onFocus
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onFocus=”command”
Description
The onFocus event handler of the Password object is used to handle the Focus event
for the password box.
Example
Listing 8.353 shows an example of the onFocus event handler.
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10” onFocus=’set()’>
<br>
<input type=”BUTTON” value=”Show Formname” >
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 930
Password.select()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
password.select()
Description
The select() method of the Password object is used to select the value entered into
the password box. The selected value is highlighted.
Example
Listing 8.354 shows an example of how the password value can be selected.
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Select Password”
➥onClick=’document.form1.pass.select()’>
</form>
</body>
</html>
Password.type
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
password.type
Description
The type property of the Password object is used to get the HTML type attribute asso-
ciated with the password box. For the Password object, this value is always password.
Example
Listing 8.355 shows an example of how the type property is used. When the button is
clicked, an alert box is displayed, showing the value of the type property.
15 0672321416 CH08b 7/24/01 12:23 PM Page 931
Client-Side 931
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Get Type”
➥ onClick=’alert(document.form1.pass.type)’>
</form>
</body>
</html>
Password.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
password.unwatch(prop)
Description
The unwatch() method of the Password object will remove a watchpoint on a property,
prop, set by the watch() method.
Example
Listing 8.356 shows how the unwatch() method is used to turn off the watchpoint set
on the Password value.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myPass = document.form1.pass.value;
watch(“myPass”,alertme);
myPass = “abc123”;
15 0672321416 CH08b 7/24/01 12:23 PM Page 932
// -->
</script>
<form name=”form1”>
Enter Password <input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Submit” onClick=’setWatch()’>
</form>
</body>
</html>
Password.value
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
password.value
Description
The value property of the Password object is used to get the value entered in the pass-
word box.
Example
Listing 8.357 shows an example of how the value property is used.
<body>
<form name=”form1”>
<input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Get Value”
➥ onClick=’alert(document.form1.pass.value)’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 933
Client-Side 933
Password.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
watch(prop, handler)
Description
The watch() method of the Password object is used to watch for changes to Password
properties. When one of the properties, prop, is assigned a value, a handler is used to
call a user-defined function.
Example
Listing 8.358 shows how the watch() method is used to inform the user that the pass-
word value has changed within the changeValue() function.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue + “</b>”+
➥” to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myPass = document.form1.pass.value;
watch(“myPass”,alertme);
myPass = “abc123”;
}
// -->
</script>
<form name=”form1”>
Enter Password <input type=”PASSWORD” Name=”pass” size=”10”>
<br>
<input type=”BUTTON” value=”Submit” onClick=’setWatch()’>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 934
Plugin
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Plugin object is used to obtain plug-in information from the browser. The Plugin
object contains an array of elements containing the MIME types handled by each plug-
in. Table 8.26 shows the different properties and methods of the Plugin object.
Example
Listing 8.359 shows an example in which all the browser’s plug-ins are printed to the
document.
<body>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 935
Client-Side 935
Plugin.description
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
plugin.description
Description
The description property of the Plugin object is used to obtain a description of the
browser plug-ins.
Example
Listing 8.360 shows an example of how the description property is used.
<body>
// -->
</script>
</body>
</html> >
Plugin.filename
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
plugin.filename
Description
The filename property of the Plugin object is used to get the path and filename for a
plug-in.
Example
Listing 8.361 shows an example of how the filename property is used.
15 0672321416 CH08b 7/24/01 12:23 PM Page 936
<body>
// -->
</script>
</body>
</html>
Plugin.length
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
plugin.length
Description
The length property of the Plugin object determines the number of MIME data types
the plug-in can support.
Example
Listing 8.362 shows an example of how the length property is used.
<body>
// -->
</script>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 937
Client-Side 937
Plugin.name
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
plugin.name
Description
The name property of the Plugin object is used to get the plug-in’s name.
Example
Listing 8.363 shows an example of how the name property is used.
<body>
// -->
</script>
</body>
</html>
Plugin.unwatch()
JavaScript 1.2+
Nav4+
Syntax
unwatch(prop)
Description
The unwatch() method of the Plugin object is used to disable a watch on a Plugin
property. Specify the property, prop, to disable.
Example
All Plugin properties are read-only, hence no example is provided.
15 0672321416 CH08b 7/24/01 12:23 PM Page 938
Plugin.watch()
JavaScript 1.2+
Nav4+
Syntax
watch(prop, handler)
Description
The watch() method of the Plugin object is used to watch for changes to Plugin prop-
erties. When one of the properties, prop, is assigned a value, a handler is used to call
a user-defined function.
Example
All Plugin properties are read-only, hence no example is provided.
Radio
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Radio object represents a check box within an HTML form. A check box is
created using the HTML <input> tag and specifying the type attribute as radio.
The Radio object has specific properties and methods associated with it, as shown in
Table 8.27.
Client-Side 939
Example
Listing 8.364 shows how a check box is created and then how the name property is
accessed using the Radio object.
<body>
<form name=”form1”>
<input type=”radio” name=button1
➥onClick=’alert(document.form1.button1.name)’>Box 1
<br>
<input type=”radio” name=”button2”>Box 2
<br>
</form>
</body>
</html>
Radio.blur()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.blur()
Description
The blur() method of the Radio object is used to remove the focus from the check
box.
15 0672321416 CH08b 7/24/01 12:23 PM Page 940
Example
Listing 8.365 shows how the blur() method is used to remove focus from the radio
button. When the Remove Focus button is clicked, the focus is removed from the radio
button and a text message is displayed.
<body>
<form name=”form1”>
<input type=”radio” name=”button1” CHECKED>Box 1
<br>
<input type=”radio” name=”button2”>Box 2
<br>
<input type=”button” value=”Remove Focus” onClick=’change()’>
<br>
<input type=”text” name=”text1” size=”15”>
</form>
</body>
</html>
Radio.checked
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.checked
Description
The checked property of the Radio object is a boolean value used to determine whether
a radio button is in a checked or unchecked state.
15 0672321416 CH08b 7/24/01 12:23 PM Page 941
Client-Side 941
Example
Listing 8.366 shows an example of how to determine whether the radio button is
checked by using the checked property.
<body>
<form name=”form1”>
<input type=”radio” name=”button1”>Box 1
<br>
<input type=”radio” name=”button2” CHECKED>Box 2
<br>
< INPUT type=”button” value=”Get Checked” onClick=’checkButton()’>
</form>
</body>
</html>
Radio.click()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.click()
Description
The click() property of the Radio object is used to simulate a mouse click on the radio
button.
15 0672321416 CH08b 7/24/01 12:23 PM Page 942
Example
Listing 8.367 shows an example of how the click() property is used.
<body>
</body>
</html>
Radio.defaultChecked
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.defaultChecked
Description
The defaultChecked property of the Radio object is a boolean value that reports which
radio buttons contain the HTML checked attribute. If the checked attribute is contained
in the Radio object, true is returned. Otherwise, false is returned.
Example
Listing 8.368 shows how the defaultChecked property is used to find out which box
is checked by default.
<body>
Client-Side 943
if(document.form1.button1.defaultChecked == true){
alert(“Box1 is checked by default”);
}
else if(document.form1.button2.defaultChecked == true){
alert(“Box 2 is checked by default”);
}
}
// -->
</script>
<form name=”form1”>
<input type=”radio” name=”button1”>Box 1
<br>
<input type=”radio” name=”button2” CHECKED>Box 2
<br><br>
<input type=”button” value=”Get Default” onClick=’checkBox()’>
</form>
</body>
</html>
Radio.focus()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.focus()
Description
The focus() method of the Radio object sets the focus to the radio button.
Example
Listing 8.369 shows how the focus() method is used.
<body>
<form name=”form1”>
<input type=”radio” name=”button1”>Box 1
<br>
<input type=”radio” name=”button2”>Box 2
<br><br>
<input type=”button” value=”Set Focus to Box 1”
➥ onClick=’document.form1.button1.focus()’>
15 0672321416 CH08b 7/24/01 12:23 PM Page 944
</body>
</html>
Radio.form
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.form
Description
The form property of the Radio object is used to reference the Form object that contains
the Radio box.
Example
Listing 8.370 shows an example of how the form property can be used to get the name
of the form that contains the Radio object.
<body>
<form name=”form1”>
<input type=”radio” name=”button1”>Box 1
<br>
<input type=”radio” name=”button2”>Box 2
<br><br>
<input type=”button” value=”Get Form Name”
onClick=’alert(“The form name is: “ + document.form1.button1.form.name)’>
</form>
</body>
</html>
Radio.handleEvent()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.handleEvent(event)
15 0672321416 CH08b 7/24/01 12:23 PM Page 945
Client-Side 945
Description
The handleEvent() method of the Radio object invokes the event handler for the spe-
cific event.
Example
Listing 8.371 shows how the handleEvent() method is used to capture all CLICK
events and pass them to the but1 object event handler.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleClick(evnt){
window.document.but1.handleEvent(evnt);
}
function showMsg(){
alert(“Button clicked.”);
}
// This registers the handle function as the event handler for the
// CLICK event.
document.onClick = handleClick;
// -->
</script>
<form name=”form1”>
<input type=”radio” name=”but1” onClick=’showMsg()’>Choice 1
<br>
<input type=”radio” name=”but1” onClick=’showMsg()’>Choice 2
<br>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 946
Radio.name
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.name
Description
The name property of the Radio object represents the name attribute of the HTML
<input> tag that creates the Radio button. This allows you to reference a Radio object
directly by name.
Example
Listing 8.372 shows how the name of the Radio button is used to access its properties.
<body>
<form name=”form1”>
<input type=”radio” name=”myButton”>Box 1
<br><br>
<input type=”button” value=”Get Name”
➥onClick=’alert(“The name of the button is: “ +
document.form1.myButton.name)’>
</form>
</body>
</html>
Radio.onBlur
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onBlur=”command”
Description
The onBlur property is an event handler for the Radio object that notifies you when the
focus is removed from a radio button.
Example
Listing 8.373 shows how the onBlur event handler is used to detect when the focus is
removed from the specified radio button.
15 0672321416 CH08b 7/24/01 12:23 PM Page 947
Client-Side 947
<body>
<form name=”form1”>
Click the radio button first, then click in the text area.
<br><br>
<input type=”radio” name=”button1” onBlur=’showChange()’>Box 1
<br>
Click the text box
<input type=”text” name=”text1” size=”40”>
<br>
</form>
</body>
</html>
Radio.onClick
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onClick=”command”
Description
The onClick property of the Radio object is an event handler that notifies you when
the mouse has been clicked on the button.
Example
Listing 8.374 uses the onClick event handler to check for a mouse click event.
<body>
<form name=”form1”>
15 0672321416 CH08b 7/24/01 12:23 PM Page 948
</body>
</html>
Radio.onFocus()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onFocus=”command”
Description
The onFocus event handler of the Radio object is an event handler that notifies you
when the focus is set on the radio button.
Example
In Listing 8.375, the onFocus event handler notifies the user with a text message when
the focus is set on the radio button.
<body>
<form name=”form1”>
Click on the radio button
<br><br>
<input type=”radio” name=”button1” onFocus=’showFocus()’>Box 1
<br><br>
<input type=”text” name=”text1” size=”40”>
15 0672321416 CH08b 7/24/01 12:23 PM Page 949
Client-Side 949
</form>
</body>
</html>
Radio.type
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.type
Description
The type property of the Radio button represents the button’s type HTML attribute.
For this object, it is always radio.
Example
Listing 8.376 shows an example of the type property.
<body>
<form name=”form1”>
<input type=”radio” name=”button1”>Box 1
<br><br>
<input type=”button” value=”Get Button Type”
onClick=’alert(“The button type is: “ + document.form1.button1.type)’>
</form>
</body>
</html>
Radio.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
radio.unwatch(prop)
Description
The unwatch() method of the Radio object will remove a watchpoint on a property,
prop, set by the watch() method.
15 0672321416 CH08b 7/24/01 12:23 PM Page 950
Example
Listing 8.377 shows how the unwatch() method is used to turn off the watchpoint on
the myRadio object.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥ “</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myRadio = document.form1.button1.value;
watch(“myRadio”,alertme);
myRadio = 4;
unwatch(“myRadio”);
myRadio = 6;
}
// -->
</script>
<body>
<form name=”form1”>
<input type=”radio” name=”button1” value=”1”>Box 1
<br><br>
<input type=”button” value=”Get Button Value” onClick=’setWatch()’>
</form>
</body>
</html>
Radio.value
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
radio.value
Description
The value property of the Radio object represents the value attribute of the HTML
<input> tag used to create the radio button.
15 0672321416 CH08b 7/24/01 12:23 PM Page 951
Client-Side 951
Example
Listing 8.378 shows how to access the value property.
<body>
<form name=”form1”>
<input type=”radio” name=”button1” value=”1”>Box 1
<br><br>
<input type=”button” value=”Get Button Value”
onClick=’alert(“The button value is: “ + document.form1.button1.value)’>
</form>
</body>
</html>
Radio.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
radio.watch(prop, handler)
Description
The watch() method of the Radio object is used to watch for changes to Radio prop-
erties. When one of the properties, prop, is assigned a value, a handler is used to call
a user-defined function.
Example
Listing 8.379 shows how the watch() method is used to track when the value of the
Radio button has been changed.
Listing 8.379 Using the watch() Method on the Radio Value Property
<html>
<script type=”text/javascript” language=”JavaScript”>
<!--
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “a”)
return newValue;
}
15 0672321416 CH08b 7/24/01 12:23 PM Page 952
// -->
</script>
<body>
<form name=”form1”>
<input type=”radio” name=”button1” value=”1”>Box 1
<br><br>
<input type=”button” value=”Get Button Value” onClick=’setWatch()’>
</form>
</body>
</html>
Reset
JavaScript 1.2+, JScript 1.0+
Nav4+, IE3+
Syntax
Core client-side JavaScript object.
Description
The Reset object represents a Reset button within an HTML form. The button is cre-
ated using the HTML <input> tag and specifying the type attribute as reset. Reset
buttons are used for form submissions. The Reset object has specific properties and
methods associated with it, as shown in Table 8.28.
Client-Side 953
Example
Listing 8.380 shows the syntax for using the Reset object.
<body>
<form name=”form1”>
Click the Reset button to reset the form.
<br><br><br>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset”>
<br>
<br>
</form>
</body>
</html>
Reset.blur()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
reset.blur()
Description
The blur() method of the Reset object is used to remove the focus from the Reset
button.
Example
Listing 8.381 shows an example of how the blur() method is used.
15 0672321416 CH08b 7/24/01 12:23 PM Page 954
<body>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br>
Message: <input type=”text” Name=”msg” Size=”40”>
<br>
<input type=”reset” name=”resetbutton” value=”Reset” onBlur=’showMsg()’>
<br>
<br>
</form>
</body>
</html>
Reset.click()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
reset.click()
Description
The click() method of the Reset object is used to simulate a mouse click on the Reset
button.
Example
Listing 8.382 shows how the click() method is used.
15 0672321416 CH08b 7/24/01 12:23 PM Page 955
Client-Side 955
<body>
function inform(){
alert(“The Reset button was clicked”);
}
// -->
</script>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset” onClick=’inform()’>
<br>
<br>
<input type=”button” value=”Simulate Click” onClick=’clickReset()’>
</form>
</body>
</html>
Reset.focus()
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
reset.focus()
Description
The focus() method of the Reset object is used to set the focus to the Reset button.
Example
Listing 8.383 shows an example of how the focus() method is used.
15 0672321416 CH08b 7/24/01 12:23 PM Page 956
<body>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset”>
<br>
<br>
<input type=”button” value=”Set Focus to Reset” onClick=’focusReset()’>
<br>
</form>
</body>
</html>
Reset.form
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
reset.form
Description
The form property of the Reset object is used to obtain the name of the form that con-
tains the Reset button.
Example
Listing 8.384 shows an example of how to get the form name.
<body>
15 0672321416 CH08b 7/24/01 12:23 PM Page 957
Client-Side 957
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset”
onClick=’alert(“The form name is: “ + document.form1.resetbutton.form.name)’>
<br>
<br>
</form>
</body>
</html>
Reset.handleEvent()
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
reset.handleEvent(event)
Description
The handleEvent() method of the Reset object invokes the event handler for the
object.
Example
Listing 8.385 shows an example of how the handleEvent() method is used.
<body>
// function that handles the specific event. The evnt parameter refers to
// the event object.
function handleMyClick(evnt){
window.document.resetbutton.handleEvent(evnt);
}
15 0672321416 CH08b 7/24/01 12:23 PM Page 958
// This registers the handle function as the event handler for the
// CLICK event.
document.onClick = handleMyClick;
// -->
</script>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset” onClick=’showMsg()’>
<br>
<br>
</form>
</body>
</html>
Reset.name
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
reset.name
Description
The name property of the Reset object represents the name given to a Reset button as
specified from the name attribute of the HTML <input type=”reset”> tag.
Example
In Listing 8.386, the name property is used to inform the user of the active frame.
<body>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
15 0672321416 CH08b 7/24/01 12:23 PM Page 959
Client-Side 959
</body>
</html>
Reset.onBlur
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
onBlur=”command”
Description
The onBlur event handler for the Reset object is an event handler that specifies when
the focus has been removed from the Reset button.
Example
In Listing 8.387, the onBlur event handler is used.
<body>
<form name=”form1”>
Click the reset button and then click in a text area.
<br><br>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
15 0672321416 CH08b 7/24/01 12:23 PM Page 960
</body>
</html>
Reset.onClick
JavaScript 1.1+, JScript 1.0+
Nav3+, IE3+, Opera3+
Syntax
onClick=”command”
Description
The onClick property is an event handler used to handle the event of a mouse click on
the Reset button.
Example
Listing 8.388 shows an example of how the onClick event handler is used.
<body>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset”
➥onClick=’alert(“The reset button was clicked”)’>
<br>
<br>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 961
Client-Side 961
Reset.onFocus
JavaScript 1.2+, ECMAScript 1.0+, JScript 1.0+
Nav4+, IE3+
Syntax
onFocus=”command”
Description
The onFocus event handler is used to specify when the focus is set on the Reset button.
Example
Listing 8.389 shows the onFocus event handler being used to inform the user when the
focus is set.
<body>
<form name=”form1”>
Click the reset button.
<br><br>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset” onFocus=’setMsg()’>
<br>
</form>
<form name=”form2”>
<br><br>
Message: <input type=”text” name=”text1” size=”45”>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 962
Reset.type
JavaScript 1.2+, ECMAScript 1.0+
Nav4+
Syntax
reset.type
Description
The type property of the Reset object represents the HTML type attribute of the Reset
button. In the case of a Reset button, this will always be reset.
Example
Listing 8.390 shows how to get the Reset button type.
<body>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset”
onClick=’alert(“The button type is: “ + document.form1.resetbutton.type)’>
<br>
<br>
</form>
</body>
</html>
Reset.unwatch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
reset.unwatch(prop)
15 0672321416 CH08b 7/24/01 12:23 PM Page 963
Client-Side 963
Description
The unwatch() method of the Reset object is used to remove a watchpoint set on a
property by the watch() method. It takes one parameter, which is the property to
unwatch.
Example
Listing 8.391 shows how the unwatch() method to turn off the watch on the Reset
object value property.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myRes = document.form1.resetbutton.value;
watch(“myRes”,alertme);
myRes = “cat”;
unwatch(“myRes”);
myRes = “dog”;
}
// -->
</script>
<body>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
<input type=”reset” name=”resetbutton” value=”Reset” onClick=’setWatch()’>
<br>
<br>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 964
Reset.value
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
reset.value
Description
The value property of the Reset object represents the HTML value attribute of the
Reset button.
Example
Listing 8.392 shows how the Reset button value can be accessed.
<body>
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
Enter Phone: <input type=”text” Name=”phone” Size=”10”>
<br><br>
<input type=”reset” name=”resetbutton” value=”Reset”
onClick=’alert(“The button value is: “ + document.form1.resetbutton.value)’>
<br>
<br>
</form>
</body>
</html>
15 0672321416 CH08b 7/24/01 12:23 PM Page 965
Client-Side 965
Reset.watch()
JavaScript 1.2+
Nav4+, NES3+
Syntax
reset.watch(prop, handler)
Description
The watch() method of the Reset object is used to watch for changes to Reset prop-
erties. When one of the properties, prop, is assigned a value, a handler is used to call
a user-defined function.
Example
Listing 8.393 shows how the watch() method is used to watch for a change to the
Reset object value property. When the value is changed, the alertme function is
called.
function alertme(id,oldValue,newValue)
{
document.writeln(id + “ changed from “ + “<b>” + oldValue +
➥”</b>”+ “ to “ + “<b>” + newValue + “</b><br>”)
return newValue;
}
function setWatch(){
myRes = document.form1.resetbutton.value;
watch(“myRes”,alertme);
myRes = “cat”;
myRes = “dog”;
}
// -->
</script>
15 0672321416 CH08b 7/24/01 12:23 PM Page 966
<form name=”form1”>
Enter Name: <input type=”text” Name=”name” Size=”15”>
<br>
<input type=”reset” name=”resetbutton” value=”Reset” onClick=’setWatch()’>
<br>
<br>
</form>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:31 PM Page 967
Client-Side 967
screen
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
Core client-side JavaScript object.
Description
The screen object provides a programmer with access to various properties of the
user’s screen. These properties are often accessed and used for sizing windows that var-
ious scripts open. Table 8.29 shows the properties of the screen object. This object
only has two methods, watch() and unwatch(), which allow you to turn on and off a
watch for a particular property. See their respective entries for more information.
Example
Listing 8.394 has a button that, when clicked, opens a secondary window that displays
all the properties of the screen object.
screen.availHeight
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
screen.availHeight
Description
The availHeight property of the screen object accesses the available pixel height of
the user’s screen. This height is minus any toolbar or any other “permanent” objects
that might be on the user’s screen.
Example
Listing 8.395 displays the available height of the user’s screen to the page.
Client-Side 969
// -->
</script>
screen.availLeft
JavaScript1.2+
Nav4+
Syntax
screen.availLeft
Description
The availLeft property of the screen object specifies the first available x coordinate
pixel not allocated to any of the user’s toolbar or any other “permanent” objects that
may be on the screen.
NOTE
If you access this property in Netscape 6, it does not consider the My Sidebar as
part of the window—just the rendering portion window.
Example
Listing 8.396 displays the available left pixel of the user’s screen to the page.
// -->
</script>
screen.availTop
JavaScript1.2+
Nav4+
Syntax
screen.availTop
16 0672321416 CH08c 7/24/01 12:31 PM Page 970
Description
The availTop property of the screen object specifies the first available y coordinate
pixel not allocated to any of the user’s toolbar or any other “permanent” objects that
might be on the screen.
Example
Listing 8.397 displays the available top pixel of the user’s screen to the page.
// -->
</script>
screen.availWidth
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
screen.availWidth
Description
The availWidth property of the screen object accesses the available pixel width of the
user’s screen. This width is minus any toolbar or any other “permanent” objects that
may be on the user’s screen.
Example
Listing 8.398 displays the available width of the user’s screen to the page.
// -->
</script>
16 0672321416 CH08c 7/24/01 12:31 PM Page 971
Client-Side 971
screen.colorDepth
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
screen.colorDepth
Description
The colorDepth property of the screen object accesses the maximum number of col-
ors the user’s screen can display. The returned value is in terms of bits.
Example
Listing 8.399 displays the color depth of the user’s screen to the page.
// -->
</script>
screen.height
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
screen.height
Description
The height property of the screen object accesses the height of the user’s screen in
pixels.
Example
Listing 8.400 displays the height of the user’s screen to the page.
Screen.pixelDepth
JavaScript1.2+
Nav4+
Syntax
screen.pixelDepth
Description
The pixelDepth property of the screen object accesses the number of bits per pixel of
the user’s screen.
Example
Listing 8.401 displays the pixel depth of the user’s screen to the page.
// -->
</script>
screen.unwatch()
JavaScript 1.2+
Nav4+
Syntax
screen.unwatch(property)
Description
The unwatch() method of the screen object is used to turn off the watch for a partic-
ular property.
Example
Listing 8.402 shows how the unwatch() method is used to stop watching the height
property. If the screen.height property changes, such as in changing screen resolu-
tion, this function will be called.
16 0672321416 CH08c 7/24/01 12:31 PM Page 973
Client-Side 973
screen.watch(“height”,alertme);
screen.unwatch(“height”);
</script>
screen.watch()
JavaScript 1.2+
Nav4+
Syntax
screen.watch(property, function)
Description
The watch() method of the screen object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 8.403 shows how the watch() method is used to start watching the height
property. If the screen.height property changes, such as in changing screen resolu-
tion, this function will be called.
screen.watch(“height”,alertme);
</script>
16 0672321416 CH08c 7/24/01 12:31 PM Page 974
screen.width
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
screen.width
Description
The width property of the screen object accesses the width of the user’s screen in pix-
els.
Example
Listing 8.404 displays the width of the user’s screen to the page.
// -->
</script>
Select
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Select object is one of the core JavaScript objects. Instances are created by the
browser when it encounters an HTML <select> tag. In the JavaScript object hierarchy,
the Select object is located at window.document.Form.Select. Table 8.30 lists the
properties, methods, and event handlers used by the Select object.
Client-Side 975
Example
Listing 8.405 displays the use of the Select properties. It contains a select box and a
button. When the button is clicked, a second window is opened. The values of the prop-
erties of this Select object are displayed in this window.
// Place the reference to the select box in a variable for easier access.
var myInstance = document.myForm.mySelect;
16 0672321416 CH08c 7/24/01 12:31 PM Page 976
// Note that the entire form object is passed with this property.
// This allows you to then drill down and get the value of other
// components in the form.
myWin.document.write(“The form can be used to grab “);
myWin.document.write(“the value of the button: “);
myWin.document.write(myInstance.form.myButton.value);
Select.blur()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.blur()
16 0672321416 CH08c 7/24/01 12:31 PM Page 977
Client-Side 977
Description
The blur() method of the Select object removes focus from the select box. This does
not mean that the selected option is unselected, but rather, the focus on this option and
the select box as a whole are removed. Be careful when using this method in conjunc-
tion with the Select.focus() method. It can lead to a focus/blur loop, where the
browser blurs a focus as soon as it is done, and vice versa.
Example
Listing 8.406 has a multiple select box and a button. If the user selects any of the
options in the box and then clicks the Click Here to Remove Focus button, the option
and entire select box will no longer have focus.
Listing 8.406 Using the blur() Method to Remove Focus from the
Select Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Select.focus()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.focus()
Description
The focus() method of the Select object gives the focus to the select box. Be careful
when using this method in conjunction with the Select.blur() method. It can lead to
a focus/blur loop, where the browser blurs a focus as soon as it is done, and vice versa.
Example
Listing 8.407 has two text boxes and two buttons. If the user clicks the first button, the
cursor is set inside the first text box. If the user clicks the second text box, the cursor
is set inside the second text box.
Listing 8.407 Using the focus() Method to Place the Cursor in the
Desired Select Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Client-Side 979
</select>
<input type=”button” value=”Click to Set Cursor” name=”myButton1”
onclick=”setFocus(1)”>
<br>
<select name=”mySelect2” multiple>
<option value=”HOCK”>Hockey</option>
<option value=”RUG”>Rugby</option>
<option value=”GOLF”>Golf</option>
<option value=”TENNIS”>Tennis</option>
</select>
<input type=”button” value=”Click to Set Cursor” name=”myButton2”
onclick=”setFocus(2)”>
</form>
</body>
</html>
Select.form
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.form
Description
The form property of an instance of a Select object holds all the data of the form in
which the select box is contained. This allows a developer to obtain specific informa-
tion about the form in which the select box is located.
Example
Listing 8.408 has a select box and a button. When the button is clicked, three proper-
ties of the form as a whole are displayed. These properties were referenced through the
form property of the select box.
Select.handleEvent()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
select.handleEvent(event)
Description
The handleEvent() method of the Select object invokes the handler for the event
specified. This method was added in JavaScript 1.2.
Example
Listing 8.409 has a single select box. The script tells the browser that it wants to inter-
cept all Click events and that it wants the myClickHandler function to handle them.
16 0672321416 CH08c 7/24/01 12:31 PM Page 981
Client-Side 981
Within this function, the handleEvent() method of the select box has been specified
to handle the click.
When the user clicks anywhere on the page, the onClick event handler in the <select>
tag calls a function to change the selection in a select box. The change increments
through the four options in the box.
// Pass all click events to the onClick event of the select box.
window.document.myForm.mySelect.handleEvent(e);
Select.length
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.length
Description
The length property of an instance of a Select object returns the number of items in
the select box.
Example
Listing 8.410 has a single select box and button. The length property of a Select
object is displayed in an alert box when the button is clicked.
Client-Side 983
Select.name
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.name
Description
The name property of an instance of a Select object returns the name of the select box.
This property is often accessed via the elements array of a Form object and used to
return the name of the select area. It is most useful when there are many forms on a
given page, and determining the name helps you determine what function you want to
perform.
Example
Listing 8.411 has a single select box and button. The elements array of a Form object
is used to retrieve the name and display it in an alert box.
Listing 8.411 Using the name Property to Retrieve the Name of a Select
Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Select.onBlur
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onblur=”command”
Description
The onBlur event handler of an instance of a Select object is fired when the focus is
moved away from that particular select box. Care should be taken when using this
event handler because it is possible to get into an infinite loop when using the onFocus
event handler or the focus() method.
Example
Listing 8.412 contains two select boxes, one of which has the Blur event intercepted
within its tag and a text box. The text box is used for a counter for the number of times
the Blur event is fired.
In the script, the event is fired and the event handler calls a function that reassigns the
first select box focus. The result of this is that when a user tries to click or tab away
from the first select box, the counter is incremented and the focus returns. Note that this
does not mean the selected item in the select box becomes unselected, but rather the
first select box gains the focus.
As you will see if you run Listing 8.412, even clicking in other windows or the URL
bar increments the counter.
Client-Side 985
Select.onChange
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onchange=”command”
Description
The onChange event handler of an instance of a Select object is fired when the option
selected in the select box is changed. Care should be taken when using this event han-
dler because it is possible to get into an infinite loop when using other event handlers
or methods that are fired when focus is placed on or away from the select box.
Example
Listing 8.413 has a single select box. If the user changes the selected option, an alert
box is displayed showing the option that has been selected.
16 0672321416 CH08c 7/24/01 12:31 PM Page 986
Listing 8.413 Using the onChange Event Handler to Display an Alert Box
When an Option Is Selected in the Select Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Select.onFocus
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onfocus=”command”
Description
The onFocus event handler of an instance of a Select object is fired when the focus is
set on that particular select box. Care should be taken when using this event handler
because it is possible to get into an infinite loop when using the onBlur event handler
or the blur() method.
Example
Listing 8.414 contains a multiple select box and a text box. The select box has an
onFocus event handler within its tag that is fired every time you select an option in the
box. In the script, the onFocus event handler within the <select> tag calls a function
16 0672321416 CH08c 7/24/01 12:31 PM Page 987
Client-Side 987
that assigns the text box focus. Each time a user clicks or tabs to the select box, the
counter is incremented and the focus bar is returned to the text box.
Select.options
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.options
Description
The options property of the Select object is an array that contains the elements of
each of the options in the select box. This property is often used to retrieve properties
of the options in a select box, such as the value or text.
16 0672321416 CH08c 7/24/01 12:31 PM Page 988
Example
Listing 8.415 has a select box with four options in it. When an option is selected, a sec-
ond window pops up. In this window, the document.write() method is used to write
the properties of the selected option to the page.
Client-Side 989
</form>
</body>
</html>
Select.options.length
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.options.length
Description
The length property of the options array of the Select object returns the number of
options in that instance of a select box.
Example
Listing 8.416 has a single select box. When the user makes a selection, the onChange
event handler is used to pop up an alert box that displays the number of options in this
select box.
Select.options.selectedIndex
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.options.selectedIndex
Description
The selectedIndex property of the options array of the Select object returns the
index number of the selected option in that instance of a select box.
16 0672321416 CH08c 7/24/01 12:31 PM Page 990
Example
Listing 8.417 has a single select box. When the user makes a selection, the onChange
event handler is used to pop up an alert box that displays the index number of the
selected option in this select box.
Select.options.value
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.options.value
Description
The value property of the options array of the Select object returns the value of the
option that is selected in that instance of a select box.
Example
Listing 8.418 has a single select box. When the user makes a selection, the onChange
event handler is used to pop up an alert box that displays the value of the selected
option in this select box.
NOTE
Different browsers might fire this event at different times, so it is possible that the
alert box is displayed differently.
Client-Side 991
<option value=”TENNIS”>Tennis</option>
</select>
</form>
Select.selectedIndex
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
select.selectedIndex
Description
The selectedIndex property of the Select object returns the index number of the
selected option in that instance of a select box. If this property is used to access a mul-
tiple select box, it will return the index number of the first selected item.
Example
Listing 8.419 has a single select box. When the user makes a selection, the onChange
event handler is used to pop up an alert box that displays the index number of the
selected option in this select box.
Select.type
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
Syntax
select.type
Description
The type property of an instance of a Select object returns the type of the select box.
This is either select-multiple, if the multiple attribute is set in the <select> tag, or
select-one if it is not.
16 0672321416 CH08c 7/24/01 12:31 PM Page 992
Example
Listing 8.420 has a select box and a button. When the button is clicked, an alert box
is popped up that displays the type property of the select box.
Select.unwatch()
JavaScript 1.2+
Nav4+
Syntax
select.unwatch(property)
Description
The unwatch() method of the Select object is used to turn off the watch for a partic-
ular property.
Example
Listing 8.421 shows how the unwatch() method is used to stop watching the value
property.
16 0672321416 CH08c 7/24/01 12:31 PM Page 993
Client-Side 993
function check(){
document.myForm.mySelect.watch(“value”, alertme);
document.myForm.mySelect.unwatch(“value”);
document.myForm.mySelect.value=”GOLF”;
}
</script>
</head>
<body onload=”check()”>
<form name=”myForm”>
<select name=”mySelect”>
<option value=”HOCK”>Hockey</option>
<option value=”RUG”>Rugby</option>
<option value=”GOLF”>Golf</option>
<option value=”TENNIS”>Tennis</option>
</select>
</form>
</body>
</html>
Select.watch()
JavaScript 1.2+
Nav4+
Syntax
select.watch(property, function)
Description
The watch() method of the Select object is used to turn on the watch for a particular
property. Any time the specified property is changed after the watch() method has
been called, the specified function is called.
Example
Listing 8.422 shows how the watch() method is used to start watching the value
property.
16 0672321416 CH08c 7/24/01 12:31 PM Page 994
function check(){
document.myForm.mySelect.watch(“value”, alertme);
document.myForm.mySelect.value=”GOLF”;
}
</script>
</head>
<body onload=”check()”>
<form name=”myForm”>
<select name=”mySelect”>
<option value=”HOCK”>Hockey</option>
<option value=”RUG”>Rugby</option>
<option value=”GOLF”>Golf</option>
<option value=”TENNIS”>Tennis</option>
</select>
</form>
</body>
</html>
Style
JavaScript1.2,
Nav4
Syntax
Core client-side JavaScript object.
document.classes.className.tagName
document.ids.idName
document.tags.tagName
document.contextual(tag1, tag2)
Description
The Style object is a core client-side object within the Navigator 4 browser. Instances
of this object exist and are accessible through four different methods. Three of these
methods, document.ids, document.classes, and document.tags, represent associa-
tive arrays that contains the ids, classes, or tags, respectively, associated with the vari-
ous style access options. The document.contextual() method, on the other hand,
16 0672321416 CH08c 7/24/01 12:31 PM Page 995
Client-Side 995
finds instances of tag1 that occur within instances of tag2, and then creates an array
filled with matching instances.
Table 8.31 contains a list of properties and methods for this object.
NOTE
Navigator 4 is the only browser that supports this object, which was deprecated in
Netscape 6. You should only use it if you are scripting HTML or XHTML documents
that require backward compatibility with Navigator 4.
16 0672321416 CH08c 7/24/01 12:31 PM Page 997
Client-Side 997
Example
Listing 8.423 demonstrates three different ways to use document.ids to control the
style result.
<style type=”text/css”>
#TEXTFORMAT {font-style: italic;}
</style>
<style type=”text/javascript”>
ids.TEXTFORMAT.fontWeight = “bold”;
</style>
</html>
Style.align
JavaScript1.2
Nav4
Syntax
style.name.align
Description
The align property specifies the alignment of an element within its parent as associ-
ated with name. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
The align property can be assigned one of the following values: left, right, or none.
16 0672321416 CH08c 7/24/01 12:31 PM Page 998
NOTE
The align property is referred to as float when using CSS syntax. JavaScript
could not use the word “float” because it is a reserved word.
Example
Listing 8.424 uses the align property to align a paragraph to the right of its parent, the
document.
// -->
</script>
<p>Where am I?</p>
</html>
Style.backgroundColor
JavaScript1.2
Nav4
Syntax
style.name.backgroundColor
Description
The backgroundColor property specifies the background color as associated with
name. Because style can be created using the document.classes, document.ids, doc-
ument.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax.
Example
Listing 8.425 uses the backgroundColor property to make the background color
around an anchor red.
16 0672321416 CH08c 7/24/01 12:31 PM Page 999
Client-Side 999
// -->
</script>
</html>
Style.backgroundImage
JavaScript1.2
Nav4
Syntax
style.name.backgroundImage
Description
The backgroundImage property specifies the background image of an element as asso-
ciated with name. Because style can be created using the document.classes, docu-
ment.ids, document.tags, or document.contextual() methods, you should check
the entries for these items for more information on the exact syntax.
Example
The code in Listing 8.426 makes the image logo.gif the background for the header
text.
</html>
Style.borderBottomWidth
JavaScript1.2
Nav4
Syntax
style.name.borderBottomWidth
Description
The borderBottomWidth property specifies the width of the bottom border of an ele-
ment as associated with name. Because style can be created using the
document.classes, document.ids, document.tags, or document.contextual()
methods, you should check the entries for these items for more information on the
exact syntax.
Example
Listing 8.427 uses the borderBottomWidth property to set the size of bottom border
that surrounds a text header. Notice that only the bottom portion of the border is shown.
// -->
</script>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1001
Client-Side 1001
Style.borderColor
JavaScript1.2
Nav4
Syntax
style.name.borderColor
Description
The borderColor property specifies the color of the border of an element as associated
with name. Because style can be created using the document.classes, document.ids,
document.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax.
Example
Listing 8.428 uses the borderColor property to set the color of the border that sur-
rounds a text header to blue.
Listing 8.428 Setting the Border Color with the borderColor Property
<html>
// -->
</script>
</html>
Style.borderLeftWidth
JavaScript1.2
Nav4
Syntax
style.name.borderLeftWidth
Description
The borderLeftWidth property specifies the width of the left border of an element as
associated with name. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1002
Example
Listing 8.429 uses the borderLeftWidth property to set the size of the left border that
surrounds a text header. Notice that only the left portion of the border is shown.
Listing 8.429 Setting the Left Border Width with the borderLeftWidth
Property
<html>
// -->
</script>
</html>
Style.borderRightWidth
JavaScript1.2
Nav4
Syntax
style.name.borderRightWidth
Description
The borderRightWidth property specifies the width of the right border of an element
as associated with name. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
Example
Listing 8.430 uses the borderRightWidth property to set the size of right border that
surrounds a text header. Notice that only the right portion of the border is shown.
Listing 8.430 Setting the Right Border Width with the borderRightWidth
Property
<html>
Client-Side 1003
// -->
</script>
</html>
Style.borderStyle
JavaScript1.2
Nav4
Syntax
style.name.borderStyle
Description
The borderStyle property specifies the style of the border that surrounds an element
as associated with name. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
The borderStyle property can be assigned one of the following values: none, solid,
double, inset, outset, groove, and ridge.
Example
Listing 8.431 uses the borderStyle property to set the border around a text header to
a double line.
Listing 8.431 Setting the Border Style with the borderStyle Property
<html>
// -->
</script>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1004
Style.borderTopWidth
JavaScript1.2
Nav4
Syntax
style.name.borderTopWidth
Description
The borderTopWidth property specifies the width of the top border of an element as
associated with name. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
Example
Listing 8.432 uses the borderTopWidth property to set the size of top border that sur-
rounds a text header. Notice that only the top portion of the border is shown.
Listing 8.432 Setting the Top Border Width with the borderTopWidth
Property
<html>
// -->
</script>
</html>
Style.borderWidths()
JavaScript1.2
Nav4
Syntax
style.borderWidths(top, right, bottom, left)
style.borderWidths(top-bottom, right-left)
style.borderWidths(all)
16 0672321416 CH08c 7/24/01 12:32 PM Page 1005
Client-Side 1005
Description
The borderWidths() method specifies the width of the border that surrounds an ele-
ment as associated with style. Because style can be created using the
document.classes, document.ids, document.tags, or document.contextual()
methods, you should check the entries for these items for more information on the
exact syntax.
Setting border widths is equivalent to setting the borderBottomWidth,
borderLeftWidth, borderRightWidth, and borderTopWidth properties. Table 8.32
lists all the arguments associated with the borderWidths() method.
Example
Listing 8.433 uses the borderWidths() method to set the width of the border that sur-
rounds a text header.
Listing 8.433 Setting All the Border Widths with the borderWidths()
Method
<html>
// -->
</script>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1006
Style.clear
JavaScript1.2
Nav4
Syntax
style.clear
Description
The clear property specifies the sides of an element where floating elements (elements
that define the align property) are not allowed. Using dot notation, this property is asso-
ciated with style. Because style can be created using the document.classes, docu-
ment.ids, document.tags, or document.contextual() methods, you should check
the entries for these items for more information on the exact syntax.
The clear property can be assigned one of the following values: left, right, both,
and none.
Example
Listing 8.434 uses the clear property to prevent floating elements from being on either
side.
// -->
</script>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1007
Client-Side 1007
Style.color
JavaScript1.2
Nav4
Syntax
style.color
Description
The color property specifies the foreground color of an element as associated with
style. Because style can be created using the document.classes, document.ids,
document.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax.
Example
Listing 8.435 uses the color property to set the color of various text.
Listing 8.435 Set the Color of Text Using the color Property
<html>
// -->
</script>
</html>
Style.display
JavaScript1.2
Nav4
Syntax
style.display
Description
The display property specifies an element to be displayed when associated with
style. Because style can be created using the document.classes, document.ids,
document.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1008
The display property can be assigned one of the following values: inline, block,
list-item, and none.
Specifying an inline value is equivalent to using the <em> tag. The block value is the
same as creating header text with the <h1>–<h6> tags. Using list-item is equivalent
to using the <li> tag. If none is specified, the element is not displayed.
Example
Listing 8.436 uses the display property to create header text. block consists of a line
break and resetting margins to their default values. Notice that in this example a car-
riage return is automatically entered before the bold tag.
// -->
</script>
</html>
Style.fontFamily
JavaScript1.2
Nav4
Syntax
style.fontFamily
Description
The fontFamily property specifies the font an element should use when associated
with style. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax. More than
one font can be specified, in case a particular font has not been loaded.
Example
Listing 8.437 uses the fontFamily property to create text with an Arial font. If that font
is not available, Helvetica is used.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1009
Client-Side 1009
// -->
</script>
</html>
Style.fontSize
JavaScript1.2
Nav4
Syntax
style.fontSize
Description
The fontSize property specifies the size of fonts used by an element when associated
with name. Because style can be created using the document.classes, document.ids,
document.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax. The values that can be used to
set font size can be divided into four categories, as shown in Table 8.33.
Example
Listing 8.438 uses absolute font sizing to define the fontSize property and associate
with text.
// -->
</script>
</html>
Style.fontStyle
JavaScript1.2
Nav4
Syntax
style.fontStyle
Description
The fontStyle property specifies the font style used by an element when associated
with style. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
The fontStyle property can be assigned one of the following values: normal or
italic.
Example
Listing 8.439 uses the fontStyle property to italicize the header text.
Client-Side 1011
<!--
// -->
</script>
</html>
Style.fontWeight
JavaScript1.2
Nav4
Syntax
style.fontWeight
Description
The fontWeight property specifies the font weight used by an element when associ-
ated with style. Because style can be created using the document.classes, docu-
ment.ids, document.tags, or document.contextual() methods, you should check
the entries for these items for more information on the exact syntax.
The fontStyle property can be assigned one of the following values: normal, bold,
bolder, lighter, or a number from 100 to 900.
Example
Listing 8.440 uses the fontWeight property to set different levels of weight on various
text.
// -->
</script>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1012
</html>
Style.lineHeight
JavaScript1.2
Nav4
Syntax
style.lineHeight
Description
The lineHeight property specifies the distance between two lines that are next to each
other. Using dot notation, the property is associated with style. Because style can be
created using the document.classes, document.ids, document.tags, or
document.contextual() methods, you should check the entries for these items for
more information on the exact syntax.
Four types of values are valid for the lineHeight property: number, length, percent-
age,and the value normal.
When a number is given without a unit of measure, it is multiplied by the font size of
the element to give the line height, while including a unit of measure after the number
specifies length. A percentage is designated by including a percent sign (%) after the
number to represent the line height as it relates to its parent.
Example
Listing 8.441 uses the lineHeight property to set the distance between lines. In the
“D1” instance, it is set to 1 inch. In the “D2” instance, it is set to 50 point.
// -->
</script>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1013
Client-Side 1013
</html>
Style.listStyleType
JavaScript1.2
Nav4
Syntax
style.listStyleType
Description
The listStyleType property specifies the format of list items elements that are asso-
ciated with style. Because style can be created using the document.classes, docu-
ment.ids, document.tags, or document.contextual() methods, you should check
the entries for these items for more information on the exact syntax.
Nine types of values are valid for the listStyleType property: disc, circle, square,
decimal, lower-roman, upper-roman, lower-alpha, upper-alpha, and none.
NOTE
The listStyleType property is only valid if the element also has the display
property set to list-item.
Example
Listing 8.442 uses the listStyleType property to format a list of items.
// -->
</script>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1014
</html>
Style.marginBottom
JavaScript1.2
Nav4
Syntax
style.marginBottom
Description
The marginBottom property specifies the minimum distance between the bottom bor-
der of an element and the top border of another element. Dot notation is used to asso-
ciate this property with style. Because style can be created using the
document.classes, document.ids, document.tags, or document.contextual()
methods, you should check the entries for these items for more information on the
exact syntax.
Example
Listing 8.443 uses the marginBottom property to set the distance between adjacent
elements.
Listing 8.443 Set the Bottom Margin with the marginBottom Property
<html>
//Create a style sheet class and id that define the bottom margin.
document.classes.FORMAT.all.borderWidths(10);
document.ids.margin.marginBottom = 40;
// -->
</script>
Client-Side 1015
</html>
Style.marginLeft
JavaScript1.2
Nav4
Syntax
style.marginLeft
Description
The marginLeft property specifies the distance between the left border of an element
and the right border of another element. Dot notation is used to associate this property
with style. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
Example
Listing 8.444 uses the marginLeft property to set the distance between adjacent
elements. Notice the distance between the border and the right edge of the browser
window.
Listing 8.444 Set the Left Margin with the marginLeft Property
<html>
// -->
</script>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1016
Style.marginRight
JavaScript1.2
Nav4
Syntax
style.marginRight
Description
The marginRight property specifies the distance between the right border of an ele-
ment and the left border of another element. Dot notation is used to associate this prop-
erty with style. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
Example
Listing 8.445 uses the marginRight property to set the distance between adjacent ele-
ments. Notice the distance between the border and the right edge of the browser win-
dow.
Listing 8.445 Set the Right Margin with the marginRight Property
<html>
// -->
</script>
</html>
Style.margins()
JavaScript1.2
Nav4
Syntax
style.margins(top, right, bottom, left)
style.margins(top-bottom, right-left)
style.margins(all)
16 0672321416 CH08c 7/24/01 12:32 PM Page 1017
Client-Side 1017
Description
The margins() method specifies the margin distance between the border of an element
and the border of adjacent elements. Dot notation is used to associate the property with
style. Because style can be created using the document.classes, document.ids,
document.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax.
Setting margin widths is equivalent to setting the marginBottom, marginLeft,
marginRight, and marginTop properties. Table 8.34 lists all the arguments associated
with the margins() method.
Example
Listing 8.446 uses the margins() method to set the margin widths around a text
element.
// -->
</script>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1018
Style.marginTop
JavaScript1.2
Nav4
Syntax
style.marginTop
Description
The marginTop property specifies the minimum distance between the top border of an
element and the bottom border of another element. Dot notation is used to associate
this property with style. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
Example
Listing 8.447 uses the marginTop property to set the minimum distance between adja-
cent elements.
Listing 8.447 Set the Top Margin with the marginTop Property
<html>
// -->
</script>
</html>
Style.paddingBottom
JavaScript1.2
Nav4
Syntax
style.paddingBottom
16 0672321416 CH08c 7/24/01 12:32 PM Page 1019
Client-Side 1019
Description
The paddingBottom property specifies the minimum distance between the bottom bor-
der of an element and its content. Using dot notation, the property is associated with
style. Because style can be created using the document.classes, document.ids,
document.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax.
Example
Listing 8.448 uses the paddingBottom property to set the distance between a line of
text and its border.
Listing 8.448 Set the Bottom Padding with the paddingBottom Property
<html>
// -->
</script>
</html>
Style.paddingLeft
JavaScript1.2
Nav4
Syntax
style.paddingLeft
Description
The paddingLeft property specifies the minimum distance between the left border of
an element and its content. Using dot notation, the property is associated with style.
Because style can be created using the document.classes, document.ids, docu-
ment.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax.
Example
Listing 8.449 uses the paddingLeft property to set the distance between a line of text
and its border.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1020
Listing 8.449 Set the Left Padding with the paddingLeft Property
<html>
// -->
</script>
</html>
Style.paddingRight
JavaScript1.2
Nav4
Syntax
style.paddingRight
Description
The paddingRight property specifies the distance between the right border of an ele-
ment and its content. Using dot notation, the property is associated with style.
Because style can be created using the document.classes, document.ids, docu-
ment.tags, or document.contextual() methods, you should check the entries for
these items for more information on the exact syntax.
Example
Listing 8.450 uses the paddingRight property to set the distance between a line of text
and its border.
Listing 8.450 Set the Right Padding with the paddingRight Property
<html>
Client-Side 1021
// -->
</script>
</html>
Style.paddings()
JavaScript1.2
Nav4
Syntax
style.paddings(top, right, bottom, left)
style.paddings(top-bottom, right-left)
style.paddings(all)
Description
The paddings() method specifies the distance between the borders of an element and
its content. Using dot notation, the property is associated with style. Because style
can be created using the document.classes, document.ids, document.tags, or
document.contextual() methods, you should check the entries for these items for
more information on the exact syntax. Setting the sizes is equivalent to setting the
paddingBottom, paddingLeft, paddingRight, and paddingTop properties. Table 8.35
lists all the arguments associated with this method.
Example
Listing 8.451 uses the paddings() method to set the distance between text and all sides
of its border.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1022
// -->
</script>
</html>
Style.paddingTop
JavaScript1.2
Nav4
Syntax
style.paddingTop
Description
The paddingTop property specifies the distance between the left border of an element
and its content. Using dot notation, the property is associated with style. Because
style can be created using the document.classes, document.ids, document.tags, or
document.contextual() methods, you should check the entries for these items for
more information on the exact syntax.
Example
Listing 8.452 uses the paddingTop property to set the distance between a line of text
and its border.
Client-Side 1023
// -->
</script>
</html>
Style.textAlign
JavaScript1.2
Nav4
Syntax
style.textAlign
Description
The textAlign property specifies the alignment of text within an element as associated
with style. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
Four types of values are valid for the textAlign property: left, right, center, and
justify.
Example
Listing 8.453 uses the textAlign property to align the text to the right.
// -->
</script>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1024
Style.textDecoration
JavaScript1.2
Nav4
Syntax
style.textDecoration
Description
The textDecoration property specifies the type of decoration that is added to text as
associated with style. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
Four types of values are valid for the textDecoration property: underline, line-
through, blink, and none.
Example
Listing 8.454 uses the textDecoration property to put a line through a line of text.
// -->
</script>
</html>
Style.textIndent
JavaScript1.2
Nav4
Syntax
style.textIndent
Description
The textIndent property specifies that the indention should appear before text as
associated with style. Because style can be created using the document.classes,
16 0672321416 CH08c 7/24/01 12:32 PM Page 1025
Client-Side 1025
Example
Listing 8.455 uses the textIndent property to set the text indention to 1 inch.
// -->
</script>
</html>
Style.textTransform
JavaScript1.2
Nav4
Syntax
style.textTransform
Description
The textTransform property specifies the transformation that should be applied to text
as associated with style. Because style can be created using the document.classes,
document.ids, document.tags, or document.contextual() methods, you should
check the entries for these items for more information on the exact syntax.
Four types of values are valid for the textTransform property: capitalize, upper-
case, lowercase, and none.
Example
Listing 8.456 uses the textTransform property to capitalize the first letter of every
word in the sentence.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1026
// -->
</script>
</html>
Style.unwatch()
JavaScript 1.2
Nav4
Syntax
style.unwatch(property)
Description
The unwatch() method of the Style object is used to turn off the watch for a particu-
lar property.
Example
Listing 8.457 shows how the unwatch() method is used to stop watching the user-
defined property textTransform.
document.ids.CAP.watch(“textTransform”, alertme);
document.ids.CAP.textTransform = “capitalize”;
document.ids.CAP.unwatch(“textTransform”);
document.ids.CAP.textTransform = “lowercase”;
16 0672321416 CH08c 7/24/01 12:32 PM Page 1027
Client-Side 1027
// -->
</script>
</head>
<body>
<p id=”CAP”>This line demonstrates the ability to capitalize words.</p>
</body>
</html>
Style.watch()
JavaScript1.2
Nav4
Syntax
style.watch(property, function)
Description
The watch() method of the Style object is used to turn on the watch for a particular
property. Any time the specified property is changed after the watch() method has
been called, the specified function is called.
Example
Listing 8.458 shows how the watch() method is used to start watching the user-defined
property p.
document.ids.CAP.watch(“textTransform”, alertme);
document.ids.CAP.textTransform = “capitalize”;
// -->
</script>
</head>
<body>
<p id=”CAP”>This line demonstrates the ability to capitalize words.</p>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1028
Style.whiteSpace
JavaScript1.2
Nav4
Syntax
style.whiteSpace
Description
The whiteSpace property specifies how whitespace should be handled within an ele-
ment. Using dot notation, the property can be associated with style. Because style
can be created using the document.classes, document.ids, document.tags, or docu-
ment.contextual() methods, you should check the entries for these items for more
information on the exact syntax.
Two types of values are valid for the whiteSpace property: normal and pre.
Example
Listing 8.459 uses the whiteSpace property to make whitespace collapsed within the
text element.
// -->
</script>
</html>
Style.width
JavaScript1.2
Nav4
Syntax
style.width
16 0672321416 CH08c 7/24/01 12:32 PM Page 1029
Client-Side 1029
Description
The width is property of the Style object is used to specify the width of a block-level
HTML element. The property itself can take a numerical length, a percentage, or the
keyword auto, which tells Navigator 4 to determine the width automatically. The fol-
lowing shows a brief example of syntax:
// length
myStyle.width = 12pt;
// percentage
myStyle.width = 75%;
// automatically format
myStyle.width = auto;
Example
Listing 8.460 shows how we can use the width property to set the border of a <p> ele-
ment to 12 point.
Listing 8.460 Using the width Property to Set the Border Width of an
Element
<html>
<head>
<script type=”text/javascript” language=”JavaScript”>
<!--
// -->
</script>
</head>
<body>
<p id=”border”>This has a 12 point border.</p>
</body>
</html>
Submit
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Submit object is one of the core JavaScript objects. Instances are created by the
browser when it encounters an HTML <input> tag with the type attribute set to
16 0672321416 CH08c 7/24/01 12:32 PM Page 1030
submit. In the JavaScript object hierarchy, the Submit object is located at window.doc-
ument.Form.Submit. Table 8.36 lists the properties, methods, and events used by the
Submit object.
NOTE
Starting with Navigator 4, if you submit a form to a mailto: or news: protocol, the
UniversalSendMail security privilege must be set.
Example
Listing 8.461 displays the use of the Submit properties. It contains a select box and a
submit button. When the button is clicked, a second window is opened. The values of
the properties of this Submit object are displayed in this window.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1031
Client-Side 1031
// Place the reference to the Submit button in a variable for easier access.
var myInstance = document.myForm.mySubmit;
// Note that the entire form object is passed with this property.
// This allows you to then drill down and get the value of other
// components in the form.
myWin.document.write(“The form can be used to grab the “);
myWin.document.write(“value of the button: “);
myWin.document.write(myInstance.form.mySubmit.value);
Submit.blur()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
submit.blur()
16 0672321416 CH08c 7/24/01 12:32 PM Page 1032
Description
The blur() method of the Submit object removes the focus from the submit button. Be
careful when using this method in conjunction with the Submit.focus() method. It can
lead to a focus/blur loop, where the browser blurs a focus as soon as it is done, and vice
versa.
Example
Listing 8.462 has a text box and a submit button. If the user clicks the Click Here to
Remove Focus button, the button will no longer be focused. The best way to see this is
to tab to the button and then click it. When tabbing to the button, you should see that
it becomes selected.
Listing 8.462 Using the blur() Method to Remove the Focus from the
Submit Button
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Submit.click()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
submit.click()
16 0672321416 CH08c 7/24/01 12:32 PM Page 1033
Client-Side 1033
Description
The click() method of an instance of the Submit object simulates a click on the sub-
mit button. Note that if you have an onClick event handler assigned to this button, it
will not be executed.
Example
Listing 8.463 has a text field, a submit button, and a link. If the user clicks the link, a
function will be called to check whether the user entered any text. If the user did not,
an alert box is displayed. If the user did enter text, the function submits the form by
calling the click() method of the submit button.
Submit.focus()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
submit.focus()
Description
The focus() method of the Submit object places focus on the Submit button. Be care-
ful when using this method in conjunction with the Submit.blur() method. It can lead
to a focus/blur loop, where the browser blurs a focus as soon as it is done, and vice
versa.
Example
Listing 8.464 has a text box and a submit button. If the user clicks in the text box, focus
is placed on the submit button.
Listing 8.464 Using the focus() Method to Set the Focus on the Submit
Button
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Submit.form
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
16 0672321416 CH08c 7/24/01 12:32 PM Page 1035
Client-Side 1035
Syntax
submit.form
Description
The form property of an instance of the Submit object provides access to all the data
of the form in which the submit button is located.
Example
Listing 8.465 has a text box and a submit button. When the button is clicked, three
properties of the form as a whole are displayed. These properties were referenced
through the form property of the submit button.
Submit.handleEvent()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
submit.handleEvent(event)
Description
The handleEvent() method of the Submit object invokes the handler for the event
specified. This method was added in JavaScript 1.2.
Example
Listing 8.466 has a single text box. The script tells the browser that it wants to inter-
cept all Click events and that it wants the myClickHandler function to handle them.
Within this function, the handleEvent() method of the submit button has been speci-
fied to handle the click.
When the user clicks anywhere on the page, the onClick event handler in the <input
type=”submit”> tag calls a function to change the text in the text box. The change is
nothing more than a simple number that is incremented, counting the number of times
the page has been clicked.
Client-Side 1037
// Pass all click events to the onClick event of the submit button.
window.document.myForm.mySubmit.handleEvent(e);
Submit.name
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
submit.name
Description
The name property of an instance of a Submit object returns the name of the submit but-
ton. This property is often accessed via the elements array of a Form object and used
to return the name of the button. It is most useful when there are many forms on a given
page, and determining the name helps you determine what function you want to per-
form.
Example
Listing 8.467 has a single text box and submit button. The elements array of a Form
object is used to retrieve the name and display it in an alert box.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1038
Listing 8.467 Using the name Property to Retrieve the Name of a Submit
Button
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Submit.onBlur
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onblur=”command”
Description
The onBlur event handler is fired when the focus is moved away from that particular
submit button. Care should be taken when using this event handler because it is possi-
ble to get into an infinite loop when using the onFocus event handler or focus()
method.
Example
Listing 8.468 contains two text boxes and a submit button. The button has the Blur
event intercepted within its tag. The second text box is used as a counter for the num-
ber of times the onBlur event handler is fired.
In the script, the event calls a function that reassigns the submit button focus. The result
of this is that when a user tries to click or tab away from the submit button box, the
counter is incremented and the focus returns. As you will see if you run Listing 8.486,
even clicking in other windows or the URL bar increments the counter.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1039
Client-Side 1039
Submit.onClick
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onclick=”command”
Description
The onClick event handler is fired when a submit button is clicked. Note that this is
not fired in the instances where a single form object is in the form, such as a text box,
and the user presses the Enter or Return key to submit the form.
Example
Listing 8.469 has a single text box and a button. If the user presses the submit button,
the Click event is fired, calling a function that changes the text in the text box to all
uppercase.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1040
Listing 8.469 Using the onClick Event Handler to Display the Contents
of a Form Textbox Before It Is Submitted
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
}
// -->
</script>
</head>
<body>
<form name=”myForm”>
Please Enter some text and click the Submit Button.<br>
<input type=”text” value=”Enter Text Here” name=”myText”>
<input type=”button” value=”Submit” name=”mySubmit” onclick=”setText()”>
</form>
</body>
</html>
Submit.onFocus
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onfocus=”command”
Description
The onFocus event handler of an instance of a Submit object is fired when focus is set
to that particular submit button. Care should be taken when using this event handler
because it is possible to get into an infinite loop when using the onBlur event handler
or blur() method.
Example
Listing 8.470 contains two text boxes and a submit button. The submit button has the
Focus event intercepted within its tag. The second text box is used for a counter for the
number of times the onFocus event handler is fired.
In the script, the event calls a function that assigns the first text box focus. The result
of this is that when a user tries to click or tab to the submit button, the counter is incre-
mented and the focus is returned to the text box.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1041
Client-Side 1041
Submit.type
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
Syntax
submit.type
Description
The type property of an instance of a Submit object returns the type of the text box.
This always returns submit.
Example
Listing 8.471 has a text box and a submit button. When the button is clicked, an alert
box is popped up that displays the type property of the submit button.
Submit.unwatch()
JavaScript 1.2+
Nav4+
Syntax
submit.unwatch(property)
Description
The unwatch() method of the Submit object is used to turn off the watch for a partic-
ular property.
Example
Listing 8.472 shows how the unwatch() method is used to stop watching the value
property.
Client-Side 1043
// Once loaded, watch the value property and then change it, and then
// turn off the watch.
function check(){
document.myForm.mySubmit.watch(“value”, alertme);
document.myForm.mySubmit.value=”Send”;
document.myForm.mySubmit.unwatch(“value”);
}
</script>
</head>
<body onload=”check()”>
<form name=”myForm”>
<input type=”submit” name=”mySubmit” value=”Submit”>
</form>
</body>
</html>
Submit.value
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
submit.value
Description
The value property of an instance of a Submit object returns the current value of the
submit button. This value is what is displayed on the button itself.
Example
Listing 8.473 contains a text box and button. When a user clicks the submit button, an
alert box pops up displaying the value of this instance.
Submit.watch()
JavaScript 1.2+
Nav4+
Syntax
submit.watch(property, function)
Description
The watch() method of the Submit object is used to turn on the watch for a particular
property. Any time the specified property is changed after the watch() method has
been called, the specified function is called.
Example
Listing 8.474 shows how the watch() method is used to start watching the value
property.
// Once page is loaded, watch the value property then change it.
function check(){
document.myForm.mySubmit.watch(“value”, alertme);
document.myForm.mySubmit.value=”Send”;
}
16 0672321416 CH08c 7/24/01 12:32 PM Page 1045
Client-Side 1045
</script>
</head>
<body onload=”check()”>
<form name=”myForm”>
<input type=”submit” name=”mySubmit” value=”Submit”>
</form>
</body>
</html>
taint()
JavaScript1.1
Nav3
Syntax
taint(object)
Description
The taint() method was a security measure that was only implemented in JavaScript
1.1 and that allowed a developer to keep return values from being used by and propa-
gated to other scripts. This method does not change the data element passed to it, but
rather returns a marked reference to the element.
Because taint() and the functionality of data tainting was removed in JavaScript 1.2,
you should avoid using this method. You should use it only if you have a specific secu-
rity reason for compatibility with Navigator 3 browsers. See Chapter 1, “What is
JavaScript to a Programmer?” for more information on the security model that is now
used in Navigator browsers.
Example
Listing 8.475 simply taints a variable that is defined in a separate window.
// -->
</script>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1046
Text
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Text object is one of the core JavaScript objects. Instances are created by the
browser when it encounters an HTML <input> tag with the type attribute set to text.
In the JavaScript object hierarchy, the Text object is located at
window.document.Form.Text. Table 8.37 lists the properties, methods, and events
used by the Text object.
Client-Side 1047
Example
Listing 8.476 displays the use of the Text properties. It contains a text box and a but-
ton. When the button is clicked, a second window is opened. The values of the proper-
ties of this Text object are displayed in the second window.
// Place the reference to the text box in a variable for easier access.
var myInstance = document.myForm.myText;
// Note that the entire form object is passed with this property.
// This allows you to then drill down and get the value of other
// components in the form.
myWin.document.write(“The form can be used to grab the value “);
myWin.document.write(“of the button: “);
myWin.document.write(myInstance.form.myButton.value);
Text.blur()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
text.blur()
Description
The blur() method of the Text object removes focus from the text box. Be careful
when using this method in conjunction with the Text.focus() method. It can lead to
a focus/blur loop, where the browser blurs a focus as soon as it is done, and vice versa.
Example
Listing 8.477 has a text box and a button. If the user highlights some of the text in the
box and then clicks the Click Here to Remove Focus button, the text will no longer be
highlighted.
Listing 8.477 Using the blur() Method to Remove Focus from the Text
Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Client-Side 1049
Text.defaultValue
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera5+
Syntax
text.defaultValue
Description
The defaultValue property of a Text object instance contains the default value spec-
ified by the value attribute of the <input> tag. This property is often used to reset
forms to their default values after a user has entered some data.
Example
Listing 8.478 has a text box and a button. If the user edits some of the text in the box
and then clicks the Click to Reset button, the text will change back to the default value.
Listing 8.478 Using the defaultValue Property to Set the Value of the
Text Box Back to Its Original Value
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Text.focus()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
text.focus()
Description
The focus() method of the Text object gives focus to the text box. Be careful when
using this method in conjunction with the Text.blur() method. It can lead to a
focus/blur loop, where the browser blurs a focus as soon as it is done, and vice versa.
Example
Listing 8.479 has two text boxes and two buttons. If the user clicks the first button, the
cursor is set inside the first text box. If the user clicks the second button, the cursor is
set inside the second text box.
Listing 8.479 Using the focus() Method to Place the Cursor in the
Desired Text Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Client-Side 1051
Text.form
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
text.form
Description
The form property of an instance of a Text object holds all the data of the form in
which the text box is contained. This allows a developer to obtain specific information
about the form in which the text box is located.
Example
Listing 8.480 has a text box and a button. When the button is clicked, three properties
of the form as a whole are displayed. These properties were referenced though the form
property of the text box.
Text.handleEvent()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
text.handleEvent(event)
Description
The handleEvent() method of the Text object invokes the handler for the event spec-
ified. This method was added in JavaScript 1.2.
Example
Listing 8.481 has a single text box. The script tells the browser that it wants to inter-
cept all Click events and that it wants the myClickHandler function to handle them.
Within this function, the handleEvent() method of the text box has been specified to
handle the click.
When the user clicks anywhere on the page, the onClick event handler in the <input
type=”text”> tag calls a function to change the text in the text box. The change is
nothing more than a simple number that is incremented, counting the number of times
the page has been clicked.
Client-Side 1053
// Pass all click events to the onClick event of the text box.
window.document.myForm.myText.handleEvent(e);
Text.name
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
text.name
Description
The name property of an instance of a Text object returns the name of the text box. This
property is often accessed via the elements array of a Form object and used to return
the name of the text area. It is most useful when there are many forms on a given page,
and determining the name helps you determine what function you want to perform.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1054
Example
Listing 8.482 has a single text box and button. The elements array of a Form object is
used to retrieve the name and display it in an alert box.
Listing 8.482 Using the name Property to Retrieve the Name of a Text
Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Text.onBlur
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onblur=”command”
Description
The onBlur event handler of an instance of a Text object is fired when the focus is
moved away from that particular text box. Care should be taken when using this event
handler because it is possible to get into an infinite loop when using the onFocus event
handler or the focus() method.
Example
Listing 8.483 contains three text boxes, one of which has the onBlur event handler
intercepted within its tag. The third text box is used for a counter for the number of
times the onBlur event handler is fired.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1055
Client-Side 1055
In the script, the event calls a function that reassigns the first text box focus. The result
of this is that when a user tries to click or tab away from the first text box, the counter
is incremented and the focus returns. As you will see if you run Listing 8.499, even
clicking in other windows or the URL bar increments the counter.
Text.onChange
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onchange=”command”
Description
The onChange event handler of an instance of a Text object is fired when the text in the
box is modified. Care should be taken when using this event handler because it is pos-
sible to get into an infinite loop when using other events or methods that are fired when
focus is placed on or away from the text box.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1056
Example
Listing 8.484 has a single text box. If the user changes the text and then shifts the focus
away from the text box by clicking elsewhere or pressing Return, the default text is
placed back in the text box.
Listing 8.484 Using the onChange Event Handler to Change the Text
Back to the Default
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
// Change the text back to the default if user tries to change it.
// Note that the user has to click away or hit return for this
// to change back.
function changeBack(){
document.myForm.myText.value = document.myForm.myText.defaultValue;
}
// -->
</script>
</head>
<body>
<form name=”myForm”>
<input type=”text” value=”Change Me?” name=”myText” onchange=’changeBack()’>
</form>
</body>
</html>
Text.onFocus
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onfocus=”command”
Description
The onFocus event handler of an instance of a Text object is fired when focus is made
on that particular text box. Care should be taken when using this event handler because
it is possible to get into an infinite loop when using the onBlur event handler or the
blur() method.
Example
Listing 8.485 contains three text boxes, one of which has the onFocus event handler
intercepted within its tag. The third text box is used for a counter for the number of
times the Focus event is fired.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1057
Client-Side 1057
In the script, the event handler calls a function that assigns the second text box focus.
The result of this is that when a user tries to click or tab to the first text box, the counter
is incremented and the focus is returned to the second text the box.
Text.onSelect
JavaScript1.0+, JScript1.0+
IE3+, Net6
Syntax
onselect=”command”
Description
The onSelect event handler of an instance of a Text object is fired when the text in the
box is highlighted. Care should be taken when using this event handler because it is
possible to get into an infinite loop when using other events or methods that are fired
when focus is placed on the text box.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1058
NOTE
Note that Netscape defined this function in JavaScript 1.0; however, it was not
fully implemented until Netscape 6. Opera browsers do not support this function
either.
Example
Listing 8.486 has two text boxes. If the user highlights the text in the first text box, the
default text of the first text box is written to the second text box.
Listing 8.486 Using the onSelect Event Handler to Set the Text in the
Second Text Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Text.select()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
text.select()
Description
The select() method of the Text object selects the text in the text box. Be careful
when using this method in conjunction with the blur() and focus() methods. It can
lead to a focus/blur loop where the browser blurs or focuses as soon as it is has been
selected, and vice versa.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1059
Client-Side 1059
Example
Listing 8.487 has a text box and a button. If the user clicks the button, the text inside
the text box will be highlighted. Notice that the focus() method had to be used to tell
the browser to actually highlight the text.
Listing 8.487 Using the select() Method to Select the Text in a Text
Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Text.type
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
Syntax
text.type
Description
The type property of an instance of a Text object returns the type of the text box. This
always returns text.
Example
Listing 8.488 has a text box and a button. When the button is clicked, an alert box is
popped up that displays the type property of the text box.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1060
Text.unwatch()
JavaScript 1.2+
Nav4+
Syntax
text.unwatch(property)
Description
The unwatch() method of the text object is used to turn off the watch for a particular
property.
Example
Listing 8.489 shows how the unwatch() method is used to stop watching the value
property.
Client-Side 1061
return newValue;
}
function check(){
document.myForm.myItem.watch(“value”, alertme);
document.myForm.myItem.unwatch(“value”);
document.myForm.myItem.value=”Send”;
}
</script>
</head>
<body onload=”check()”>
<form name=”myForm”>
<input type=”text” name=”myItem” value=”Submit”>
</form>
</body>
</html>
Text.value
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
text.value
Description
The value property of an instance of a Text object returns the current value of the text
box. Note that this is not the default value that can be accessed via the
Text.defaultValue property and is often used to set the value of a text box.
Example
Listing 8.490 contains a text box and button. You can edit the text in the text box and
then click the Reset button to reset the text back to the default value.
Listing 8.490 Resetting the Value of a Text Box to the Default Value
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Text.watch()
JavaScript 1.2+
Nav4+
Syntax
text.watch(property, function)
Description
The watch() method of the Text object is used to turn on the watch for a particular
property. Any time the specified property is changed after the watch() method has
been called, the specified function is called.
Example
Listing 8.491 shows how the watch() method is used to start watching the value
property.
function check(){
document.myForm.myItem.watch(“value”, alertme);
document.myForm.myItem.value=”Send”;
}
</script>
</head>
<body onload=”check()”>
<form name=”myForm”>
<input type=”text” name=”myItem” value=”Submit”>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1063
Client-Side 1063
</form>
</body>
</html>
Textarea
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Textarea object is one of the core JavaScript objects. Instances are created by the
browser when it encounters an HTML <textarea> tag. In the JavaScript object hierar-
chy, the Textarea object is located at window.document.Form.Textarea. Table 8.38
lists the event handlers, methods, and properties used by the Textarea object.
Example
Listing 8.492 displays the use of the Textarea properties. It contains a text area and a
button. When the button is clicked, a second window is opened. The values of the prop-
erties of this Textarea object are displayed in this window.
// Place the reference to the text area in a variable for easier access.
var myInstance = document.myForm.myTextArea;
// Note that the entire form object is passed with this property.
// This allows you to then drill down and get the value of other
// components in the form.
myWin.document.write(“The form can be used to grab the “);
16 0672321416 CH08c 7/24/01 12:32 PM Page 1065
Client-Side 1065
Textarea.blur()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
textarea.blur()
Description
The blur() method of the Textarea object removes the focus from the text area. Be
careful when using this method in conjunction with the Textarea.focus() method. It
can lead to a focus/blur loop, where the browser blurs a focus as soon as it is done, and
vice versa.
Example
Listing 8.493 has a text area and a button. If the user highlights some of the text in the
box and then clicks the Click Here to Remove Focus button, the text will no longer be
highlighted.
Listing 8.493 Using the blur() Method to Remove the Focus from the
Text Area
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
16 0672321416 CH08c 7/24/01 12:32 PM Page 1066
Textarea.defaultValue
JavaScript1.0+, JScript1.0+
Nav2+, IE3+
Syntax
textarea.defaultValue
Description
The defaultValue property of a Textarea object instance contains the text between
the beginning and ending <textarea> tags. This property is often used to reset areas to
their default values after a user has modified them.
Example
Listing 8.494 has a text area and a button. If the user edits some of the text in the box
and then clicks the Click to Reset button, the text will change back to the default value.
Listing 8.494 Using the defaultValue Property to Set the Value of the
Text Area Back to Its Original Value
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
16 0672321416 CH08c 7/24/01 12:32 PM Page 1067
Client-Side 1067
Textarea.focus()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
textarea.focus()
Description
The focus() method of the Textarea object gives the focus to the text area. Be care-
ful when using this method in conjunction with the Textarea.blur() method. It can
lead to a focus/blur loop, where the browser blurs a focus as soon as it is done, and vice
versa.
Example
Listing 8.495 has two text areas and two buttons. If the user clicks the first button, the
cursor is set inside the first text area. If the user clicks the second button, the cursor is
set inside the second text area.
Listing 8.495 Using the focus() Method to Place the Cursor in the
Desired Text Area
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1068
Textarea.form
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
textarea.form
Description
The form property of an instance of a Textarea object holds all the data of the form in
which the text box is contained. This allows a developer to obtain specific information
about the form in which the text area is located.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1069
Client-Side 1069
Example
Listing 8.496 has a text area and a button. When the button is clicked, three properties
of the form as a whole are displayed. These properties were referenced through the
form property of the text area.
Textarea.handleEvent()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
textarea.handleEvent(event)
Description
The handleEvent() method of the Textarea object invokes the handler for the event
specified. This method was added in JavaScript 1.2.
Example
Listing 8.497 has a single text area. The script tells the browser that it wants to inter-
cept all Click events and that it wants the myClickHandler function to handle them.
Within this function, the handleEvent() method of the text area has been specified to
handle the click.
When the user clicks anywhere on the page, the onClick event handler in the
<textarea> tag calls a function to change the text in the text area. The change is noth-
ing more than a simple number that is incremented, counting the number of times the
page has been clicked.
// Pass all click events to the onClick event of the text area.
window.document.myForm.myTextArea.handleEvent(e);
}
16 0672321416 CH08c 7/24/01 12:32 PM Page 1071
Client-Side 1071
Textarea.name
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
textarea.name
Description
The name property of an instance of a Textarea object returns the name of the text area.
This property is often accessed via the elements array of a Form object and used to
return the name of the text area. It is most useful when there are many forms on a given
page, and determining the name helps you determine what function you want to per-
form.
Example
Listing 8.498 has a text area and button. The elements array of a Form object is used
to retrieve the name and display it in an alert box.
Listing 8.498 Using the name Property to Retrieve the Name of a Text
Area
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Textarea.onBlur
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onblur=”command”
Description
The onBlur event handler of an instance of a Textarea object is fired when the focus
is moved away from that particular text area. Care should be taken when using this
event handler because it is possible to get into an infinite loop when using onFocus
event handler or focus() method.
Example
Listing 8.499 contains three text areas, one of which has the onBlur event handler used
within its tag. The third text box is used as a counter for the number of times the onBlur
event handler is used.
In the script, the event calls a function that reassigns the first text area focus. The result
of this is that when a user tries to click or tab away from the first text area, the counter
is incremented and the focus returns. As you will see if you run Listing 8.513, even
clicking in other windows or the URL bar increments the counter.
Client-Side 1073
<!--
Textarea.onChange
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onchange=”command”
Description
The onChange event handler of an instance of a Textarea object is fired when the text
in the area is modified. Care should be taken when using this event handler because it
is possible to get into an infinite loop when using other events or methods that are fired
when focus is placed on or away from the text area.
Example
Listing 8.500 has a single text area. If the user changes the text and then shifts the focus
away from the text area by clicking elsewhere, the default text is placed back in the text
area.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1074
Listing 8.500 Using the onChange Event Handler to Change the Text
Back to the Default
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
// Change the text back to the default if user tries to change it.
// Note that the user has to click away or hit return for this
// to change back.
function changeBack(){
document.myForm.myTextArea.value = document.myForm.myTextArea.defaultValue;
}
// -->
</script>
</head>
<body>
<form name=”myForm”>
<textarea name=”myTextArea” rows=”2” cols=”50” onchange=’changeBack()’>
Here is some text in my text area.
</textarea>
</form>
</body>
</html>
Textarea.onFocus
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onfocus=”command”
Description
The onFocus event handler of an instance of a Textarea object is fired when focus is
made on that particular text area. Care should be taken when using this event handler
because it is possible to get into an infinite loop when using the onBlur event handler
or the blur() method.
Example
Listing 8.501 contains three text boxes, one of which has the Focus event intercepted
within its tag. The third text box is used for a counter for the number of times the Focus
event is fired.
In the script, the event calls a function that assigns the second text box focus. The result
of this is that when a user tries to click or tab to the first text box, the counter is incre-
mented and the focus is returned to the second text box.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1075
Client-Side 1075
Textarea.onKeyDown
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
onkeydown=”command”
Description
The onKeyDown event handler of an instance of a Textarea object is fired when a key
is pressed down within the text area. Care should be taken when using this event han-
dler because it is possible to get into an infinite loop when using other events or meth-
ods that are fired when the focus is placed on or away from the text area or other
key-related events are used. The onKeyDown event handler is called followed by a
onKeyPress event handler.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1076
Example
Listing 8.502 has a single text area. If the user presses a key while the focus is on the
text area, an alert box is displayed as soon as the key is pressed.
Textarea.onKeyPress
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
onkeypress=”command”
Description
The onKeyPress event handler of an instance of a Textarea object is fired when a key
is pressed within the text area. Care should be taken when using this event handler
because it is possible to get into an infinite loop when using other events or methods
that are fired when the focus is placed on or away from the text area or other key-
related events are used. This event is called after an onKeyDown event handler.
Example
Listing 8.503 has a single text area. If the user presses a key while the focus is on the
text area, an alert box is displayed as soon as the key is pressed, showing the type of
event that was fired. The first event handler is onKeyDown, which is followed by an
onKeyPress event handler.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1077
Client-Side 1077
Textarea.onKeyUp
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
onkeyup=”command”
Description
The onKeyUp event handler of an instance of a Textarea object is fired when a key is
released within the text area. Care should be taken when using this event handler
because it is possible to get into an infinite loop when using other events or methods
that are fired when the focus is placed on or away from the text area or other key-
related events are used. The onKeyUp event handler is called after an onKeyPress event
handler.
Example
Listing 8.504 has a single text area. If the user releases a key while the focus is on the
text area, an alert box is displayed as soon as the key is released.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1078
Textarea.onSelect
JavaScript1.0+, JScript1.0+
IE3+, Net6
Syntax
onselect=”command”
Description
The onSelect event handler of an instance of a Textarea object is fired when the text
in the area is highlighted. Care should be taken when using this event handler because
it is possible to get into an infinite loop when using other events or methods that are
fired when the focus is placed on the text area.
NOTE
Note that Netscape defined this function in JavaScript 1.0; however, it was not
fully implemented until Netscape 6 was released. Opera browsers do not support
this function either.
Example
Listing 8.505 has two text areas. If the user highlights the text in the first text area, the
default text of the first text area is written to the second text area.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1079
Client-Side 1079
Listing 8.505 Using the onSelect Event Handler to Set the Text in the
Second Text Box
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Textarea.select()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
textarea.select()
Description
The select() method of the Textarea object selects the text in the text area. Be care-
ful when using this method in conjunction with the blur() and focus() methods. It
can lead to a focus/blur loop where the browser blurs or focuses as soon as it is has
been selected, and vice versa.
Example
Listing 8.506 has a text area and a button. If the user clicks the button, the text inside
the text area will be highlighted. Notice the focus() method had to be used to tell the
browser to actually highlight the text.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1080
Listing 8.506 Using the select() Method to Select the Text in a Text
Area
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Textarea.type
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
Syntax
textarea.type
Description
The type property of an instance of a Textarea object returns the type of the text area.
This always returns textarea.
Example
Listing 8.507 has a text area and a button. When the button is clicked, an alert box is
popped up that displays the type property of the text area.
Client-Side 1081
Textarea.unwatch()
JavaScript 1.2+
Nav4+
Syntax
textarea.unwatch(property)
Description
The unwatch() method of the Textarea object is used to turn off the watch for a par-
ticular property.
Example
Listing 8.508 shows how the unwatch() method is used to stop watching the value
property.
// Watch the value of the Teaxtarea box, then change it, before unwatching.
function check(){
document.myForm.myItem.watch(“value”, alertme);
document.myForm.myItem.value=”Send”;
document.myForm.myItem.unwatch(“value”);
}
</script>
</head>
<body onload=”check()”>
<form name=”myForm”>
<textarea name=”myItem” rows=”3” cols=”30”>Submit</textarea>
</form>
</body>
</html>
Textarea.value
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
textarea.value
Description
The value property of an instance of a Textarea object returns the current value of the
text area. Note that this is not the default value that can be accessed via the
Textarea.defaultValue property and is often used to set the value of a text area.
Example
Listing 8.509 contains a text area and button. You can edit the text in the text area, and
then click the Reset button to reset the text back to the default value.
Listing 8.509 Resetting the Value of a Text Area to the Default Value
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
Client-Side 1083
</script>
</head>
<body>
<form name=”myForm”>
<textarea name=”myTextArea” rows=”6” cols=”50”>
Here is some text in my text area.
</textarea>
<input type=”button” value=”Reset” name=”myButton” onclick=’resetText()’>
</form>
</body>
</html>
Textarea.watch()
JavaScript 1.2+
Nav4+
Syntax
textarea.watch(property, function)
Description
The watch() method of the Textarea object is used to turn on the watch for a partic-
ular property. Any time the specified property is changed after the watch() method
has been called, the specified function is called.
Example
Listing 8.510 shows how the watch() method is used to start watching the value
property.
function check(){
document.myForm.myItem.watch(“value”, alertme);
document.myForm.myItem.value=”Send”;
}
</script>
</head>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1084
untaint()
JavaScript1.1
Nav3
Syntax
untaint(property)
untaint(variable)
untaint(function)
untaint(object)
Description
The untaint() method, a security measure that was only implemented in JavaScript
1.1, allowed a developer to allow return values to be used by and propagated to other
scripts. This method does not change the data element passed to it, but rather returns
an unmarked reference to the element.
Because untaint() and the functionality of data tainting was removed in JavaScript
1.2, you should avoid using this method. You should use it only if you have a specific
security reason for compatibility with Navigator 3 browsers. See Chapter 1 for more
information on the security model that is now used in Navigator browsers.
Example
Listing 8.511 simply untaints a variable that is defined in a separate window.
// -->
</script>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1085
Client-Side 1085
Window
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
Core client-side JavaScript object.
Description
The Window object is one of the top-level JavaScript objects that are created when a
<body>, <frameset>, or <frame> tag is encountered. Instances of this object can also
be created by using the Window.open() method. Table 8.39 lists the properties and
methods associated with the Window object.
Client-Side 1087
Any of the methods or properties of this object can have the instance name left off if it
refers to the window in which they are invoked. Setting the status property, for
instance, would set the status in the current window, whereas setting myWin.status
sets the status in the window named myWin. The only exception to this rule is in using
the location property and the close() and open() methods, which must take the
instance’s name when called within an event handler.
NOTE
Each of the entries for the Window object’s methods and properties in this chapter
will be preceded by the Window object name in its syntax definition.
Example
Listing 8.512 contains a button. When the button is clicked, a new window instance is
created using the open() method. Information is then written to the window before the
stream is closed. There is also a button in the new window to close it.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1089
Client-Side 1089
// Open the window. Give the window instance the name newDoc and
// name the document in the window myWin.
var newWin = open(‘’, ‘myWin’, myFeatures);
newWin.document.writeln(‘<form>’);
newWin.document.writeln(‘<table cellspacing=”0” cellpadding=”0”
border=”1”>’);
newWin.document.writeln(‘<tr valign=”top” bgcolor=”#000099”><td>’);
newWin.document.writeln(‘<font size=”-1” color=”#ffffff”><b>’);
newWin.document.writeln(‘ Readme</b></font>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”top”><td>’);
newWin.document.writeln(‘<textarea cols=”45” rows=”7” wrap=”soft”>’);
newWin.document.writeln(myReadme + ‘</textarea>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”bottom” align=”right”’);
newWin.document.writeln(‘ bgcolor=”#c0c0c0”><td>’);
newWin.document.writeln(‘<input type=”button” value=”Close”’);
newWin.document.writeln(‘ onclick=”window.close()”>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘</table></form>’);
16 0672321416 CH08c 7/24/01 12:32 PM Page 1090
// -->
</script>
</head>
<body>
<form>
<b>Click the following button to open a new window: </b>
<input type=”button” value=”Open” onclick=’openWin()’>
</form>
</body>
</html> >
window.alert()
JavaScript1.0+, JScript1.0
Nav2+, IE3+, Opera3+
Syntax
window.alert(string)
Description
The alert() method of the Window object displays an alert dialog box when invoked.
The value of the string passed to the method is displayed in the box.
Example
Listing 8.513 pops up an alert box when the script is loaded. The result of running this
script can be seen in Figure 8.4.
// -->
</script>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1091
Client-Side 1091
Figure 8.4
An alert box created with the Window.alert() method.
window.atob()
JavaScript1.2
Nav4
Syntax
window.atob(data)
Description
The atob() method of the Window object, which was only implemented in Navigator
4, is used to decode data that was encoded in base-64 encoding.
Example
Listing 8.514 shows how you can encode data using the btoa() method, and then
decode it back using atob().
window.back()
JavaScript1.2+, JScript3.0
Nav4+, IE4+
Syntax
window.back()
Description
The back() method of the Window object simulates the user clicking the Back button
on the browser. It returns the browser’s page or frame to the previous page or frame.
Example
Listing 8.515 has two buttons. One of the buttons takes the browser back one page and
the other button takes it forward. Note that there has to be a back and forward page dur-
ing your session for the button to have somewhere to go.
window.blur()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.blur()
Description
The blur() method of the Window object removes the focus from the window. Be care-
ful when using this method in conjunction with the focus() method of objects. It can
lead to a focus/blur loop, where the browser blurs a focus as soon as it is done, and vice
versa.
Example
Listing 8.516 has two buttons. When the user clicks the Open button, a second, smaller
window is opened. If the Blur button is clicked, the focus is removed from the parent
window and placed on the child window.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1093
Client-Side 1093
Listing 8.516 Using the blur() Method to Remove the Focus from a
Window
<html>
<head>
<script language=”JavaScript” type=”text/javascript”>
<!--
// -->
</script>
</head>
<body>
<form>
<input type=”button” value=”Open” onclick=’openWin()’>
<input type=”button” value=”Blur” onclick=’blurWin()’>
</form>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1094
window.btoa()
JavaScript1.2
Nav4
Syntax
window.btoa(data)
Description
The btoa() method of the Window object, which was only implemented in Navigator
4, is used to encode data in base-64 encoding.
Example
Listing 8.517 shows how you can encode data using the btoa() method, and then
decode it an back using atob().
window.captureEvents()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.captureEvents(event)
window.captureEvents(event1 | event2 | eventN)
16 0672321416 CH08c 7/24/01 12:32 PM Page 1095
Client-Side 1095
Description
The captureEvents() method of the Window object captures all the events of the event
type passed. Because you can capture the events that are natively handled by the lan-
guage itself, programmers can now define a function to handle events in a manner they
want. If you have multiple events that you want to capture, separate them with the pipe
(|) character. The types of events that can be captured are as follows:
• Event.ABORT
• Event.BLUR
• Event.CHANGE
• Event.CLICK
• Event.DBLCLICK
• Event.DRAGDROP
• Event.ERROR
• Event.FOCUS
• Event.KEYDOWN
• Event.KEYPRESS
• Event.KEYUP
• Event.LOAD
• Event.MOUSEDOWN
• Event.MOUSEMOVE
• Event.MOUSEOUT
• Event.MOUSEOVER
• Event.MOUSEUP
• Event.MOVE
• Event.RESET
• Event.RESIZE
• Event.SELECT
• Event.SUBMIT
• Event.UNLOAD
After an event has been captured, you can define a function to replace the built-in
method for handling the event.
Example
Listing 8.518 has a single text box. The script in the <head> of the document specifies
a function to handle all onClick events in the window. To be able to do this, the
captureEvents() method had to be used to capture all events of type Event.CLICK.
When the page itself is clicked, a counter, which is displayed in the text box, is incre-
mented.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1096
// Pass all click events to the onClick event of the text box.
window.document.myForm.myText.handleEvent(e);
window.clearInterval()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.clearInterval(interval)
16 0672321416 CH08c 7/24/01 12:32 PM Page 1097
Client-Side 1097
Description
The clearInterval() method of the Window object clears the interval that is passed to
the method. The interval that is passed has to be previously defined using the
setInterval() method.
Example
Listing 8.519 sets an interval in the <head> of the document that displays a counter in
a text box on the page. An interval is set to update the counter in the text box every five
seconds. There is also a button on the page that can be clicked to clear the interval and
stop the counting.
// -->
</script>
</head>
<body onload=”startCounter()”>
<form name=”myForm”>
<input type=”text” size=”2” value=”” name=”myText”>
<input type=”button” value=”Clear Interval” onclick=”stopCounter()”>
</form>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1098
window.clearTimeout()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.clearTimeout(timeout)
Description
The clearTimeout() method of the Window object clears the timeout passed to the
method. The timeout that is passed has to be previously defined using the
setTimeout() method.
Example
Listing 8.520 has a button and text box. By the default, the time will be displayed in
the text box after five seconds. This is done using the setTimeout() method. If the but-
ton is clicked, a function is called that invokes the clearTimeout() method preventing
the time time from being displayed in the text box.
// -->
</script>
</head>
<body>
<form name=”myForm”>
<input type=”text” size=”2” value=”” name=”myText”>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1099
Client-Side 1099
window.close()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.close()
Description
The close() method of the Window object is used to close browser windows. Even
though this method was first introduced in JavaScript 1.0, there have been some
changes. In the first version, this method could be used to close any window. In
JavaScript 1.1, it was restricted to close only windows opened using JavaScript. In
JavaScript 1.2, you must have the UniversalBrowserWrite privilege to uncondition-
ally close a window.
Example
Listing 8.521 has a button that opens a window. Within the opened window there is a
Close button. Clicking this button invokes the close() method and closes the browser
window.
newWin.document.writeln(‘<form>’);
newWin.document.writeln(‘<table cellspacing=”0” cellpadding=”0”
border=”1”>’);
newWin.document.writeln(‘<tr valign=”top” bgcolor=”#000099”><td>’);
newWin.document.writeln(‘<font size=”-1” color=”#ffffff”><b>’);
newWin.document.writeln(‘ Readme</b></font>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”top”><td>’);
newWin.document.writeln(‘<textarea cols=”45” rows=”7” wrap=”soft”>’);
newWin.dpcument.writeln(myReadme + ‘</textarea>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”bottom” align=”right”);
newWin.document.writeln(‘ bgcolor=”#c0c0c0”><td>’);
// Write the close() method on the new window. Invoke it with an onClick
// event.
newWin.document.writeln(‘<input type=”button” value=”Close”);
newWin.document.writeln(‘ onclick=”window.close()”>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘</table></form>’);
// Close the stream to the document and bring the window to the front.
newWin.document.close();
newWin.focus();
}
// -->
</script>
</head>
<body>
<form>
<b>Click the following button to open a new window: </b>
<input type=”button” value=”Open” onclick=’openWin()’>
</form>
</body>
</html>
window.closed
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
Syntax
window.closed
16 0672321416 CH08c 7/24/01 12:32 PM Page 1101
Client-Side 1101
Description
The closed property of the Window object returns a Boolean value specifying whether
the window instance it is referencing is closed. If the window is still open, the property
returns false. If it is closed, the property returns true.
Example
Listing 8.522 has two buttons. When the Open button is clicked, a second window is
opened and focused. When the Check button is clicked, the script checks to see whether
the window is still open. If it is, the text in the text area of the second window is
changed. If it is not, an alert dialog box is displayed.
// Open the window. Give the window instance the name newWin and
// name the document in the window myDoc.
newWin = open(‘’, ‘myDoc’, myFeatures);
newWin.document.writeln(‘<form name=”secondForm”>’);
newWin.document.writeln(‘<table cellspacing=”0” cellpadding=”0”
border=”1”>’);
newWin.document.writeln(‘<tr valign=”top” bgcolor=”#000099”><td>’);
newWin.document.writeln(‘<font size=”-1” color=”#ffffff”><b>’);
newWin.document.writeln(‘ Readme</b></font>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”top”><td>’);
newWin.document.writeln(‘<textarea name=”myTextArea” cols=”45” rows=”7”’);
newWin.document.writeln(‘ wrap=”soft”>’ + myReadme + ‘</textarea>’);
newWin.document.writeln(‘</td></tr>’);
16 0672321416 CH08c 7/24/01 12:32 PM Page 1102
// Close the stream to the document and bring the window to the front.
newWin.document.close();
newWin.focus();
}
function checkWin(){
// Use the closed property to see if the window has been closed.
if(newWin.closed){
alert(“Sorry, the window has been closed.”);
}else{
var myText = “This window is still opened”;
newWin.document.secondForm.myTextArea.value = myText;
newWin.focus();
}
}
// -->
</script>
</head>
<body>
<form>
<input type=”button” value=”Open” onclick=’openWin()’>
<input type=”button” value=”Check” onclick=’checkWin()’>
</form>
</body>
</html>
window.confirm()
JavaScript1.0+, JScript1.0
Nav2+, IE3+, Opera3+
Syntax
window.confirm(string)
Description
The confirm() method of the Window object displays a confirmation dialog box when
invoked. The value of the string passed to the method is displayed in the box. This box
will contain both an OK and a Cancel button. The method returns a Boolean value of
true if the user clicks OK and false if the user clicks Cancel.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1103
Client-Side 1103
Example
Listing 8.523 pops up a confirmation box when the script is loaded to see whether the
user wishes to proceed. After the user makes a decision, the script writes his choice to
the page. The result of running this script can be seen in Figure 8.5.
// -->
</script>
Figure 8.5
A confirmation box created with the Window.confirm() method.
window.crypto
JavaScript1.2
Nav4
Syntax
window.crypto.method
Description
The crypto property of the Window object is used to access the encryption functions
available within Navigator 4.
Example
Listing 8.524 shows how you can use the crypto property to access the random()
method within Navigator’s encryption features.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1104
window.crypto.random()
JavaScript1.2
Nav4
Syntax
window.crypto.random(num)
Description
The random method of the window.crypto object is used to create a random number of
length num in bytes. This method is part of the encryption functions available within the
Navigator 4.
Example
Listing 8.525 shows how you can use the crypto property to access the random()
method within Navigator’s encryption features.
window.crypto.signText()
JavaScript1.2
Nav4
16 0672321416 CH08c 7/24/01 12:32 PM Page 1105
Client-Side 1105
Syntax
window.crypto.signText(text, style)
window.crypto.signText(text, style, authority1, ..., authorityN)
Description
The signText() method of the window.crypto object is used to sign text. Depending
on the style of signing, which can be ask or auto, the browser might pop up a dialog
with a list of possible certificates to sign the text with. You can optionally pass 1 or
more authority arguments that will allow you to pass Certificate Authorities.
After the data has been encoded and sent to the server, the server will decode and ver-
ify it. If a failure occurs, one of the following codes will be returned:
• error: noMatchingCert—Specifies that the user’s certificate does not match
one of the passed authority arguments.
• error: userCancel—Specifies that the user cancelled the ask dialog box with-
out submitting a certificate.
• error: internalError—Specifies that an internal error has occurred while
processing the data.
Example
Listing 8.526 prompts the user for some text, and then prompts him before signing the
text. After being signed, the text could then be passed to the server.
window.defaultStatus
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.defaultStatus = string
16 0672321416 CH08c 7/24/01 12:32 PM Page 1106
Description
The defaultStatus property of the Window object reflects the message that is dis-
played in the status bar of the browser. Note that in JavaScript 1.1, this property was
tainted. See Chapter 1 for more information on JavaScript security and data tainting.
Example
Listing 8.527 shows how you can set the default status to be displayed after a document
has finished loading. This is done in conjunction with the onLoad event handler within
the <body> tag.
window.disableExternalCapture()
JavaScript1.2+
Nav4+
Syntax
window.disableExternalCapture()
Description
The disableExternalCapture() method of the Window object disables any external
event capturing set up using the enableExternalCapture() method. The functionality
of this method provides the capturing of events in frames loaded from a different
server. Before you can enable the capturing of these external events, you must first
obtain UniversalBrowserWrite privileges. After they have been obtained and the
method has been invoked, use the Window.captureEvents() method to specify the
events you want to capture.
NOTE
For more information on privileges, JavaScript security, and signed scripts, see
Chapter 1.
Example
Listing 8.528 enables external event capturing when the document loads. The docu-
ment itself has a button that, when clicked, calls a function to disable the external event
captures.
Client-Side 1107
window.document
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
Creates Instance of Document Object.
window.document.event
window.document.method()
window.document.property
Description
The document property, which is a child object of the Window object, is a core
JavaScript object that is created when instances of the <body> tag are encountered. The
properties, methods, and events associated with this object are in Table 8.40.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1108
Client-Side 1109
See the entries in this chapter for the Document object for more information on each of
these events, methods, and properties.
Example
Listing 8.529 uses the write() method of the document property to write text to the
user’s page.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1110
// -->
</script>
window.enableExternalCapture()
JavaScript1.2+
Nav4+
Syntax
window.enableExternalCapture(event)
Description
The enableExternalCapture() method of the Window object enables external event
capturing of the event that is passed to the method. This method provides the captur-
ing of events in frames loaded from a different server. Before you can enable the cap-
turing of these external events, you must first obtain UniversalBrowserWrite
privilege. Obtaining this privilege will send a security dialog box to the user to decide
whether to accept the request.
After it has been obtained and the method has been invoked, you use the
Window.captureEvents() method to specify the events you want to capture. To
remove the ability to capture these events, you can invoke the
Window.disableExternalCapture() method. The types of events that can be captured
are as follows:
• Event.ABORT
• Event.BLUR
• Event.CHANGE
• Event.CLICK
• Event.DBLCLICK
• Event.DRAGDROP
• Event.ERROR
• Event.FOCUS
• Event.KEYDOWN
• Event.KEYPRESS
• Event.KEYUP
• Event.LOAD
• Event.MOUSEDOWN
• Event.MOUSEMOVE
• Event.MOUSEOUT
16 0672321416 CH08c 7/24/01 12:32 PM Page 1111
Client-Side 1111
• Event.MOUSEOVER
• Event.MOUSEUP
• Event.MOVE
• Event.RESET
• Event.RESIZE
• Event.SELECT
• Event.SUBMIT
• Event.UNLOAD
NOTE
For more information on privileges, JavaScript security, and signed scripts, see
Chapter 1.
Example
Listing 8.530 enables external event capturing when the document loads.
// -->
</script>
window.find()
JavaScript1.2, JScript3.0
Nav4, IE4
Syntax
window.find()
Description
The find() method of the Window object displays a find dialog box when invoked. This
allows a user to search for a string in the page from which it was invoked.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1112
NOTE
This method was only supported in the version 4 browsers, and has been removed
since then.
Example
Listing 8.531 has a function that pops up a Find box when it is called.
Listing 8.531 A Find Box That Can Be Used to Search for Text in the
Document
<script language=”JavaScript1.2” type=”text/javascript”>
<!--
// -->
</script>
window.focus()
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
Syntax
window.focus()
Description
The focus() method of the Window object places focus on the window. Be careful
when using this method in conjunction with the blur() method of objects. It can lead
to a focus/blur loop, where the browser blurs a focus as soon as it is done, and vice
versa.
Example
Listing 8.532 has a button. When the user clicks the Open button, a second, smaller
window is opened, and the focus is placed back on the parent window.
Client-Side 1113
// -->
</script>
<body>
<form>
<input type=”button” value=”Open” onclick=’openWin()’>
</form>
</body>
</html>
window.forward()
JavaScript1.2+, Jscript3.0
Nav4+, IE4+
Syntax
window.forward()
Description
The forward() method of the Window object simulates the user clicking the Forward
button on the browser. It returns the browser’s page or frame to the next page or frame
in its history.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1114
Example
Listing 8.533 has two buttons. One of the buttons takes the browser back one page and
the other button takes it forward. Note that there has to be a back and forward page dur-
ing your session for the button to have somewhere to go.
Listing 8.533 Using the forward() Method to Take the User to the Next
Page in His History
<html>
<body>
<form>
<input type=”button” value=”Back” onclick=”window.back()”>
<input type=”button” value=”Forward” onclick=”window.forward()”>
</form>
</body>
</html>
window.frames
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.frames[“frameName”]
window.frames[num]
Description
The frames property of the Window object contains an array that stores each frame
instance, created with the <frame> tag, in a document. Array entries of the child frame
can be referenced either by index number or by the name assigned by the name attribute
of the <frame> tag.
Example
Listing 8.534 uses the length property of frames array and a for loop to access the
name of each frame in the window. This information is then written to the document
window.
Client-Side 1115
window.frames.length
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.frames[“frameName”].length
window.frames[num].length
Description
The length sub property of the frames property of the Window object contains the num-
ber of frame instances in a document created with the <frame> tag.
Example
Listing 8.535 uses the length property of the frames array and a for loop to access the
name of each frame in the window. This information is then written to the document
window.
window.handleEvent()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.object.handleEvent(event)
Description
The handleEvent() method of the Window object invokes the handler for the event
specified of the specified object. This method was added in JavaScript 1.2.
Example
Listing 8.536 has a single text box. The script tells the browser that it wants to inter-
cept all Click events and that it wants the myClickHandler function to handle them.
Within this function, the handleEvent() method of the text box has been specified to
handle the click.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1116
When the user clicks anywhere on the page, the onClick event handler in the <input
type=”text”> tag calls a function to change the text in the text box. The change is
nothing more than a simple number that is incremented, counting the number of times
the page has been clicked.
// Pass all click events to the onClick event of the text box.
window.document.myForm.myText.handleEvent(e);
}
window.history
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
16 0672321416 CH08c 7/24/01 12:32 PM Page 1117
Client-Side 1117
Syntax
window.history[num]
window.history.method()
window.history.property
Description
The history property of the Window object is actually one of the core JavaScript
objects. This object contains an array of the names and URLs of the pages the window
has visited. A specific URL in the history array can be accessed by specifying the
indexed location, num, that represents the URL about which you want to retrieve infor-
mation.
Also, as defined in the syntax definition, the methods and properties of this object are
also accessible for programming use. Table 8.41 has a list of each of these, followed by
a description.
For more information on the History object and its properties and methods, see its
entry in this chapter.
Example
Listing 8.537 has two buttons that allow a user to move forward and back in his history.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1118
window.home()
JavaScript1.2+, JScript3.0
Nav4+, IE4+
Syntax
window.home()
Description
The home() method of the Window object simulates the user clicking the Home button
on the browser. It takes the browser to the user’s specified home page.
Example
Listing 8.538 has a single button that, when clicked, takes the browser to the user’s
home page.
Listing 8.538 Using the home() Method to Go to the User’s Home Page
<form>
<h3>Home James!</h3>
<input type=”button” value=”Home” onclick=”window.home()”>
</form>
window.innerHeight
JavaScript1.2+
Nav4+
Syntax
window.innerHeight
Description
The innerHeight property of the Window object references the pixel height of the doc-
ument within the browser’s frame. This does not include any of the toolbars or other
“chrome” that makes up the frame itself.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1119
Client-Side 1119
Example
Listing 8.539 has a button that, when clicked, opens up a second, smaller window. The
innerHeight property is written to this new window.
// Open the window. Give the window instance the name newDoc and
// name the document in the window myDoc.
var newWin = open(‘’, ‘myDoc’, myFeatures);
// Write the window height and width properties to the new window.
newWin.document.writeln(‘<h4>Properties for this Window</h4>’);
newWin.document.writeln(‘innerHeight: ‘ + newWin.innerHeight + ‘<br>’);
newWin.document.writeln(‘innerWidth: ‘ + newWin.innerWidth + ‘<br>’);
newWin.document.writeln(‘outerHeight: ‘ + newWin.outerHeight + ‘<br>’);
newWin.document.writeln(‘outerWidth: ‘ + newWin.outerWidth + ‘<br>’);
newWin.document.writeln(‘<form>’);
newWin.document.writeln(‘<input type=”button” value=”Close”’);
newWin.document.writeln(‘ onclick=”window.close()”>’);
newWin.document.writeln(‘</form>’);
}
// -->
</script>
</head>
<body>
<form>
<input type=”button” value=”Open” onclick=”openWin()”>
</form>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1120
window.innerWidth
JavaScript1.2+
Nav4+
Syntax
window.innerWidth
Description
The innerWidth property of the Window object references the pixel width of the docu-
ment within the browser’s frame. This does not include any of the toolbars or other
“chrome” that makes up the frame itself.
Example
Listing 8.540 has a button that, when clicked, opens up a second, smaller window. The
innerWidth property is written to this new window.
// Open the window. Give the window instance the name newWin and
// name the document in the window myDoc.
var newWin = open(‘’, ‘myDoc’, myFeatures);
// Write the window height and width properties to the new window.
newWin.document.writeln(‘<h4>Properties for this Window</h4>’);
newWin.document.writeln(‘innerHeight: ‘ + newWin.innerHeight + ‘<br>’);
newWin.document.writeln(‘innerWidth: ‘ + newWin.innerWidth + ‘<br>’);
newWin.document.writeln(‘outerHeight: ‘ + newWin.outerHeight + ‘<br>’);
newWin.document.writeln(‘outerWidth: ‘ + newWin.outerWidth + ‘<br>’);
newWin.document.writeln(‘<form>’);
newWin.document.writeln(‘<input type=”button” value=”Close”’);
newWin.document.writeln(‘ onclick=”window.close()”>’);
newWin.document.writeln(‘</form>’);
16 0672321416 CH08c 7/24/01 12:32 PM Page 1121
Client-Side 1121
}
// -->
</script>
</head>
<body>
<form>
<input type=”button” value=”Open” onclick=”openWin()”>
</form>
</body>
</html>
window.length
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.length
Description
The length property of the Window object represents the number of frames within a
window. This returns the same results as Window.frames.length.
Example
Listing 8.541 shows a function that can be used to return the number of frames in a
window.
// -->
</script>
16 0672321416 CH08c 7/24/01 12:32 PM Page 1122
window.location
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.location
Description
The location property of the Window object returns the current URL of the document
in the window.
Example
Listing 8.542 pops up an alert box that contains the URL of the current window.
// -->
</script>
window.locationbar
JavaScript1.2+
Nav4+
Syntax
window.locationbar.property
Description
The locationbar property of the Window object is, to some degree, an object itself. The
real use of this property is to access its visible property to determine whether the loca-
tion bar is visible to the user.
NOTE
As of this writing, the locationbar property only has one subproperty: visible.
Example
See the example of Window.locationbar.visible for an example of using the
locationbar property.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1123
Client-Side 1123
window.locationbar.visible
JavaScript1.2+
Nav4+
Syntax
window.locationbar.visible
Description
The visible subproperty of the locationbar property of the Window is used to deter-
mine whether the location bar is visible to the user. If it is visible, the property returns
true. It returns false if the bar is not visible.
Example
Listing 8.543 determines whether several of the browser bars are displayed. In the
example, you will see whether the location bar is visible by using the visible prop-
erty.
// -->
</script>
window.menubar
JavaScript1.2+
Nav4+
Syntax
window.menubar.property
16 0672321416 CH08c 7/24/01 12:32 PM Page 1124
Description
The menubar property of the Window object is, to some degree, an object itself. The real
use of this property is to access its visible property to determine whether the menu
bar is visible to the user.
NOTE
As of this writing, the menubar property only has one subproperty: visible.
Example
See the example of Window.menubar.visible for an example of using the menubar
property.
window.menubar.visible
JavaScript1.2+
Nav4+
Syntax
window.menubar.visible
Description
The visible subproperty of the menubar property of the Window is used to determine
whether the menu bar is visible to the user. If it is visible, the property returns true. It
returns false if the bar is not visible.
Example
Listing 8.544 determines whether several of the browser bars are displayed. In the
example, you will see whether the menu bar is visible by using the visible property.
Client-Side 1125
// -->
</script>
window.moveBy()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.moveBy(numHorz, numVert)
Description
The moveBy() method of the Window object moves the specified window by the num-
ber of pixels passed to the method. As shown in the syntax definition, the first numeric
value passed to the method represents the number of horizontal pixels you want to
move the window, whereas the second numeric value represents the vertical number of
pixels.
If the numbers passed are positive, the window is moved to the right horizontally, and
down vertically. Negative numbers move the window in the opposite direction.
Example
Listing 8.545 has four buttons: Up, Down, Right, and Left. If you click these buttons,
the window the document is loaded in will move one pixel at a time in that direction.
window.moveTo()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.moveTo(numX, numY)
Description
The moveTo() method of the Window object moves the specified window to the speci-
fied location passed to the method. As shown in the syntax definition, the first numeric
value passed to the method represents the x coordinate to which you want to move the
window, whereas the second numeric value represents the y coordinate.
16 0672321416 CH08c 7/24/01 12:32 PM Page 1127
Client-Side 1127
Example
Listing 8.546 has two text fields and a button. If the user enters an integer value in each
of the text fields and clicks the button, the window will move to that location.
window.name
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.name
Description
The name property of an instance of a Window object returns the name of the window.
This property contains the name specified when new windows are created using the
Window.open() method. In JavaScript 1.0, this property was read only, but this was
16 0672321416 CH08c 7/24/01 12:32 PM Page 1128
changed in JavaScript 1.1 so that you can assign a name to a window not created with
the Window.open() method. This property was tainted in JavaScript 1.1 as well.
Example
Listing 8.547 has a button that launches a second window. The name of the window is
written to it using the name property of the Window object.
// Open the window. Give the window instance the name newWin and
// name the document in the window myDoc.
var newWin = open(‘’, ‘myDoc’, myFeatures);
}
// -->
</script>
</head>
<body>
<form>
<input type=”button” value=”Open” onclick=”openWin()”>
</form>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1129
Client-Side 1129
window.offscreenBuffering
JavaScript1.2, JScript3.0+
Nav4+, IE4+
Syntax
window.offscreenBuffering = boolean
Description
The offscreenBuffering property of the Window object is used to explicitly instruct
the browser whether to buffer data offscreen before displaying. Without doing this, a
user’s window might flicker as the page is being drawn. This property simply takes a
boolean value of true or false to set it.
Example
Listing 8.548 shows how you can instruct the browser to not buffer data offscreen.
//-->
</script>
window.onBlur
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onblur=”command”
Description
The onBlur event handler is a property of a Window object and is fired when the focus
is moved away from that particular window instance. Care should be taken when using
this event handler because it is possible to get into an infinite loop when using the
onFocus event handler or the focus() method. Note that when this event handler is
called within the <body> tag, it is overridden if a <frame> tag that also uses this event
handler loaded the document.
NOTE
Some Navigator 3 browsers do not fully support this event handler when called in
a <frameset> tag.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1130
Example
Listing 8.549 has a frame set with two frames. The first frame, toc, has the onBlur
event handler specified in its tag. When focus leaves this frame, the event is fired and
the myBlurFunc() function will be called.
window.onDragDrop
JavaScript1.2+
Nav4+
Syntax
ondragdrop=”command”
Description
The onDragDrop event handler of a property of a Window object is fired when the user
drops an object, such as a file, on that particular window instance.
Example
In Listing 8.550, if you try to drop a new file on to the browser when this page is
loaded, you will be asked to confirm this operation. If you accept, the page will load.
If you cancel, the page will not load.
window.onError
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
Syntax
onerror=”command”
16 0672321416 CH08c 7/24/01 12:33 PM Page 1131
Client-Side 1131
Description
The onError event handler of the Window object is fired when an error occurs loading
the page. You might find this useful to try and reload the page, using the reload()
method of the Location object.
Example
Listing 8.551 is an example of placing the onError event handler in the <body> tag. If
there is an error when loading this page, an alert box will be displayed to the user.
window.onFocus
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onfocus=”command”
Description
The onFocus event handler of a property of a Window object is fired when the focus is
placed on that particular window instance. Care should be taken when using this event
handler because it is possible to get into an infinite loop when using onBlur event han-
dler or blur() method. Note that when this event handler is called within the <body>
tag, it is overridden if a <frame> tag that also uses this event handler loaded the docu-
ment.
NOTE
Some Navigator 3 browsers do not fully support this event handler when called in
a <frameset> tag.
Example
Listing 8.552 has a frame set with two frames. The first frame, toc, has the onFocus
event handler specified in its tag. When the focus leaves this frame, the event is fired
and the myFocusFunc() function (not shown) will be called.
window.onLoad
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
onload=”command”
Description
The onLoad event handler of a property of a Window object is fired when the page has
finished loading in that particular window instance.
NOTE
The onLoad event handler in the <body> of a document that is loaded in a frame
will fire before an event handler loaded in the <frameset> tag that loaded the
document.
Example
Listing 8.553 pops up an alert box when the page has finished loading.
window.onMove
JavaScript1.2+
Nav4+
Syntax
onmove=”command”
Description
The onMove event handler of a property of a Window object is fired when the window it
is referenced in is moved. The user physically moving the window or a script moving
it can fire this event.
Example
Listing 8.554 pops up an alert box if the user tries to move the window.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1133
Client-Side 1133
window.onResize
JavaScript1.2+
Nav4+
Syntax
onresize=”command”
Description
The onResize event handler of a property of a Window object is fired when the window
it is referenced in is resized. The user physically resizing the window or a script resiz-
ing it can fire this event.
Example
Listing 8.555 pops up an alert box if the user tries to resize the window.
window.onUnload
JavaScript 1.0+, JScript 1.0+
Nav2+, IE3+, Opera3+
Syntax
onunload=”command”
Description
The onUnload event handler of a property of a Window object is fired when the page is
unloaded in that particular window instance. This occurs when the user leaves the page
for another page.
NOTE
The onUnLoad event handler in the <body> of a document that is loaded in a
frame will fire before an event handler loaded in the <frameset> tag that loaded
the document.
Example
Listing 8.556 pops up an alert box when the user leaves the page.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1134
window.open()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.open(pageURL, name, parameters)
Description
The open() method of the Window object creates a new instance of a window. It loads
the pageURL passed to the method in a window based on the parameters specified. The
action attribute of the <form> tag and the target attribute of the <a> tag can reference
the window by the name passed.
Most of the parameters passed, which are listed without spaces and commas, are tog-
gled on and off by setting them to yes or no. It is also possible to use 1 or 0 to turn
these features on or off. Either way, you should be consistent across each of the
options. Table 8.42 has the different parameters that can be passed and how to turn
them on and off.
NOTE
If you place spaces in the parameter string, the options will not work. Be sure to
comma separate each of these options and do not insert any spaces.
Client-Side 1135
NOTE
It is possible to open windows that are not on the physical screen. However, this is
a secure feature and must be in a signed script to implement.
Example
Listing 8.557 has a single button that opens a new window when clicked. As you can
see in the creation of the window, various parameters are passed that define how the
window should look when opened.
// Open the window. Give the window instance the name newWin and
// name the document in the window myDoc.
var newWin = open(‘’, ‘myDoc’, myFeatures);
newWin.document.writeln(‘<form>’);
newWin.document.writeln(‘<table cellspacing=”0” cellpadding=”0”
border=”1”>’);
newWin.document.writeln(‘<tr valign=”top” bgcolor=”#000099”><td>’);
newWin.document.writeln(‘<font size=”-1” color=”#ffffff”><b>’);
newWin.document.writeln(‘ Readme</b></font>’);
16 0672321416 CH08c 7/24/01 12:33 PM Page 1137
Client-Side 1137
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”top”><td>’);
newWin.document.writeln(‘<textarea cols=”45” rows=”7” wrap=”soft”>’);
newWin.document.writeln(myReadme + ‘</textarea>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”bottom” align=”right”’);
newWin.document.writeln(‘ bgcolor=”#c0c0c0”><td>’);
newWin.document.writeln(‘<input type=”button” value=”Close”’);
newWin.document.writeln(‘ onclick=”window.close()”>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘</table></form>’);
// Close the stream to the document and bring the window to the front.
newWin.document.close();
newWin.focus();
}
// -->
</script>
<body>
<form>
<b>Click the following button to open a new window: </b>
<input type=”button” value=”Open” onclick=’openWin()’>
</form>
</body>
</html>
window.opener
JavaScript1.1+, JScript1.0+
Nav3+, IE3+, Opera3+
Syntax
window.opener
window.opener.method
window.opener.property
Description
The opener property of the Window object corresponds to the window that opens the
window from which the property was accessed. When accessed by a child window, it
returns the parent window. With this property, you can then invoke methods and access
properties of the Window object on the “opener” window. This property can also be set
in scripts that allow the browser to clean up the reference to the parent window if it is
closed before the child window. Most browsers have limits on the number of open win-
dows they can have, and, by cleaning up these closed windows, you are able to regain
the ability to open more windows if your limit has been reached. This is accomplished
by setting the opener property to null.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1138
Example
Listing 8.558 has a button that opens a second window when clicked. In the second
window, there is a button that closes the parent window by referencing it via the opener
property. After the close() method has been called on this window, the opener prop-
erty is set to null to clean up the parent window.
Listing 8.558 Using the opener Property to Return the Parent Window
<html>
<head>
// Open the window. Give the window instance the name newWin and
// name the document in the window myDoc.
var newWin = open(‘’, ‘myDoc’, myFeatures);
newWin.document.writeln(‘<form>’);
newWin.document.writeln(‘<table cellspacing=”0” cellpadding=”0”
border=”1”>’);
newWin.document.writeln(‘<tr valign=”top” bgcolor=”#000099”><td>’);
newWin.document.writeln(‘<font size=”-1” color=”#ffffff”><b>’);
newWin.document.writeln(‘ Readme</b></font>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”top”><td>’);
newWin.document.writeln(‘<textarea cols=”45” rows=”7” wrap=”soft”>’);
newWin.document.writeln(myReadme + ‘</textarea>’);
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘<tr valign=”bottom” align=”right” ‘);
newWin.document.writeln(‘bgcolor=”#c0c0c0”><td>’);
Client-Side 1139
newWin.document.writeln(‘</td></tr>’);
newWin.document.writeln(‘</table></form>’);
// Close the stream to the document and bring the window to the front.
newWin.document.close();
newWin.focus();
}
// -->
</script>
</head>
<body>
<form>
<b>Click the following button to open a new window: </b>
<input type=”button” value=”Open” onclick=’openWin()’>
</form>
</body>
</html>
window.outerHeight
JavaScript1.2+
Nav4+
Syntax
window.outerHeight
Description
The outerHeight property of the Window object references the pixel height of the
browser’s frame. This includes any of the toolbars or other “chrome” that makes up the
frame itself.
Example
Listing 8.559 has a button that, when clicked, opens up a second, smaller window. The
outerHeight property is written to this new window.
// Open the window. Give the window instance the name newWin and
// name the document in the window myDoc.
var newWin = open(‘’, ‘myDoc’, myFeatures);
// Write the window height and width properties to the new window.
newWin.document.writeln(‘<h4>Properties for this Window</h4>’);
newWin.document.writeln(‘innerHeight: ‘ + newWin.innerHeight + ‘<br>’);
newWin.document.writeln(‘innerWidth: ‘ + newWin.innerWidth + ‘<br>’);
newWin.document.writeln(‘outerHeight: ‘ + newWin.outerHeight + ‘<br>’);
newWin.document.writeln(‘outerWidth: ‘ + newWin.outerWidth + ‘<br>’);
newWin.document.writeln(‘<form>’);
newWin.document.writeln(‘<input type=”button” value=”Close”’);
newWin.document.writeln(‘ onclick=”window.close()”>’);
newWin.document.writeln(‘</form>’);
}
// -->
</script>
</head>
<body>
<form>
<input type=”button” value=”Open” onclick=”openWin()”>
</form>
</body>
</html>
window.outerWidth
JavaScript1.2+
Nav4+
Syntax
window.outerWidth
Description
The outerWidth property of the Window object references the pixel width of the
browser’s frame. This includes any of the toolbars or other “chrome” that make up the
frame itself.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1141
Client-Side 1141
Example
Listing 8.560 has a button that, when clicked, opens up a second, smaller window. The
outerWidth property is written to this new window.
// Open the window. Give the window instance the name newWin and
// name the document in the window myDoc.
var newWin = open(‘’, ‘myDoc’, myFeatures);
// Write the window height and width properties to the new window.
newWin.document.writeln(‘<h4>Properties for this Window</h4>’);
newWin.document.writeln(‘innerHeight: ‘ + newWin.innerHeight + ‘<br>’);
newWin.document.writeln(‘innerWidth: ‘ + newWin.innerWidth + ‘<br>’);
newWin.document.writeln(‘outerHeight: ‘ + newWin.outerHeight + ‘<br>’);
newWin.document.writeln(‘outerWidth: ‘ + newWin.outerWidth + ‘<br>’);
newWin.document.writeln(‘<form>’);
newWin.document.writeln(‘<input type=”button” value=”Close”’);
newWin.document.writeln(‘ onclick=”window.close()”>’);
newWin.document.writeln(‘</form>’);
}
// -->
</script>
</head>
<body>
<form>
<input type=”button” value=”Open” onclick=”openWin()”>
</form>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1142
window.pageXOffset
JavaScript1.2+, JScript3+
Nav4+, IE4+
Syntax
window.pageXOffset
Description
The pageXOffset property of the Window object reflects the current horizontal pixel
location of the top-left corner of the document in the window. In chromeless windows,
this property can be referenced if you are moving a window with the moveTo() method
before the actual move is made to see whether the window needs to be moved. It is also
useful when using the scrollTo() method because it returns the current location of the
viewable document in relation to the whole page.
Example
Listing 8.561 has a button that, when clicked, displays the current x and y coordinates
of the window.
// -->
</script>
</head>
<body>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1143
Client-Side 1143
<form>
<input type=”button” value=”Show Location” onclick=”showLocation()”>
</form>
</body>
</html>
window.pageYOffset
JavaScript1.2+, JScript3+
Nav4+, IE4+
Syntax
window.pageYOffset
Description
The pageYOffset property of the Window object reflects the current vertical pixel loca-
tion of the top-left corner of the document in the window. In chromeless windows, this
property can be referenced if you are moving a window with the moveTo() method
before the actual move is made to see whether the window needs to be moved. It is also
useful when using the scrollTo() method because it returns the current location of the
viewable document in relation to the whole page.
Example
Listing 8.562 has a button that, when clicked, displays the current x and y coordinates
of the window.
// -->
</script>
</head>
<body>
<form>
<input type=”button” value=”Show Location” onclick=”showLocation()”>
</form>
</body>
</html>
window.parent
JavaScript1.0+, JScript1.0
Nav2+, IE3+, Opera3+
Syntax
window.parent.parent[num]
window.parent.frameName
Description
The parent property of the Window object contains a reference to the parent window of
any frames that are loaded. In the instance where Frame A loads a page with a <frame-
set> with Frame A.1 and A.2, the parent of the documents in A.1 and A.2 is Frame A.
Frame A’s parent is the top level window.
The referencing of these sibling frames can either be done using the frames array and
passing an index number, or you can directly reference a frame using the name that is
assigned by the name attribute of the <frame> tag.
Example
Listing 8.563 shows how to reference the parent of the third frame on a page.
window.personalbar
JavaScript1.2+
Nav4+
Syntax
window.personalbar.property
16 0672321416 CH08c 7/24/01 12:33 PM Page 1145
Client-Side 1145
Description
The personalbar property of the Window object is, to some degree, an object itself. The
real use of this property is to access its visible property to determine whether the per-
sonal bar is visible to the user.
NOTE
As of this writing, the personalbar property only has one subproperty: visible.
Example
Listing 8.564 determines whether several of the browser bars are displayed. In the
example, you will see whether the personal bar is visible by using the visible prop-
erty.
// -->
</script>
window.personalbar.visible
JavaScript1.2+
Nav4+
Syntax
window.personalbar.visible
Description
The visible subproperty of the personalbar property of the Window is used to deter-
mine whether the personal bar is visible to the user. If it is visible, the property returns
true. It returns false if the bar is not visible.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1146
Example
Listing 8.565 determines whether several of the browser bars are displayed. In the
example, you will see whether the personal bar is visible by using the visible prop-
erty.
// -->
</script>
window.print()
JavaScript 1.2+, JScript 3.0+
Nav4+, IE4+
Syntax
window.print()
Description
The print() method of the Window object simulates the user clicking the Print button
on the browser. It tells the browser to open the Print dialog box to print the current
page.
Example
Listing 8.566 has a button. Clicking the button will tell the browser to open the Print
dialog box to allow the user to print the current page.
Listing 8.566 Using the print() Method to Print the Current Page
<html>
<body>
<form>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1147
Client-Side 1147
window.prompt()
JavaScript1.0+, JScript1.0
Nav2+, IE3+, Opera3+
Syntax
window.prompt(string1, string2)
Description
The prompt() method of the Window object displays a prompt dialog box when
invoked. The value of string1 passed to the method is displayed in the box, and the
value of string2 is contained in the text field of the prompt dialog box. The returned
value of this method is the text in the text field.
Example
Listing 8.567 pops up a prompt box when the script is loaded, asking the user for a
password. If the correct password is entered, the page finishes loading. The result of
running this script can be seen in Figure 8.6.
// Keep asking the user for a password until they get it right.
while(prompt(‘Please enter your password’, ‘HERE’) != ‘admin’){
alert(‘That was an incorrect response, please try again’);
}
// -->
</script>
Figure 8.6
An alert box created with the Window.prompt() method.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1148
window.releaseEvents()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.releaseEvents(event)
window.releaseEvents(event1 | event2 | eventN)
Description
The releaseEvents() method of the Window object releases all previously captured
events of the event type passed. These events can be captured with the
Window.captureEvents() method. The events that can be released are as follows:
• Event.ABORT
• Event.BLUR
• Event.CHANGE
• Event.CLICK
• Event.DBLCLICK
• Event.DRAGDROP
• Event.ERROR
• Event.FOCUS
• Event.KEYDOWN
• Event.KEYPRESS
• Event.KEYUP
• Event.LOAD
• Event.MOUSEDOWN
• Event.MOUSEMOVE
• Event.MOUSEOUT
• Event.MOUSEOVER
• Event.MOUSEUP
• Event.MOVE
• Event.RESET
• Event.RESIZE
• Event.SELECT
• Event.SUBMIT
• Event.UNLOAD
After one of these events has been captured, you can define a function to replace the
built-in method for handling the event. Use the releaseEvents() method to free the
event after a capture.
Example
Listing 8.568 has a single text box and a button. The script in the <head> of the docu-
ment specifies a function to handle all onClick events in the window. To be able to do
this, the captureEvents() method has to be used to capture all events of type
16 0672321416 CH08c 7/24/01 12:33 PM Page 1149
Client-Side 1149
Event.CLICK. When the page itself is clicked, a counter, which is displayed in the text
box, is incremented.
When the button is pressed down, the onMouseDown event handler is fired and the
Event.CLICK is released and no longer increments the page when the page is clicked.
// Pass all click events to the onClick event of the text box.
window.document.myForm.myText.handleEvent(e);
}
// -->
</script>
</head>
<body>
<form name=”myForm”>
<input type=”text” size=”2” value=”” name=”myText” onclick=’changeText()’>
<input type=”button” value=”Release Event” onmousedown=’releaseClick()’>
</form>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1150
window.resizeBy()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.resizeBy(numHort, numVert)
Description
The resizeBy() method of the Window object resizes the specified window by the num-
ber of pixels passed to the method. As shown in the syntax definition, the first numeric
value passed to the method represents the number of vertical pixels you want to size
the window by, whereas the second numeric value represents the horizontal number of
pixels.
If the numbers passed are positive, the window size is increased. Negative numbers
reduce the size of the window.
Example
Listing 8.569 has four buttons. Two buttons are for increasing height, and the other two
are for increasing width. If you click these buttons, the window will resize 10 pixels at
a time.
Client-Side 1151
// -->
</script>
</head>
<body>
<form>
<table border=0>
<tr>
<td colspan=”2”>
<input type=”button” value=”Expand Down”
onclick=”resizeWin(‘vert’,10)”>
</td>
</tr>
<tr>
<td>
<input type=”button” value=”Retract From Right”
onclick=”resizeWin(‘horz’,-10)”>
</td>
<td>
<input type=”button” value=”Grow Right”
onclick=”resizeWin(‘horz’,10)”>
</td>
</tr>
<tr>
<td colspan=”2”>
<input type=”button” value=”Retrack Up”
onclick=”resizeWin(‘vert’,-10)”>
</td>
</tr>
</table>
</form>
</body>
</html>
window.resizeTo()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.resizeTo(numWidth, numHeight)
Description
The resizeTo() method of the Window object resizes the specified window to the spec-
ified size passed to the method. As shown in the syntax definition, the first numeric
value passed to the method represents the width you want to size the window to,
whereas the second numeric value represents the height.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1152
Example
Listing 8.570 has two text fields and a button. If the user enters an integer value in each
of the text fields and clicks the button, the window will resize to those settings.
window.routeEvent()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.routeEvent(event)
Description
The routeEvent() method of the Window object passes all previously captured events
of the event type passed through their normal event process. The events that can be
passed are as follows:
16 0672321416 CH08c 7/24/01 12:33 PM Page 1153
Client-Side 1153
• Event.ABORT
• Event.BLUR
• Event.CHANGE
• Event.CLICK
• Event.DBLCLICK
• Event.DRAGDROP
• Event.ERROR
• Event.FOCUS
• Event.KEYDOWN
• Event.KEYPRESS
• Event.KEYUP
• Event.LOAD
• Event.MOUSEDOWN
• Event.MOUSEMOVE
• Event.MOUSEOUT
• Event.MOUSEOVER
• Event.MOUSEUP
• Event.MOVE
• Event.RESET
• Event.RESIZE
• Event.SELECT
• Event.SUBMIT
• Event.UNLOAD
After one of these events has been captured using the Window.captureEvents()
method, you can define a function to replace the built-in method for handling the event.
Use the releaseEvents() method to free the event after a capture, and use
routeEvent() to allow the normal processing to take place.
Example
Listing 8.571 has a single text box and a link. The script in the <head> of the document
specifies a function to handle all onClick events in the window. To be able to do this,
the captureEvents() method has to be used to capture all events of type Event.CLICK.
When the page itself is clicked, a counter, which is displayed in the text box, is incre-
mented.
When the link is clicked, the onMouseDown event handler is fired and the Event.CLICK
is routed through its normal means and no longer increments the page when the page
is clicked.
// Pass all click events to the onClick event of the text box.
window.document.myForm.myText.handleEvent(e);
}
// -->
</script>
</head>
<body>
<form name=”myForm”>
<input type=”text” size=”2” value=”” name=”myText” onclick=’changeText()’>
<a href=”http://www.purejavascript.com”
onmousedown=’window.routeEvent(Event.CLICK)’>Click Here!</a>
</form>
</body>
</html>
window.screenX
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.screenX
16 0672321416 CH08c 7/24/01 12:33 PM Page 1155
Client-Side 1155
Description
The screenX property of the Window object is used to set the x coordinate of the left
edge of the window. Within Netscape browsers, the property requires the
UniversalBrowserWrite privilege.
Example
Listing 8.572 simply pops up an alert box that contains the screenX property value.
window.screenY
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.screenY
Description
The screenY property of the Window object is used to set the y coordinate of the left
edge of the window. Within Netscape browsers, the property requires the
UniversalBrowserWrite privilege.
Example
Listing 8.573 simply pops up an alert box that contains the screenY property value.
window.scroll()
JavaScript1.1, JScript3.0
Nav3, IE3, Opera3
Syntax
window.scroll(numX, numY)
Description
The scroll() method of the Window object scrolls the specified window to the speci-
fied location passed to the method. As shown in the syntax definition, the first numeric
value passed to the method represents the x coordinate to which you want to scroll the
window, whereas the second numeric value represents the y coordinate. Note that this
method has been deprecated in JavaScript 1.2 and replaced with the scrollBy() and
scrollTo() methods.
Example
Listing 8.574 has two text fields and a button. If the user enters an integer value in each
of the text fields and clicks the button, the window will be scrolled to those settings.
Client-Side 1157
</head>
<body>
<form>
<table border=0>
<tr>
<td colspan=”2”>
<input type=”button” value=”Down” onclick=”scrollWin(‘vert’,10)”>
</td>
</tr>
<tr>
<td>
<input type=”button” value=” Left “ onclick=”scrollWin(‘horz’,-10)”>
</td>
<td>
<input type=”button” value=”Right” onclick=”scrollWin(‘horz’,10)”>
</td>
</tr>
<tr>
<td colspan=”2”>
<input type=”button” value=” Up “ onclick=”scrollWin(‘vert’,-10)”>
</td>
</tr>
</table>
</form>
</body>
</html>
window.scrollbars
JavaScript1.2+
Nav4+
Syntax
window.scrollbars.property
Description
The scrollbars property of the Window object is, to some degree, an object itself. The
real use of this property is to access its visible property to determine whether the
scrollbars are visible to the user.
NOTE
As of this writing, the scrollbars property only has one subproperty: visible.
Example
See the example of Window.scrollbars.visible for an example of using the
scrollbars property.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1158
window.scrollbars.visible
JavaScript1.2+
Nav4+
Syntax
window.scrollbars.visible
Description
The visible subproperty of the scrollbars property of the Window is used to deter-
mine whether the scrollbars are visible to the user. If they are visible, the property
returns true. It returns false if the bars are not visible.
Example
Listing 8.575 determines whether several of the browser scrollbars are displayed. In the
example, you will see whether the scrollbars are visible by using the visible property.
// -->
</script>
window.scrollBy()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.scrollBy(numHorz, numVert)
16 0672321416 CH08c 7/24/01 12:33 PM Page 1159
Client-Side 1159
Description
The scrollBy() method of the Window object scrolls the specified window by the num-
ber of pixels passed to the method. As shown in the syntax definition, the first numeric
value passed to the method represents the number of horizontal pixels by which you
want to scroll the window, whereas the second numeric value represents the vertical
number of pixels.
If the numbers passed are positive, the window is scrolled up. Negative numbers are
scrolled down.
Example
Listing 8.576 has four buttons. Each of these buttons scroll the windows contents in
different directions when clicked.
window.scrollTo()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.scrollTo(numX, numY)
Description
The scrollTo() method of the Window object scrolls the specified window to the spec-
ified location passed to the method. As shown in the syntax definition, the first numeric
value passed to the method represents the x coordinate to which you want to scroll the
window, whereas the second numeric value represents the y coordinate.
Example
Listing 8.577 has two text fields and a button. If the user enters an integer value in each
of the text fields and clicks the button, the window will be scrolled to those settings.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1161
Client-Side 1161
window.self
JavaScript1.0+, JScript1.0
Nav2+, IE3+, Opera3+
Syntax
window.self.method
window.self.property
Description
The self property of the Window object contains a reference to the current window.
This allows you to invoke functions or call properties on the current window without
any confusion when multiple windows are displayed.
Example
Listing 8.578 shows how to close the current window through the self reference.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1162
Listing 8.578 Using the self Property to Reference the Current Window
<script language=”JavaScript” type=”text/javascript”>
<!--
self.close()
// -->
</script>
window.setHotKeys()
JavaScript1.2
Nav4
Syntax
window.setHotKeys(boolean)
Description
The setHotKeys() method of the Window object enables or disables all hot keys within
a window that do not have menus. It simply takes a boolean value to enable or disable
this option. Passing true will enable the hot keys, whereas false will disable them.
Example
Listing 8.579 shows how you can disable hot keys for a given window.
window.setInterval()
JavaScript1.2+, JScript3.0+
Nav4+, IE4+
Syntax
window.setInterval(expression, milliseconds)
window.setInterval(function, milliseconds)
window.setInterval(function, milliseconds, arg1, ..., argN)
16 0672321416 CH08c 7/24/01 12:33 PM Page 1163
Client-Side 1163
Description
The setInterval() method of the Window object sets an interval to invoke the expres-
sion or function that is passed to the method. The expression or function is invoked
after every elapse of the milliseconds. As shown in the syntax definition, it is possi-
ble to pass arguments to the function you want to invoke. This interval can be cleared
by using the clearInterval() method.
Example
Listing 8.580 sets an interval in the <head> of the document that displays the current
time in a text box on the page. The interval is set so that it only updates the time in the
text box every five seconds. There is also a button on this page that allows you to clear
the interval if you click it.
// -->
</script>
</head>
<body onload=”startCounter()”>
<form name=”myForm”>
<input type=”text” size=”2” value=”” name=”myText”>
<input type=”button” value=”Clear Interval” onclick=”stopCounter()”>
</form>
</body>
</html>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1164
window.setResizable()
JavaScript1.2
Nav4
Syntax
window.setResizable(boolean)
Description
The setResizable() method of the Window object enables or disables a user’s ability
to resize a window. It simply takes a boolean value to perform this option. Passing true
will enable the user to resize the window, whereas false will disable this feature.
Example
Listing 8.581 shows how you can disable the resizing of a window.
window.setTimeout()
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.setTimeout(expression, milliseconds)
window.setTimeout(function, milliseconds)
window.setTimeout(function, milliseconds, arg1, ..., argN)
Description
The setTimeout() method of the Window object sets a timeout to invoke the expression
or function that is passed to the method. The expression or function is invoked after the
elapse of the milliseconds. As shown in the syntax definition, it is possible to pass
arguments to the function you want to invoke. This timeout can be cleared by using the
clearTimeout() method.
Example
Listing 8.582 has a button and text box. By default, the time will be displayed in the
text box after five seconds. This is done using the setTimeout() method. If the button
is clicked, a function is called that invokes the clearTimeout() method, preventing the
time from being displayed in the text box.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1165
Client-Side 1165
// -->
</script>
</head>
<body>
<form name=”myForm”>
<input type=”text” size=”2” value=”” name=”myText”>
<input type=”button” value=”Clear Timeout” onclick=”stopTime()”>
</form>
</body>
</html>
window.setZOptions()
JavaScript1.2
Nav4
Syntax
window.setZOptions(type)
Description
The setZOptions() method of the Window object specifies the z-order stacking
behavior of a window. It takes a type to indicate how this stacking can occur. The
following are the possible values of type. To set this property in Navigator, you need
the UniversalBrowserWrite privilege.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1166
Example
Listing 8.583 shows how you can set the z-order stacking of a window.
//-->
</script>
window.status
JavaScript1.0+, JScript1.0+
Nav2+, IE3+, Opera3+
Syntax
window.status = string
Description
The status property of the Window object allows you to specify the message that is dis-
played in the status bar of the browser. Note that in JavaScript 1.1, this property was
tainted. See Chapter 1 for more information on JavaScript security and data tainting.
NOTE
When setting the Window.status property, be sure that your function returns
true. This also applies when setting the property within the body of an HTML tag.
Example
Listing 8.584 shows how you can set the status in the Status Bar by rolling over a link.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1167
Client-Side 1167
window.statusbar
JavaScript1.2+
Nav4+
Syntax
window.statusbar.property
Description
The statusbar property of the Window object is, to some degree, an object itself. The
real use of this property is to access its visible property to determine whether the sta-
tus bar is visible to the user.
NOTE
As of this writing, the statusbar property only has one subproperty: visible.
Example
See the example of Window.statusbar.visible for an example of using the status-
bar property.
window.statusbar.visible
JavaScript1.2+
Nav4+
Syntax
window.statusbar.visible
Description
The visible subproperty of the statusbar property of the Window is used to determine
whether the status bar is visible to the user. If it is visible, the property returns true. It
returns false if the bar is not visible.
Example
Listing 8.585 determines whether several of the browser bars are displayed. In the
example, you will see whether the status bar is visible by using the visible property.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1168
// -->
</script>
window.stop()
JavaScript1.2+, Jscript3.0
Nav4+, IE4+
Syntax
window.stop()
Description
The stop() method of the Window object simulates the user clicking the Stop button on
the browser. It stops the browser from downloading and rendering the current page.
Example
Listing 8.586 has a button and an image reference to a nonexistent image. The browser
will continue to try and download the image until it times out or the download is
stopped. Clicking the button will stop the download.
Listing 8.586 Using the stop() Method to Stop a Page from Loading
<html>
<body>
<form>
<input type=”button” value=”Stop” onclick=”window.stop()”>
</form>
<p>
<table border=”1”color= bgcolor=”#FF0000”>
<tr>
<td>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1169
Client-Side 1169
<img src=”http://www.purejavascript.com/images/fake.gif”
width=468 height=60>
</td>
</tr>
</table>
</p>
</body>
</html>
window.toolbar
JavaScript1.2+
Nav4+
Syntax
window.toolbar.property
Description
The toolbar property of the Window object is, to some degree, an object itself. The real
use of this property is to access its visible property to determine whether the toolbar
is visible to the user.
NOTE
As of this writing, the toolbar property only has one subproperty: visible.
Example
See the example of Window.toolbar.visible for an example of using the toolbar
property.
window.toolbar.visible
JavaScript1.2+
Nav4+
Syntax
window.toolbar.visible
Description
The visible subproperty of the toolbar property of the Window object is used to deter-
mine whether the toolbar is visible to the user. If it is visible, the property returns true.
It returns false if the bar is not visible.
Example
Listing 8.587 determines whether several of the browser bars are displayed. In the
example, you will see whether the toolbar is visible by using the visible property.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1170
// -->
</script>
window.top
JavaScript1.0+, JScript1.0
Nav2+, IE3+, Opera3+
Syntax
window.top.frames[num]
window.top.frameName
window.top.method
window.top.property
Description
The top property of the Window object contains a reference to the topmost browser
window of any frames or pages that are loaded. In the instance where a Frame A loads
a page with a <frameset> with Frame A.1 and A.2, the top of the documents in A.1
and A.2 is the window that actually has Frame A loaded. Frame A’s top is also this win-
dow.
As shown in the syntax definition, the referencing of sibling frames can either be done
using the frames array and passing an index number, or you can directly reference a
frame using the name that is assigned by the name attribute of the <frame> tag. From
within the current page or any of the frames, you can reference the top window and
execute any methods or reference any properties that might reside there.
Example
Assuming that the page with this script lies within a <frameset>, Listing 8.588 shows
how you can call a function that is defined in the topmost page.
16 0672321416 CH08c 7/24/01 12:33 PM Page 1171
Client-Side 1171
Listing 8.588 Using the top Property to Call a Function in the Top Frame
<script language=”JavaScript” type=”text/javascript”>
<!--
// -->
</script>
window.unwatch()
JavaScript 1.2+
Nav4+
Syntax
window.unwatch(property)
Description
The unwatch() method of the Window object is used to turn off the watch for a partic-
ular property specified by property.
Example
Listing 8.589 shows how the unwatch() method is used to stop watching the
outerHeight property of the Window object after its value has changed.
//Start watch.
window.watch(“outerHeight”, alertme);
// Change value.
window.outerHeight = 100;
// End watch.
window.unwatch(“outerHeight”);
16 0672321416 CH08c 7/24/01 12:33 PM Page 1172
window.watch()
JavaScript 1.2+
Nav4+
Syntax
window.watch(property)
Description
The watch() method of the Window object is used to turn on the watch for a particular
property specified by property.
Example
Listing 8.590 shows how the watch() method is used to start watching the
outerHeight property of the Window object after its value has changed.
//Start watch.
window.watch(“outerHeight”, alertme);
// Change value.
window.outerHeight = 100;
// -->
</script>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1173
Client-Side 1173
window.window
JavaScript1.0+, JScript1.0
Nav2+, IE3+, Opera3+
Syntax
window.method
window.property
Description
The window property of the Window object contains a reference to the current window.
This allows you to invoke functions or call properties on the current window without
any confusion when multiple windows are displayed.
Example
Listing 8.591 shows how to close the current window through the window reference.
window.close()
// -->
</script>
16 0672321416 CH08c 7/24/01 12:33 PM Page 1174
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1175
Server-Side
CHAPTER 9
Server-Side
This chapter is a detailed reference of all the items and ele-
ments making up the server-side JavaScript language. This
refers to the implementation available in the Netscape and
iPlanet Web Server Enterprise Edition, which we will simply
refer to as Enterprise Server (ES) from this point on, and
within Microsoft’s Active Server Pages (ASP) environment,
which is available for their Internet Information Server (IIS)
or Personal Web Server (PWS).
Because both Microsoft and Netscape have taken different
approaches for their server-side implementation, be sure to
check the supported environments for these entries.
Additionally, be sure to read Chapter 5, “JavaScript on the
Server-Side,” for more information on how these implementa-
tions are used.
As in other chapters of Part III, the details of the language are
covered in this chapter. Each entry includes the language ver-
sion, syntax, description, and an example of each server-
side–specific language element.
The chapter is in alphabetical order, by JavaScript objects, to
provide you with quick, easy access to the methods, properties,
functions, and event handlers of every server-side object.
These appear alphabetically after the respective parent object
using simple dot notation.
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1176
1 1 7 6 C h a p t e r 9 : S e r v e r- S i d e
addClient()
ES2+
Syntax
addClient(URL)
Description
The addClient() function is a top-level function that is not associated with any core
object. This function is used to preserve the property values of a client object when
you generate dynamic links or use the redirect() function. The addClient() func-
tion takes a URL as its only parameter.
Example
This example demonstrates how you can use the addClient() function when dynami-
cally building links. In Listing 9.1, a link is built by using a property of the project
object.
In Listing 9.2, the addClient() function is used in conjunction with the redirect()
function. This will send the user to the URL specified in the addClient() function.
addResponseHeader()
ES3+
Syntax
addResponseHeader(key, value)
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1177
S e r v e r- S i d e 1 1 7 7
Description
The addResponseHeader() function is a top-level function that is not associated with
any core object. This function is used to add fields and values to the HTTP header sent
back to the client. Because of when the actual header is sent in relation to the body of
the data, you should be sure to set these fields and values before you call the flush()
or redirect() functions.
NOTE
Because the JavaScript runtime engine flushes the output buffer after 64KB of con-
tent has been generated, you should be sure to call the addResponseHeader()
function before this time.
Example
Listing 9.3 shows how you can send back a dynamically built external JavaScript
source file to a browser with the proper content-type header field and value.
</server>
Application
ASP1+
Syntax
Core ASP environment object
Description
The Application object is a core ASP environment object. It is used to share infor-
mation across all users of a given application, which includes all .asp files as well as
any virtual directories and their subdirectories. Table 9.1 contains the methods, collec-
tions, and events of this object.
1 1 7 8 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.4 shows how you could specify the version of your application that users are
implementing, and then write it out.
Application.Application_OnEnd
ASP1+
Syntax
function Application_OnEnd(){
code
}
Description
The Application_OnEnd event function of the Application object is called when the
Application_OnEnd event is fired. This occurs when the application quits, which is
after the Session_OnEnd event is fired.
Example
Listing 9.5 shows how you can append a string to the end of the log file of the last
request of an application.
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1179
S e r v e r- S i d e 1 1 7 9
Application.Application_OnStart
ASP1+
Syntax
function Application_OnStart(){
code
}
Description
The Application_OnStart event function of the Application object is called when
the Application_OnStart event is fired. This occurs when the application starts,
which is before the Session_OnStart event is fired.
Example
In Listing 9.6 shows how you can append a string to the end of the log file on the first
request of an application.
Application.Contents
ASP1+
Syntax
Application.Contents(name)
Description
The Contents collection of the Application object contains all the items that have
been added to the application through script commands. You are able to access a spe-
cific item by specifying its name.
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1180
1 1 8 0 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.7 shows how you can use the Remove() method of the Contents collection to
remove myItem, which was added to the application.
Application.Contents.Remove()
ASP1+
Syntax
Application.Contents.Remove(name)
Application.Contents.Remove(num)
Description
The Remove() method of the Contents collection of the Application object is used to
remove an item from the application’s collection. This item can either be referenced by
its name or its num index position.
Example
Listing 9.8 shows how you can use the Remove() method of the Contents collection to
remove myItem, which was added to the application.
Application.Contents.RemoveAll()
ASP1+
Syntax
Application.Contents.RemoveAll()
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1181
S e r v e r- S i d e 1 1 8 1
Description
The RemoveAll() method of the Contents collection of the Application object is used
to remove all items from the application’s collection.
Example
Listing 9.9 shows how you can use the RemoveAll() method of the Contents collec-
tion to remove all items that have been added to the application.
Application.Lock()
ASP1+
Syntax
Application.Lock()
Description
The Lock() method of the Application object prevents other clients from modifying
any items stored in the Application object. To unlock the object, you must call the
Unlock() method, or the server will unlock it either when the page has finished pro-
cessing or times out.
Example
In Listing 9.10 we lock a counter item before updating it. This item could be used to
count the number of users a given application has serviced.
// Initialize the counter, which should ONLY be done on the first page of
// the application.
Application(“counter”) = 0;
1 1 8 2 C h a p t e r 9 : S e r v e r- S i d e
Application.StaticObjects
ASP1+
Syntax
Application.StaticObjects(name)
Description
The StaticObjects collection of the Application object stores all the objects created
with <object> elements on a given ASP page. These are referenced by the name given
to each instance of the elements.
Example
Listing 9.11 shows how you can grab the instance myControl from your current ASP
page.
Application.Unlock()
ASP1+
Syntax
Application.Unlock()
Description
The Unlock() method of the Application object unlocks the previously locked
Application object. To first lock the object, you must call the Lock() method. If you
fail to call the Unlock() method, the server will unlock it when the page has finished
processing or times out.
Example
In Listing 9.12 we lock a counter item before updating it. This item could be used to
count the number of users a given application has serviced. After updating, we unlock
it for others to access and modify.
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1183
S e r v e r- S i d e 1 1 8 3
// Initialize the counter, which should ONLY be done on the first page of
// the application.
Application(“counter”) = 0;
ASPError
ASP3+
Syntax
Core ASP environment object
Description
The ASPError object is a core ASP environment object. Its properties and methods are
used to retrieve information about errors that have occurred on a given page. This
object is returned by the Server.GetLastError() method and exposes read-only prop-
erties. Table 9.2 contains a list of properties for this object.
1 1 8 4 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.13 shows how you can write out a short description of an error that has been
exposed to the ASPError object.
ASPError.ASPCode
ASP3+
Syntax
ASPError.ASPCode
Description
The ASPCode property of the ASPError object contains error code generated by IIS.
Example
In Listing 9.14 we write out the value of the ASPCode property.
ASPError.ASPDescription
ASP3+
Syntax
ASPError.ASPDescription
Description
The ASPDescription property of the ASPError object contains a more detailed descrip-
tion of the error returned.
Example
In Listing 9.15 we write out the value of the ASPDescription property.
S e r v e r- S i d e 1 1 8 5
ASPError.Category
ASP3+
Syntax
ASPError.Category
Description
The Category property of the ASPError object indicates if the source of the error was
internal to ASP, JScript, or an object.
Example
In Listing 9.16 we write out the value of the Category property.
ASPError.Column
ASP3+
Syntax
ASPError.Column
Description
The Column property of the ASPError object contains the column position within the
ASP file where the error occurred.
Example
In Listing 9.17 we write out the value of the Column property.
ASPError.Description
ASP3+
Syntax
ASPError.Description
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1186
1 1 8 6 C h a p t e r 9 : S e r v e r- S i d e
Description
The Description property of the ASPError object contains a short description of the
error.
Example
In Listing 9.18 we write out the value of the Description property.
ASPError.File
ASP3+
Syntax
ASPError.File
Description
The File property of the ASPError object contains the name of the ASP file being
processed when the error occurred.
Example
In Listing 9.19 we write out the value of the File property.
ASPError.Line
ASP3+
Syntax
ASPError.Line
Description
The Line property of the ASPError object contains the line number on which the error
occurred.
Example
In Listing 9.20 we write out the value of the Line property.
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1187
S e r v e r- S i d e 1 1 8 7
ASPError.Number
ASP3+
Syntax
ASPError.Number
Description
The Number property of the ASPError object contains the standard COM error code.
Example
In Listing 9.21 we write out the value of the Number property.
ASPError.Source
ASP3+
Syntax
ASPError.Source
Description
The Source property of the ASPError object contains the actual source code, if avail-
able, that the error occurred in.
Example
In Listing 9.22 we write out the value of the Source property.
1 1 8 8 C h a p t e r 9 : S e r v e r- S i d e
blob() (Function)
ES2+
Syntax
blob(path)
Description
BLOB data represents binary large objects that can be stored in a database. This allows
you to store various types of information, such as images, movie files, and sounds in
the database.
NOTE
Be sure to consult the documentation on your specific database to see whether
there are any limitations to BLOB data types.
The blob() function is used to store BLOB data in your database. This function takes
the path to a BLOB file as its only parameter. Note that this path must be an absolute
pathname and not a relative one.
Example
In Listing 9.23, a cursor instance has been created to perform a query on the database
to find a specific row. Focus is then placed on that row and the blob() function is used
to assign the data to a column. The final step in the process is to use the updateRow()
method to commit the change.
Listing 9.23 Using the blob() Function to Insert BLOB Data into a
Database
<server>
// Close the cursor and write it to the page if there was an error.
var dbError = myCursor.close();
if(dbError) write(myCursor.close());
</server>
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1189
S e r v e r- S i d e 1 1 8 9
blob (Object)
ES2+
Syntax
Core object is created with the blob.blobImage() and blob.blobLink() methods.
Description
The top-level blob object contains methods that allow you to store and retrieve blob
data in a database. BLOB data represents binary large objects that can be stored in a
database. This allows you to store various types of information, such as images, movie
files, and sounds in the database.
NOTE
Be sure to consult the documentation on your specific database to see whether
there are any limitations to BLOB data types.
The core blob object is created when you use the methods of this object. Table 9.3 has
the methods of the blob object and a description of what they do when invoked.
Example
Listing 9.24 queries a database for a specific image, creating an instance of a blob
object when retrieved. The image is then written to the page using the write() and
blobImage() methods. The actual tag written will be as follows:
// Write the <img> tag to the page with the following attributes set.
write(myCursor.path.blobImage(“gif”, “Click”, “left”, 468, 60, 0, false));
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1190
1 1 9 0 C h a p t e r 9 : S e r v e r- S i d e
blob.blobImage()
ES2+
Syntax
cursor.column.blobImage(fileType, altText, align, width, height, border, ismap)
Description
The blobImage() method retrieves and displays a BLOB image stored in a database.
The method actually returns the HTML for the <img> tag used to display the image.
The href attribute of the <img> tag references the instance of this image in memory and
does not have to contain a “normal” URL of the image itself.
This method can take up to seven parameters that set the various attributes of the <img>
tag. These attributes are contained in Table 9.4. At a minimum, you must pass the
fileType of the image.
Table 9.4 Properties That Can Be Set with the blobImage() Method
Parameter Attribute Description
It Sets
fileType none This parameter does not set an attribute. It specifies
the type of file that is being displayed, such as gif
or jpeg.
altText alt A string that is displayed when the browser has
been set to not display images or when a mouse is
over an image for a specified period of time.
align align This can be set to LEFT, RIGHT, or any other value
your target browser supports.
width width The width in pixels of your image.
height height The height in pixels of your image.
border border An integer value that specifies the size of any bor-
der that might appear around the image if the
image is surrounded by the <a> tag.
ismap ismap Specifies whether the image has a map file associ-
ated with it to handle any clicks that might occur
within it. This parameter is set by specifying true if
the image has a map file associated with it or false
if not.
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1191
S e r v e r- S i d e 1 1 9 1
Example
Listing 9.25 queries a database for a specific image. The image is then written to the
page using the write() and blobImage() methods. The actual tag written will be as
follows:
<IMG ALT=”Click” ALIGN=”left” WIDTH=”468” HEIGHT=”60” BORDER=”0”
➥ISMAP=”false”>
// Write the <img> tag to the page with the following attributes set.
write(myCursor.path.blobImage(“gif”, “Click”, “left”, 468, 60, 0, false));
blob.blobLink()
ES2+
Syntax
cursor.column.blobLink(mimeType, text)
Description
The blobLink() method retrieves BLOB data stored in a database, stores it in mem-
ory, and creates a temporary link to it. The method actually returns the HTML for the
<a> tag used to display the link. The href attribute of the <a> tag references the BLOB
data type, which has been stored in a temporary memory location, and does not con-
tain a “normal” URL of this attribute. The data is stored in memory until the user clicks
the link or until 60 seconds have elapsed.
The parameters this method takes are the MIME type of the file referenced, and the
text that is displayed to the user as a link.
Example
Listing 9.26 queries a database for a specific image. A link referencing the image is
then written to the page using the write() and blobLink() methods. The actual tag
written will be as follows:
<a href=”LIVEWIRE_TEMP1”>Click Here!</a>
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1192
1 1 9 2 C h a p t e r 9 : S e r v e r- S i d e
// Write the <a> tag to the page with the attributes set.
write(myCursor.path.blobLink(“image/gif”, “Click Here!”));
callC()
ES2+
Syntax
callC(JSFuncName, arg1, arg2, ..., argN)
Description
The callC() function, which returns string values, is a top-level function that is not
associated with any core object. callC() is used to call a JavaScript function that ref-
erences a C function in a shared library. These libraries are the pre-built .dll files on
Windows machine and .so files on Unix machines. callC() takes the JavaScript name
you have assigned to the C function and any arguments the function needs as argu-
ments.
Before you can call this function, you must register the C library using the server-side
JavaScript registerCFunction(). RegisterCFunction() takes the JavaScript name
with which you want to reference the function, the path to the library, and the C func-
tion name as parameters.
Example
Listing 9.27 registers an external C library, extlib.dll, that contains a function named
getMyDate. The registration of this function assigns the name JSExtLib to be used
within the script. If the function successfully registers, the callC() function is used to
call the C function and pass it two parameters. The results are written to the user’s page.
If the function does not register properly, an error is written to the user’s page.
Listing 9.27 Using a C Function with callC That Has Been Registered
<server>
S e r v e r- S i d e 1 1 9 3
</server>
client
ES2+
Syntax
Core object is created with each connection of a client to your application.
Description
An instance of the client object is created with each connection of a user to your
application. This object is used to maintain session variables for that user as she moves
through your application’s pages. Because the object is not created until a user con-
nects to your application, you cannot use the object on the first page of your applica-
tion.
NOTE
The client object is created for each user’s connection to each application you
have built using Server-side JavaScript, so a single user connected to two applica-
tions will have two client objects created.
The object itself is held until the user is inactive for a set period of time or the object
is destroyed. At that time, the JavaScript runtime engine cleans up the object. The
default timeout is ten minutes, but this can be changed by using the expiration()
method or can be destroyed manually by using the destroy() method.
client objects do not have any default properties, but properties can be created for
them. Do note that because of the method used to maintain user sessions, these prop-
erties are all converted to strings. If you have created a property that must be evaluated
as a numeric value, use the parseInt() and parseFloat() methods for processing.
If you must store an object as a property, you will have to create an array of objects in
the project or server objects. Then you can create a property to hold the index of your
object in the client object.
17 0672321416 CH09a was 13a 7/24/01 12:40 PM Page 1194
1 1 9 4 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.28 contains a form the user fills out with her name, e-mail address, and phone
number. When the Submit button is clicked, the form is sent back to itself and the script
sees information being passed in. This information is then assigned to three created
properties of the client object and is then written to the user’s page.
S e r v e r- S i d e 1 1 9 5
write(‘</table>’);
write(‘</td></tr></table>’);
write(‘</form>’);
}
</server>
</body>
</html>
client.destroy()
ES2+
Syntax
client.destroy()
Description
The destroy() method of the client object explicitly destroys that instance of the
object and all its associated properties. If this method is not called, the JavaScript run-
time will destroy the object after 10 minutes or after the time specified with the
client.expiration() method.
If you are using cookies to maintain your client object, calling the destroy() method
acts in the same manner but does not remove information stored in the browser’s
cookie file. To remove the cookie information, set the expiration to 0 seconds by using
the client.expiration() method.
When using URL encoding to maintain the client object, the destroy() method will
destroy all information with the exception that the links created before the method call
will retain their properties. Because of this, good programming practice warrants call-
ing the method at the top or bottom of a page.
Example
Listing 9.29 shows how to destroy the properties of your user’s client object.
Listing 9.29 Using the destroy() Method to Destroy the client Object
Properties
<server>
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1196
1 1 9 6 C h a p t e r 9 : S e r v e r- S i d e
client.expiration()
ES2+
Syntax
client.expiration(seconds)
Description
The expiration() method of the client object sets the number of seconds of user
inactivity before the JavaScript runtime destroys all properties associated with that ses-
sion. The default timeout is 10 minutes if you do not explicitly set this property. Also,
this method has no effect when using URL encoding to maintain your client objects.
NOTE
Setting this to 0 will remove any cookies associated with the client object when
using client cookies to maintain sessions.
Example
Listing 9.30 sets the destruction of the client object to occur after five minutes of
inactivity.
</server>
client.property
ES2+
Syntax
client.property
Description
When a property is created for an instance of the client object, it is accomplished by
passing information from a form. When you pass a form element, designated by the
name attribute, to the server, it is accessible through the client.property syntax,
where property is the name passed.
Example
Listing 9.31 shows how the form value zip is accessible in a server-side JavaScript
script by assigning it to an instance of the client object. Once assigned, the value
stored in the property is written back out to the user’s page.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1197
S e r v e r- S i d e 1 1 9 7
client.unwatch()
ES3+
Syntax
client.unwatch(property)
Description
The unwatch() method of the client object is used to turn off the watch for a partic-
ular property.
Example
Listing 9.32 shows how the unwatch() method is used to stop watching the user-
defined property p.
// watch property
client.watch(“zip”, alertme);
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1198
1 1 9 8 C h a p t e r 9 : S e r v e r- S i d e
</server>
client.watch()
ES3+
Syntax
client.watch(property, function)
Description
The watch() method of the client object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 9.33 shows how the watch() method is used to start watching the user-defined
property p.
// watch property
client.watch(“zip”, alertme);
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1199
S e r v e r- S i d e 1 1 9 9
client.zip = null;
</server>
Connection
ES3+
Syntax
Core object is created when the DbPool.connection() method is called.
Description
The Connection object represents a given connection, pulled from a “pool”, to a data-
base. This object has only one property, the prototype property, which you can use to
add properties to the object. Table 9.5 shows the methods associated with this object.
NOTE
If you only need a single connection to the database and do not need to create a
pool, use the database object for your connection.
1 2 0 0 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.34 creates a pool of connections to an Oracle database and initializes a con-
nection from that pool. It takes a user’s UID and name that was passed in, runs a query
(based on the UID) against the database to find that user’s information, and updates the
user’s name. If a connection is not made, the error code and message is returned to the
screen.
// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;
// Focus on that line, change the name column for that user,
// and update the row.
currRow.next();
currRow.name = client.name;
currRow.updateRow(“employees”);
S e r v e r- S i d e 1 2 0 1
</server>
Connection.beginTransaction()
ES3+
Syntax
connection.beginTransaction()
Description
The beginTransaction() method of the Connection object begins a new SQL trans-
action. This groups all the actions against the database together until the user exits the
page or either the commitTransaction() or rollbackTransaction() methods are
called. In the instance of the user exiting the page, the transaction is either committed
or rolled back, depending on the setting of the commit flag when the DbPool object
instance is created.
NOTE
You cannot have nested transactions.
Example
Listing 9.35 creates a pool of connections to an Oracle database and pulls one of the
connections from the pool. After the connection has been verified, the
beginTransaction() method is called and a SQL query is performed. The results are
formatted in a table with the SQLTable() method and written to the user’s page.
1 2 0 2 C h a p t e r 9 : S e r v e r- S i d e
</server>
Connection.commitTransaction()
ES3+
Syntax
connection.commitTransaction()
Description
The commitTransaction() method of the Connection object commits a new SQL
transaction. This commits all the actions against the database since the last commit. If
the commit is successful, 0 is returned. If a non-zero number is returned, an error is
encountered. In this case, various methods of the Connection object can be used to
retrieve the code and message of the error.
Example
Listing 9.36 creates a pool of connections to an Oracle database and pulls one of the
connections from the pool. After the connection has been verified, the
beginTransaction() method is called and a SQL query is performed. The results are
formatted in a table with the SQLTable() method and written to the user’s page.
S e r v e r- S i d e 1 2 0 3
</server>
Connection.connected()
ES3+
Syntax
connection.connected()
Description
The connected() method of the Connection object tells if the pool of connections to
the database is still connected.
Example
Listing 9.37 creates a pool of connections and pulls a connection from the pool for pro-
cessing. If the connection is made, any code within that section is executed. If the con-
nection fails, the error is written to the page.
1 2 0 4 C h a p t e r 9 : S e r v e r- S i d e
}else{
</server>
Connection.cursor()
ES3+
Syntax
connection.cursor(sql)
connection.cursor(sql, boolean)
Description
The cursor() method of the Connection object creates a Cursor object that can be
used to run SQL queries against the database. The method takes the sql statement as a
parameter, as well as an optional boolean value that specifies whether the cursor is
updateable.
Example
Listing 9.38 shows how you would run a query against the database using the cursor()
method. The while loop is used to write the results to the user’s page.
Listing 9.38 Using the cursor() Method to Run a Query Against the
Database
<server>
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1205
S e r v e r- S i d e 1 2 0 5
Connection.execute()
ES3+
Syntax
connection.execute(statement)
Description
The execute() method of the Connection object enables your application to execute
a DDL (Data Definition Language) or DML (Data Manipulation Language) query,
which does not return a Cursor, supported by your database. This includes statements
such as CREATE, ALTER, and DROP.
NOTE
Be sure to use SQL that conforms to your database.
Example
Listing 9.39 deletes all rows with a UID less than the number passed to the script.
</server>
Connection.majorErrorCode()
ES3+
Syntax
connection.majorErrorCode()
Description
The majorErrorMessage() method of the Connection object contains the ODBC or
database numeric error code that is returned if an error occurs.
Example
Listing 9.40 shows how you would create a pool of connections, pull a connection from
it, and test for the connection. If the test fails, the majorErrorCode() is used when
writing the error to the page.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1206
1 2 0 6 C h a p t e r 9 : S e r v e r- S i d e
if (myConn.connected()) {
}else{
</server>
Connection.majorErrorMessage()
ES3+
Syntax
connection.majorErrorMessage()
Description
The majorErrorMessage() method of the Connection object contains the ODBC or
database string error message that is returned if an error occurs.
Example
Listing 9.41 shows how you would create a pool of connections, pull a connection from
it, and test for the connection. If the test fails, the majorErrorMessage() is used when
writing the error to the page.
S e r v e r- S i d e 1 2 0 7
// not be made.
var myConn = myPool.connection(‘Employees’, 15);
if (myConn.connected()) {
}else{
</server>
Connection.minorErrorCode()
ES3+
Syntax
connection.minorErrorCode()
Description
The minorErrorMessage() method of the Connection object contains the secondary
ODBC or database numeric error code that is returned if an error occurs.
Example
Listing 9.42 shows how you would create a pool of connections, pull a connection from
it, and test for the connection. If the test fails, the minorErrorCode() is used when
writing the secondary error to the page.
if (myConn.connected()) {
1 2 0 8 C h a p t e r 9 : S e r v e r- S i d e
</server>
Connection.minorErrorMessage()
ES3+
Syntax
connection.minorErrorMessage()
Description
The minorErrorMessage() method of the Connection object contains the secondary
ODBC or the database string error message that is returned if an error occurs.
Example
Listing 9.43 shows how you would create a pool of connections, pull a connection from
it, and test for the connection. If the test fails, the minorErrorMessage() is used when
writing the secondary error to the page.
if (myConn.connected()) {
}else{
S e r v e r- S i d e 1 2 0 9
Connection.prototype
ES3+
Syntax
connection.prototype.method = name
connection.prototype.property = value
Description
The prototype property of the Connection object allows you to add methods and
properties to the Connection object. If you are adding a method, you set the instance
equal to the name of the method you have defined.
Example
Listing 9.44 creates a new property and method of the Connection object. An instance
is created and the new property is set. The new method is then called to verify the prop-
erty and, if it is incorrect (which it is), an error message is written to the page.
1 2 1 0 C h a p t e r 9 : S e r v e r- S i d e
</server>
Connection.release()
ES3+
Syntax
connection.release()
Description
The release() method of the Connection object returns the connection to the DbPool
instance after all cursors have been closed. If you do not close the cursor, the connec-
tion will remain until it times out or the variable holding your connection, assuming
you assigned it to one, goes out of scope. Depending on how you have written your
application, this can happen when the application is stopped, the Web server is stopped,
or when control leaves the HTML page.
Example
Listing 9.45 shows a pool being created, a connection being pulled from the pool, and
a query run against the database. When the cursor is closed, the connection is released.
// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;
S e r v e r- S i d e 1 2 1 1
// Focus on that line, change the name column for that user,
// and update the row.
currRow.next();
currRow.name = client.name;
currRow.updateRow(“employees”);
</server>
Connection.rollbackTransaction()
ES3+
Syntax
connection.rollbackTransaction()
Description
The rollbackTransaction() method of the Connection object will undo all actions
performed since the last beginTransaction() method call.
NOTE
You cannot have nested transactions.
Example
Listing 9.46 takes a commit field sent to the application from the user. If this evaluates
to true, the transaction is committed. If not, it is rolled back.
1 2 1 2 C h a p t e r 9 : S e r v e r- S i d e
}else{
</server>
Connection.SQLTable()
ES3+
Syntax
connection.SQLTable(sql)
Description
The SQLTable() method of the Connection object takes a sql SELECT statement as a
parameter and executes a query through the connection from which it was called. It
returns the result formatted in an HTML table for easy writing to a client’s page. This
is a simple table in the following format:
<table border=”1”>
<tr>
<th>column 1</th>
<th>column 2</th>
...
<th>column N</th>
</tr>
<tr>
<td>value 1 of column 1</td>
<td>value 1 of column 2</td>
...
<td>value 1 of column N</td>
</tr>
<tr>
<td>value 2 of column 1</td>
<td>value 2 of column 2</td>
...
<td>value 2 of column N</td>
</tr>
...
</table>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1213
S e r v e r- S i d e 1 2 1 3
Example
Listing 9.47 runs a user passed query and formats the result using the SQLTable()
method. This information is then written to the user’s page.
</server>
Connection.storedProc()
ES3+
Syntax
connection.storedProc(procName)
connection.storedProc(procName, arg1, arg2, ... , argN)
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1214
1 2 1 4 C h a p t e r 9 : S e r v e r- S i d e
Description
The storedProc() method of the Connection object creates a Stproc object that
allows you to execute a database-specific stored procedure using the connection from
which it was invoked.
As shown in the syntactical definition, you can also pass any arguments needed to the
method for processing. If you are using a stored procedure that requires arguments, or
if you want to have the procedure run using default arguments, you must pass
/Default/ as the argument. The following shows an example of passing a default
value:
var myStproc = myConn.storedProc(“sp_employees”, “/Default/”);
The scope of this procedure is restricted to the current page. Any methods of the
Stproc object must be invoked on the current page. If this is not possible, a new object
will have to be created on subsequent pages to access the properties needed.
Example
Listing 9.48 creates a pool of connections and pulls one of the connections. When the
connection has been verified, the storedProc() method is used to invoke the fictitious
sp_employees stored procedure.
myConn.beginTransaction();
S e r v e r- S i d e 1 2 1 5
</server> >
Connection.toString()
ES3+
Syntax
connection.toString()
Description
The toString() method of the Connection object returns a text value of the object.
When invoked on an instance of a Connection object, the string is returned in the fol-
lowing format:
“dbName” “uid” “dbType” “dbInstance”
If the parameter is unknown, an empty string is returned. Table 9.6 contains the value
of these returned values.
Example
Listing 9.49 creates an instance of the Connection object. Once created, the write()
method is used to write its string value to the page.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1216
1 2 1 6 C h a p t e r 9 : S e r v e r- S i d e
</server>
Connection.unwatch()
ES3+
Syntax
connection.unwatch(property)
Description
The unwatch() method of the Connection object is used to turn off the watch for a
particular property.
Example
Listing 9.50 shows how the unwatch() method is used to stop watching the user-
defined property p.
S e r v e r- S i d e 1 2 1 7
// change value
myConn.type = null;
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1218
1 2 1 8 C h a p t e r 9 : S e r v e r- S i d e
Connection.watch()
ES3+
Syntax
connection.watch(property, function)
Description
The watch() method of the Connection object is used to turn on the watch for a
particular property specified by property. Any time the specified property is changed
after the watch() method has been called, the specified function is called.
Example
Listing 9.51 shows how the watch() method is used to start watching the user-defined
property p.
S e r v e r- S i d e 1 2 1 9
// change value
myConn.type = null;
</server>
Cursor
ES2+
Syntax
connection.cursor()
database.cursor()
Description
The Cursor object is a core object created when the cursor() method of the
Connection or database object is called. A database query is said to return a cursor,
so this object contains references to the rows returned from a query.
When working with cursor objects, you should explicitly close them using the close()
method when you are finished. Not doing so will cause the JavaScript runtime to hold
the cursor in memory until the connection or pool to which the cursor was tied goes out
of scope.
The Cursor object has several methods and properties associated with it. These are
listed in Table 9.7.
1 2 2 0 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.52 takes a UID, passed as an area code, that is assigned to the client object.
A pool of connections is then opened to the database, and one of the connections is
pulled to run the query. The results of the query are stored in a Cursor object and are
iterated through use of the next() method. After all rows have been updated with the
new area code, the cursor is closed and the connection is released.
// Assign the user submitted ID and area code to the client object
// as properties.
client.uid = request.uid;
client.areacode = request.areacode;
S e r v e r- S i d e 1 2 2 1
// For all the lines that matched, update the area code.
while(currRow.next()){
currRow.areacode = client.areacode;
currRow.updateRow(“employees”);
}
</server>
Cursor.close()
ES2+
Syntax
cursor.close()
Description
The close() method of the Cursor object closes the cursor and frees all memory that
had been used to store its information. If successful, the method returns 0, otherwise it
returns an error code that can be obtained by using the majorErrorCode() and
majorErrorMessage() methods of the Connection or database objects.
Example
Listing 9.53 creates a cursor and then closes it.
// Create cursor
var currRow = myConn.cursor(‘SELECT areacode FROM employees WHERE uid >= ‘
➥ + client.uid);
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1222
1 2 2 2 C h a p t e r 9 : S e r v e r- S i d e
</server>
Cursor.columnName
ES2+
Syntax
cursor.columnName
Description
The columnName property of the Cursor object is an array of objects that corresponds
to the name of the columns in the cursor.
Example
Listing 9.54 shows a cursor object being created. The various values are then written
to the page using the columnName property as their reference.
// Write each person’s name and phone number to the page in the form:
// “<name>’s phone number is (<areacode>) <phone>”
while(currRow.next()){
write(currRow.name + “‘s phone number is (“ + currRow.areacode + “) “);
write(currRow.phone + “<br>”);
}
</server>
Cursor.columnName()
ES2+
Syntax
cursor.columnName(num)
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1223
S e r v e r- S i d e 1 2 2 3
Description
The columnName() method of the Cursor object takes the zero-based indexed number
location, num, passed to the method and returns the name of the column in that loca-
tion. Note that these names are not returned in any specific order unless you order them
as such. Successive calls to the method, however, will return all the columns. See the
example for more information on this.
Example
Listing 9.55 has two cursors. One of the cursors returns specific column names and the
other returns all columns. See the comments in the code for the output.
// Writes all column names stored in the second cursor to the page.
// This will include ‘areacode’ and ‘phone’ as well as any other
// columns.
for(var i = 0; i <= currRow2.columns(); i++){
write(currRow2.columnName(i));
}
1 2 2 4 C h a p t e r 9 : S e r v e r- S i d e
</server>
Cursor.columns()
ES2+
Syntax
cursor.columns()
Description
The columns() method of the Cursor object returns the number of columns in the cur-
sor on which it is invoked. If the SQL string that was passed to create the cursor spec-
ified a set number of columns to return, this is the number returned by the method.
Example
Listing 9.56 shows how you can return all the column names of the columns in your
cursor.
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1225
S e r v e r- S i d e 1 2 2 5
Cursor.deleteRow()
ES2+
Syntax
cursor.deleteRow(table)
Description
The deleteRow() method of the Cursor object uses an updateable cursor and deletes
the current row in the specified table of the Cursor object. If the delete was success-
ful, 0 is returned; otherwise it returns an error code that can be obtained by using the
majorErrorCode() and majorErrorMessage() methods of the Connection or data-
base objects.
Example
Listing 9.57 creates a Cursor object and selects all instances of a given id. The
deleteRow() method is then used to delete each of these instances.
Listing 9.57 Deleting a Row from the Cursor Using the deleteRow()
Method
<server>
1 2 2 6 C h a p t e r 9 : S e r v e r- S i d e
</server>
Cursor.insertRow()
ES2+
Syntax
cursor.insertRow(table)
Description
The insertRow() method of the Cursor object uses an updateable cursor and inserts a
new row in the specified table of the Cursor object. If the insert was successful, 0 is
returned; otherwise, it returns an error code that can be obtained by using the
majorErrorCode() and majorErrorMessage() methods of the Connection or data-
base objects.
NOTE
Depending on your database, you might have to close the current cursor and
reopen it if you want to access a newly inserted row. Also, if the next() method
has been called on the cursor, any columns you do not specify values for will get
the same values as the current row.
Example
Listing 9.58 creates a Cursor object and selects all rows. The insertRow() method is
then used to insert a new row with three specified columns.
Listing 9.58 Inserting a Row from the Cursor Using the insertRow()
Method
<server>
S e r v e r- S i d e 1 2 2 7
</server>
Cursor.next()
ES2+
Syntax
cursor.next()
Description
The next() method of the Cursor object moves the point in the current row to the next
row in the cursor. This method is used to iterate through each of the rows returned by
the cursor. This method returns true, unless it is the last row of the cursor, at which
time it returns false.
Example
Listing 9.59 creates an instance of the Cursor object and iterates through its results,
deleting each row. This is performed by using the next()method.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1228
1 2 2 8 C h a p t e r 9 : S e r v e r- S i d e
Listing 9.59 Using the next() Method to Iterate Through the Rows in a
Cursor
<server>
</server>
Cursor.prototype
ES2+
Syntax
cursor.prototype.method = name
cursor.prototype.property = value
Description
The prototype property of the Cursor object allows you to create new properties and
methods of the object. If you are adding a method, you set the instance equal to the
name of the method you have defined.
Example
Listing 9.60 creates a new property and method of the Cursor object. An instance is
created and the new property is set. The new method is then called to verify the prop-
erty, and, if it is incorrect, an error message is written to the >page.
S e r v e r- S i d e 1 2 2 9
}
}
</server>
Cursor.unwatch()
ES3+
Syntax
cursor.unwatch(property)
Description
The unwatch() method of the Cursor object is used to turn off the watch for a partic-
ular property.
Example
Listing 9.61 shows how the unwatch() method is used to stop watching the user-
defined property p.
1 2 3 0 C h a p t e r 9 : S e r v e r- S i d e
// watch property
currRow.watch(“type”, alertme);
// change value
currRow.type = “DELETE”;
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1231
S e r v e r- S i d e 1 2 3 1
Cursor.updateRow()
ES2+
Syntax
cursor.updateRow(table)
Description
The updateRow() method of the Cursor object uses an updateable cursor and updates
the current row in the specified table of the cursor object. If the insert was successful,
0 is returned; otherwise, it returns an error code that can be obtained by using the
majorErrorCode() and majorErrorMessage() methods of the Connection or data-
base objects.
Example
Listing 9.62 creates a Cursor object and selects all rows. The updateRow() method is
then used to update the current row with three specified values.
Listing 9.62 Updating a Row from the Cursor Using the updateRow()
Method
<server>
1 2 3 2 C h a p t e r 9 : S e r v e r- S i d e
</server>
Cursor.watch()
ES3+
Syntax
cursor.watch(property, function)
Description
The watch() method of the Cursor object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 9.63 shows how the watch() method is used to start watching the user-defined
property p.
S e r v e r- S i d e 1 2 3 3
// watch property
currRow.watch(“type”, alertme);
// change value
currRow.type = “DELETE”;
</server>
database
ES2+
Syntax
Core object is created when the database.connect() method is called.
Description
The database object represents a given connection to a database. This object has only
one property, the prototype property, which you can use to add properties to the
object. Table 9.8 lists the methods associated with this object.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1234
1 2 3 4 C h a p t e r 9 : S e r v e r- S i d e
NOTE
If you only need a pool of connections to the database, use the DbPool object for
your connection to initialize a pool, and then use the Connection.connection()
method to assign a connection.
Example
Listing 9.64 creates a connection to an Oracle database. It takes a user’s UID and name
that was passed in, runs a query (based on the UID) against the database to find that
user’s information, and updates her name. If a connection is not made, the error code
and message are returned to the screen.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1235
S e r v e r- S i d e 1 2 3 5
// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if(myConn.connected()){
// Focus on that line, change the name column for that user,
// and update the row.
currRow.next();
currRow.name = client.name;
currRow.updateRow(“employees”);
myConn.commitTransaction();
</server>
database.beginTransaction()
ES2+
Syntax
database.beginTransaction()
Description
The beginTransaction() method of the database object begins a new SQL transac-
tion. This groups all the actions against the database together until the user exits the
page or either the commitTransaction() or rollbackTransaction() methods are
called. In the instance of the user exiting the page, the transaction is either committed
or rolled back, depending on the setting of the commit flag when the database object
instance is created.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1236
1 2 3 6 C h a p t e r 9 : S e r v e r- S i d e
NOTE
You cannot have nested transactions.
Example
Listing 9.65 creates a connection to an Oracle database. After the connection has been
verified, the beginTransaction() method is called and a SQL query is performed. The
results are formatted in a table with the SQLTable() method and written to the user’s
page.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if(myConn.connected()){
</server>
database.commitTransaction()
ES2+
Syntax
database.commitTransaction()
Description
The commitTransaction() method of the database object commits a new SQL trans-
action. This commits all the actions against the database since the last commit. If the
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1237
S e r v e r- S i d e 1 2 3 7
Example
Listing 9.66 creates a connection to an Oracle database. After the connection has been
verified, the beginTransaction() method is called and a SQL query is performed. The
results are formatted in a table with the SQLTable() method and written to the user’s
page.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if(myConn.connected()){
</server>
database.connect()
ES2+
Syntax
database.connect(dbType, dbInstance, uid, pwd, dbName)
1 2 3 8 C h a p t e r 9 : S e r v e r- S i d e
Description
The connect method of the database object is the actual method that connects to a
database given the parameters passed. Before you open a connection to a database and
have the ability to run queries against it, you should create an instance of this object.
Each parameter is defined in Table 9.9.
Example
Listing 9.67 creates a connection to an Oracle database. It takes a user’s UID and name
that was passed in, runs a query (based on the UID) against the database to find that
user’s information, and updates her name. If a connection is not made, the error code
and message are returned to the screen.
// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;
// Open a connection.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1239
S e r v e r- S i d e 1 2 3 9
if(myConn.connected()){
// Focus on that line, change the name column for that user,
// and update the row.
currRow.next();
currRow.name = client.name;
currRow.updateRow(“employees”);
myConn.commitTransaction();
</server>
database.connected()
ES2+
Syntax
database.connected()
Description
The connected() method of the database object tells whether the connection to the
database is still active.
Example
Listing 9.68 creates a connection to a database. If the connection is made, any code
within that section is executed. If the connection fails, the error is written to the page.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1240
1 2 4 0 C h a p t e r 9 : S e r v e r- S i d e
}else{
</server>
database.cursor()
ES2+
Syntax
database.cursor(sql)
database.cursor(sql, boolean)
Description
The cursor() method of the database object creates a Cursor object that can be
used to run SQL queries against the database. The method takes the sql statement as a
parameter, as well as an optional boolean value that specifies whether the cursor is
updateable.
Example
Listing 9.69 shows how you would run a query against the database using the
cursor() method. The while loop is used to write the results to the user’s page.
Listing 9.69 Using the cursor() Method to Run a Query Against the
Database
<server>
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1241
S e r v e r- S i d e 1 2 4 1
database.disconnect()
ES2+
Syntax
database.disconnect()
Description
The disconnect method of the database object disconnects a connection to a data-
base.
Example
Listing 9.70 creates a connection to an Oracle database. It takes a user’s UID and name
that was passed in, runs a query (based on the UID) against the database to find that
user’s information, and updates her name. If a connection is not made, the error code
and message are returned to the screen. After the processing has been completed, the
connection is dropped using the disconnect() method.
// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;
// Open a connection.
var myConn = database.connect(“ORACLE”,”mySID”,”myApp”,”appsPWD”,”myTNS”,true);
if(myConn.connected()){
// Focus on that line, change the name column for that user,
// and update the row.
currRow.next();
currRow.name = client.name;
currRow.updateRow(“employees”);
myConn.commitTransaction();
1 2 4 2 C h a p t e r 9 : S e r v e r- S i d e
</server>
database.execute()
ES2+
Syntax
database.execute(statement)
Description
The execute() method of the database object enables your application to execute a
DDL (Data Definition Language) or DML (Data Manipulation Language) query,
which does not return a Cursor, supported by your database. This includes statements
such as CREATE, ALTER, and DROP.
NOTE
Be sure to use SQL that conforms to your database.
Example
Listing 9.71 deletes all rows with a UID less than the number passed to the script.
</server>
database.majorErrorCode()
ES2+
Syntax
database.majorErrorCode()
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1243
S e r v e r- S i d e 1 2 4 3
Description
The majorErrorCode() method of the database object contains the ODBC or database
numeric error code that is returned if an error occurs.
Example
Listing 9.72 shows how you would create a connection and test for a successful con-
nection. If the test fails, the majorErrorCode() is used when writing the error to the
page.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if (myConn.connected()) {
}else{
</server>
database.majorErrorMessage()
ES2+
Syntax
database.majorErrorMessage()
Description
The majorErrorMessage() method of the database object contains the ODBC or data-
base string error message that is returned if an error occurs.
Example
Listing 9.73 shows how you would create a connection and test for a successful con-
nection. If the test fails, the majorErrorMessage() is used when writing the error to
the page.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1244
1 2 4 4 C h a p t e r 9 : S e r v e r- S i d e
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if (myConn.connected()) {
}else{
</server>
database.minorErrorCode()
ES2+
Syntax
database.minorErrorCode()
Description
The minorErrorCode() method of the database object contains the secondary ODBC
or database numeric error code that is returned if an error occurs.
Example
Listing 9.74 shows how you would create a connection and test for a successful con-
nection. If the test fails, the minorErrorCode() is used when writing the secondary
error to the page.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if (myConn.connected()) {
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1245
S e r v e r- S i d e 1 2 4 5
}else{
</server>
database.minorErrorMessage()
ES2+
Syntax
database.minorErrorMessage()
Description
The minorErrorMessage() method of the database object contains the secondary
ODBC or database string error message that is returned if an error occurs.
Example
Listing 9.75 shows how you would create a connection and test for a successful con-
nection. If the test fails, the minorErrorMessage() is used when writing the secondary
error to the page.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if (myConn.connected()) {
}else{
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1246
1 2 4 6 C h a p t e r 9 : S e r v e r- S i d e
database.prototype
ES2+
Syntax
database.prototype.method = name
database.prototype.property = value
Description
The prototype property of the database object allows you to add methods and prop-
erties to the database object. If you are adding a method, you set the instance equal to
the name of the method you have defined.
Example
Listing 9.76 creates a new property and method of the database object. An instance is
created and the new property is set. The new method is then called to verify the prop-
erty, and, if it is incorrect (which it is), an error message is written to the page.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
S e r v e r- S i d e 1 2 4 7
</server>
database.rollbackTransaction()
ES2+
Syntax
database.rollbackTransaction()
Description
The rollbackTransaction() method of the database object will undo all actions per-
formed since the last beginTransaction() method call.
NOTE
You cannot have nested transactions.
Example
Listing 9.77 takes a commit field sent to the application from the user. If this evaluates
to true, the transaction is committed. If not, it is rolled back.
if(client.commit = “YES”){
}else{
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1248
1 2 4 8 C h a p t e r 9 : S e r v e r- S i d e
database.SQLTable()
ES2+
Syntax
database.SQLTable(sql)
Description
The SQLTable() method of the database object takes a sql SELECT statement as a
parameter and executes this query through the connection from which it was called. It
returns the results formatted in an HTML table for easy writing to a client’s page. This
is a simple table in the following format:
<table border=”1”>
<tr>
<th>column 1</th>
<th>column 2</th>
...
<th>column N</th>
</tr>
<tr>
<td>value 1 of column 1</td>
<td>value 1 of column 2</td>
...
<td>value 1 of column N</td>
</tr>
<tr>
<td>value 2 of column 1</td>
<td>value 2 of column 2</td>
...
<td>value 2 of column N</td>
</tr>
...
</table>
Example
Listing 9.78 runs a user passed query and formats the result using the SQLTable()
method. This information is then written to the user’s page.
// Open a connection.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1249
S e r v e r- S i d e 1 2 4 9
if(myConn.connected()){
</server>
database.storedProc()
ES3+
Syntax
database.storedProc(procName)
database.storedProc(procName, arg1, arg2, ... , argN)
Description
The storedProc() method of the database object creates a Stproc object that allows
you to execute a database-specific stored procedure using the connection from which
it was invoked.
As shown in the syntactical definition, you can also pass any arguments needed to the
method for processing. If you are using a stored procedure that requires arguments, or
if you want to have the procedure run using default arguments, you must pass
/Default/ as the argument. The following shows an example of passing a default
value:
var myStproc = myConn.storedProc(“sp_employees”, “/Default/”);
The scope of this procedure is restricted to the current page. Any methods of the
Stproc object must be invoked on the current page. If this is not possible, a new object
will have to be created on subsequent pages to access the properties needed.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1250
1 2 5 0 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.79 creates a connection to a database. When the connection has been verified,
the storedProc() method is used to invoke the fictitious sp_employees stored proce-
dure.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if(myConn.connected()){
myConn.beginTransaction();
</server> >
database.storedProcArgs()
ES3+
Syntax
database.storedProcArgs(procName)
database.storedProcArgs(procName, type1, type2, ... , typeN)
Description
The storedProcArgs() method of the database object creates a Stproc object that
allows you to execute a database-specific stored procedure using the connection from
which it was invoked on DB2, ODBC, and Sybase databases. If this method is invoked
on Informix or Oracle databases, it has no effect. The difference between this method
and the storedProc() method is that this method takes a type as a parameter for the
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1251
S e r v e r- S i d e 1 2 5 1
arguments passed. These types can be IN, OUT, or INOUT. The following shows an exam-
ple of passing these types:
var myStproc = myConn.storedProc(“sp_employees”, “INOUT”, “OUT”);
The scope of this procedure is restricted to the current page. Any methods of the
Stproc object must be invoked on the current page. If this is not possible, a new object
will have to be created on subsequent pages to access the properties needed.
Example
Listing 9.80 creates a connection to a database. After the connection has been verified,
the storedProc() method is used to invoke the fictitious sp_employees stored proce-
dure, and the storedProcArgs() method is used to specify the argument types.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if(myConn.connected()){
myConn.beginTransaction();
</server>
database.toString()
ES2+
Syntax
database.toString()
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1252
1 2 5 2 C h a p t e r 9 : S e r v e r- S i d e
Description
The toString() method of the database object returns a text value of the object.
When invoked on an instance of a database object, the string is returned in the fol-
lowing format:
“dbName” “uid” “dbType” “dbInstance”
If the parameter is unknown, an empty string is returned. Table 9.10 contains the value
of these returned values.
Example
Listing 9.81 creates an instance of the database object. Once created, the write()
method is used to write its string value to the page.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if(myConn.connected()){
S e r v e r- S i d e 1 2 5 3
</server>
database.unwatch()
ES3+
Syntax
database.unwatch(property)
Description
The unwatch() method of the database object is used to turn off the watch for a par-
ticular property.
Example
Listing 9.82 shows how the unwatch() method is used to stop watching the user-
defined property p.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1254
1 2 5 4 C h a p t e r 9 : S e r v e r- S i d e
// watch property
myConn.watch(“type”, alertme);
// change value
myConn.type = null;
</server>
database.watch()
ES3+
Syntax
database.watch(property, function)
Description
The watch() method of the database object is used to turn on the watch for a partic-
ular property specified by property. Any time the specified property is changed after
the watch() method has been called, the specified function is called.
Example
Listing 9.83 shows how the watch() method is used to start watching the user-defined
property p.
S e r v e r- S i d e 1 2 5 5
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
// watch property
myConn.watch(“type”, alertme);
// change value
myConn.type = null;
</server>
DbPool
ES3+
Syntax
new DbPool()
1 2 5 6 C h a p t e r 9 : S e r v e r- S i d e
Description
The DbPool object is an object that holds a “pool” of connections to a database. Before
you open a connection to a database and have the ability to run queries against it, you
should create an instance of this object. After the instance is created, connections can
be obtained from the pool as needed. The pool object itself takes all the parameters nec-
essary to make the connection. It is possible to create a pool without specifying any
parameters; however, you must pass the parameters when the first connection is
attempted.
The creation of a DbPool object is done using the format defined in the syntax defini-
tion. Each parameter is defined in Table 9.11.
S e r v e r- S i d e 1 2 5 7
Example
Listing 9.84 creates a pool of connections to an Oracle database and initializes a con-
nection from that pool. It takes a user’s UID and name that was passed in, runs a query
(based on the UID) against the database to find that user’s information, and updates her
name. If a connection is not made, the error code and message are returned to the
screen.
// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;
1 2 5 8 C h a p t e r 9 : S e r v e r- S i d e
// Focus on that line, change the name column for that user,
// and update the row.
currRow.next();
currRow.name = client.name;
currRow.updateRow(“employees”);
</server>
DbPool.connect()
ES3+
Syntax
dbpool.connect(dbType, dbInstance, uid, pwd, dbName)
Description
The connect method of the DbPool object is used to connect to a database when the
connection was not made with the initialization of the original DbPool object. The
method takes all the parameters necessary to connect to the database. Each parameter
is defined in Table 9.9.
S e r v e r- S i d e 1 2 5 9
Parameter Description
dbName The name of the database you want to log into. For Oracle,
DB2, and ODBC connections this should be a blank, “”,
string. In Oracle, the name of the database for these connec-
tions is set up in the tnsnames.ora file and is defined by the
DSN for ODBC connections. DB2 does not have a database
name and is referenced only by the dbInstance.
maxConn The maximum number of connections to the pool. This is
effectively the number of connections the pool will open to
the database.
commitFlag This flag determines whether a pending transaction is com-
mitted when connection is released. If it is set to false, the
transaction is rolled back. If it is set to true, it is committed.
Example
Listing 9.85 creates a connection pool. The connect() method is then called to open
the pool to an Oracle database. If a connection is not made, the error code and message
are returned to the screen.
// Assign the user submitted ID and name to the client object as properties.
client.uid = request.uid;
client.name = request.name;
if(myConn.connected()){
1 2 6 0 C h a p t e r 9 : S e r v e r- S i d e
</server>
DbPool.connected()
ES3+
Syntax
dbpool.connected()
Description
The connected() method of the DbPool object tells whether the pool of connections to
the database is still connected.
Example
Listing 9.86 creates a pool of connections and pulls a connection from the pool for pro-
cessing. If the connection is made, any code within that section is executed. If the con-
nection fails, the error is written to the page.
if (myConn.connected()) {
}else{
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1261
S e r v e r- S i d e 1 2 6 1
DbPool.connection()
ES3+
Syntax
dbpool.connection(name, seconds);
Description
The connection() method of the DbPool object pulls a connection from the pool. The
connection is returned from the method and can be stored in a variable to be used for
processing.
The method takes two parameters. The first parameter is a name, which is a name you
can give your connection. Because you actually store the connection in a variable, this
name’s primary function becomes one for debugging purposes. The second parameter
is a seconds value for the number of seconds you give the instance to connect.
Example
Listing 9.87 creates a pool of connections to an Oracle database and initializes a con-
nection from that pool. It takes a user’s UID and name that was passed in, runs a query
(based on the UID) against the database to find that user’s information, and updates her
name. If a connection is not made, the error code and message are returned to the
screen.
if (myConn.connected()) {
}else{
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1262
1 2 6 2 C h a p t e r 9 : S e r v e r- S i d e
DbPool.DbPool()
ES3+
Syntax
new DbPool()
Description
The DbPool() method of the DbPool object is the underlying method that creates a
“pool” of connections to a database. The creation of a DbPool object is done using the
format defined in the syntax definition. Each parameter is defined in Table 9.14.
Example
Listing 9.88 creates a pool of connections and pulls a connection from the pool for pro-
cessing. If the connection is made, any code within that section is executed. If the con-
nection fails, the error is written to the page.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1263
S e r v e r- S i d e 1 2 6 3
if (myConn.connected()) {
}else{
</server>
DbPool.disconnect()
ES3+
Syntax
dbpool.disconnect()
Description
The disconnect() method of the DbPool object disconnects all connections to a data-
base within that pool.
Example
Listing 9.89 creates a connection to an Oracle database. The next line drops the con-
nection by using the disconnect() method.
1 2 6 4 C h a p t e r 9 : S e r v e r- S i d e
</server>
DbPool.majorErrorCode()
ES3+
Syntax
dbpool.majorErrorCode()
Description
The majorErrorCode() method of the DbPool object contains the ODBC or database
numeric error code that is returned if an error occurs.
Example
Listing 9.90 shows how you would create a pool of connections and test for the con-
nection. If the test fails, the majorErrorCode() is used when writing the error to the
page.
if (myPool.connected()) {
}else{
</server>
DbPool.majorErrorMessage()
ES3+
Syntax
dbpool.majorErrorMessage()
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1265
S e r v e r- S i d e 1 2 6 5
Description
The majorErrorMessage() method of the DbPool object contains the ODBC or data-
base string error message that is returned if an error occurs.
Example
Listing 9.91 shows how you would create a pool of connections and test for the con-
nection. If the test fails, the majorErrorMessage() method is used to write the error to
the page.
if (myPool.connected()) {
}else{
</server>
DbPool.minorErrorCode()
ES3+
Syntax
dbpool.minorErrorCode()
Description
The minorErrorCode() method of the DbPool object contains the secondary ODBC or
database numeric error code that is returned if an error occurs.
Example
Listing 9.92 shows how to create a pool of connections and test for the connection. If
the test fails, the minorErrorCode() method is used to write the secondary error to the
page.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1266
1 2 6 6 C h a p t e r 9 : S e r v e r- S i d e
if (myPool.connected()) {
}else{
</server>
DbPool.minorErrorMessage()
ES3+
Syntax
dbpool.minorErrorMessage()
Description
The minorErrorMessage() method of the DbPool object contains the secondary ODBC
or database string error message that is returned if an error occurs.
Example
Listing 9.93 shows how to create a pool of connections and test for the connection. If
the test fails, the minorErrorMessage() method is used to write the secondary error to
the page.
if (myPool.connected()) {
}else{
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1267
S e r v e r- S i d e 1 2 6 7
</server>
DbPool.prototype
ES3+
Syntax
dbpool.prototype.method = name
dbpool.prototype.property = value
Description
The prototype property of the DbPool object allows you to add methods and proper-
ties to the DbPool object. If you are adding a method, you set the instance equal to the
name of the method you have defined.
Example
Listing 9.94 creates a new property and method of the DbPool object. An instance is
created and the new property is set. The new method is then called to verify the prop-
erty, and, if it is incorrect, an error message is written to the page.
1 2 6 8 C h a p t e r 9 : S e r v e r- S i d e
</server>
DbPool.storedProcArgs()
ES3+
Syntax
database.storedProcArgs(procName)
database.storedProcArgs(procName, type1, type2, ... , typeN)
Description
The storedProcArgs() method of the database object creates a Stproc object that
allows you to execute a database-specific stored procedure using the connection from
which it was invoked on DB2, ODBC, and Sybase databases. If this method is invoked
on Informix or Oracle databases, it has no affect. The difference between this method
and the storedProc() method is that this method takes a type as a parameter for the
arguments passed. These types can be IN, OUT, or INOUT. The following shows an exam-
ple of passing these types:
var myStproc = myConn.storedProc(“sp_employees”, “INOUT”, “OUT”);
The scope of this procedure is restricted to the current page. Any methods of the
Stproc object must be invoked on the current page. If this is not possible, a new object
will have to be created on subsequent pages to access the properties needed.
Example
Listing 9.95 creates a pool of connections to a database. The storedProc() method is
used to invoke the fictitious sp_employees stored procedure, and the
storedProcArgs() method is used to specify the argument types.
S e r v e r- S i d e 1 2 6 9
</server>
DbPool.toString()
ES3+
Syntax
dbpool.toString()
Description
The toString() method of the DbPool object returns a text value of the object. When
invoked on an instance of a DbPool object, the string is returned in the following for-
mat:
“dbName” “uid” “dbType” “dbInstance”
If the parameter is unknown, an empty string is returned. Table 9.15 contains the value
of these returned values.
Example
Listing 9.96 creates an instance of the DbPool object. Once created, the write()
method is used to write its string value to the page.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1270
1 2 7 0 C h a p t e r 9 : S e r v e r- S i d e
</server>
DBPool.unwatch()
ES3+
Syntax
dbpool.unwatch(property)
Description
The unwatch() method of the DbPool object is used to turn off the watch for a partic-
ular property.
Example
Listing 9.97 shows how the unwatch() method is used to stop watching the user-
defined property p.
S e r v e r- S i d e 1 2 7 1
// watch property
myPool.watch(“type”, alertme);
// change value
myPool.type = null;
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1272
1 2 7 2 C h a p t e r 9 : S e r v e r- S i d e
DBPool.watch()
ES3+
Syntax
dbpool.watch(property, function)
Description
The watch() method of the DBPool object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 9.98 shows how the watch() method is used to start watching the user-defined
property p.
S e r v e r- S i d e 1 2 7 3
// watch property
myPool.watch(“type”, alertme);
// change value
myPool.type = null;
</server>
debug()
ES2+
Syntax
debug(expression)
debug(variable)
Description
The debug function is a top-level function that is not associated with any core object.
This function is used to display the value of an expression or variable in the Trace
Information window when running the application in the JavaScript Application
Manager’s debug window.
Example
Listing 9.99, when run in the JavaScript Application Manager’s debugger, will display
the value of the request.name when encountered.
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1274
1 2 7 4 C h a p t e r 9 : S e r v e r- S i d e
deleteResponseHeader()
ES3+
Syntax
deleteResponseHeader(key)
Description
The deleteResponseHeader() function is a top-level function and is not associated
with any core object. This function is used to delete fields in the HTTP header before
it is sent back to the client. Because of when the actual header is sent in relation to the
body of the data, you should be sure to delete these fields before you call the flush()
or redirect() functions.
NOTE
The JavaScript runtime engine flushes the output buffer after 64KB of content has
been generated. You should be sure to call the deleteResponseHeader() func-
tion before this time.
Example
Listing 9.100 shows how you can delete the content-type header field before it is sent
back to the browser.
</server>
File()
ES2+
Syntax
new File(path)
Description
The File object allows you to perform various tasks such as reading and writing to a
file on your disk. The object itself has many methods to use and a prototype property
that allows a programmer to create new properties and methods of the object. Table
9.16 lists the methods accessible and a brief description of each. An instance of this
object is created by simply passing the path of the file you want to create or read.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1275
S e r v e r- S i d e 1 2 7 5
The usage of the File object is very straightforward. The methods provided allow you
to perform the various tasks needed on the files on your file system. Part of this func-
tionality of working with these files is to allow programmers to specify how they want
to open the files. A file can be opened to read, write, append, or open in binary mode.
These options are specified in the open() method in the following form:
myFile.open(“option”);
1 2 7 6 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.101 displays an option menu that allows a user to select a file to read. When
the form is submitted, the script reads the file and displays its contents on a page.
// If there was not an error, then open the file and display it.
write(‘<h3>The contents of ‘ + request.file + ‘ are as follows:</h3>’);
while(!myLog.eof()){
write(myLog.readln());
}
}
}else{
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1277
S e r v e r- S i d e 1 2 7 7
// If this page was called then write the select box to the page for
// the user to use to select which log they want to see.
</server>
</body>
</html>
File.byteToString()
ES2+
Syntax
File.byteToString(num)
Description
The byteToString() method of the File object is used to convert the numeric value
passed to its ASCII equivalent. If the method is not passed a number, an empty string
is returned.
Example
Listing 9.102 opens two files, one for reading and the other for appending. Bytes are
then read using the readByte() method from the first file, converted back to string
characters using the byteToString() method, and written to the second file. Both files
are closed when the process has completed.
// Open the log file for reading and the summary file for
// appending.
myLog.open(“r”);
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1278
1 2 7 8 C h a p t e r 9 : S e r v e r- S i d e
</server>
File.clearError()
ES2+
Syntax
file.clearError()
Description
The clearError() method of the File object clears the file error status and the value
returned by the eof() method.
Example
Listing 9.103 opens a file for reading. If the operation returned an error, the error is
written to the page. If there was an error, it is cleared after writing it.
if (myLog.error() == 0) {
}else{
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1279
S e r v e r- S i d e 1 2 7 9
</server>
File.close()
ES2+
Syntax
file.close()
Description
The close() method of the File object closes the file on which it has been invoked.
This method returns true if it was successful and false if it was unsuccessful.
Example
Listing 9.104 shows how to open a file and then close it.
</server>
File.constructor
ES2+
Syntax
file.constructor
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1280
1 2 8 0 C h a p t e r 9 : S e r v e r- S i d e
Description
The constructor property of the File object specifies the function that creates the
object.
Example
Listing 9.2105 shows an example of the constructor property.
if(myLog.constructor == File){
write(“Object created”);
}
</server>
File.eof()
ES2+
Syntax
file.eof()
Description
The eof() method of the File object returns true if the position of the pointer within
the file is past the end of the file. It returns false otherwise.
Example
Listing 9.106 reads a file and writes its contents to the page until the end of the file is
found with the eof() method.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1281
S e r v e r- S i d e 1 2 8 1
Listing 9.106 Reading a File Until You Come to the End of It, Which Can
Be Evaluated Using the eof() Method
<server>
</server>
File.error()
ES2+
Syntax
file.error()
Description
The error() method of the File object returns the operating system error code when
an error occurs opening a file. This method returns 0 if there is no error, and –1 if the
file you invoke the method on is unable to be opened.
Example
Listing 9.107 opens a file for reading. If there was a problem during this operation, the
error is written to the user’s page.
1 2 8 2 C h a p t e r 9 : S e r v e r- S i d e
}else{
</server>
File.exists()
ES2+
Syntax
file.exists()
Description
The exists() method of the File object returns a boolean value based on the exis-
tence of the file in which it was invoked. If the file exists, the method returns true. It
returns false if the file does not exist.
Example
Listing 9.108 opens a file and then checks to see whether it exists.
Listing 9.108 Using the exists() Method to See Whether a File Exists
<server>
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1283
S e r v e r- S i d e 1 2 8 3
File.flush()
ES2+
Syntax
file.flush()
Description
The flush() method of the File object is used to write buffered information to a file.
This information is placed in a buffer when the write(), writeln(), and writeByte()
methods are used. Note that this is not the same as the top-level flush function.
Example
Listing 9.109 opens a file for reading and another file for writing. If the file for read-
ing exists, a string is written to the other file. The flush() method is used to write the
buffered information to the file.
myLog.open(“r”);
mySummary.open(“w”);
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1284
1 2 8 4 C h a p t e r 9 : S e r v e r- S i d e
File.getLength()
ES2+
Syntax
file.getLength()
Description
The getLength() method of the File object returns the number of characters in a text
file or the number of bytes in a binary file. If the method is unsuccessful, –1 is returned.
Example
Listing 9.110 opens a file for reading and another file for writing. The getLength()
method is used in a for loop to determine when to stop reading from the file.
mySummary.flush();
</server>
File.getPosition()
ES2+
Syntax
file.getPosition()
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1285
S e r v e r- S i d e 1 2 8 5
Description
The getPosition() method of the File object returns the zero-based index position of
the current pointer in the file. If the pointer is on the first character, 0 is returned. If
there is an error, -1 is returned.
Example
Listing 9.111 loops through each character, printing it on a new line next to its indexed
location.
mySummary.flush();
</server>
File.open()
ES2+
Syntax
file.open(option)
Description
The open() method of the File object is used to open a file to read, write, and/or
append to. The method returns true if it is successful and false otherwise. The options
passed determine the mode in which the file is opened. The options are specified in
Table 9.18.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1286
1 2 8 6 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.112 shows how to open a file in read mode.
// Initialize a file
var myLog = new File(“/data/logs/today.log”);
</server>
File.prototype
ES3+
Syntax
file.prototype.method = name
file.prototype.property = value
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1287
S e r v e r- S i d e 1 2 8 7
Description
The prototype property of the File object allows you to add methods and properties
to the File object. If you are adding a method, you set the instance equal to the name
of the method you have defined.
Example
Listing 9.113 creates a new property and method of the File object. An instance is cre-
ated and the new property is set. The new method is then called to verify the property,
and, if it is incorrect (which it is), an error message is written to the page.
// Initialize a file
var myLog = new File(“/data/logs/today.log”);
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1288
1 2 8 8 C h a p t e r 9 : S e r v e r- S i d e
File.read()
ES2+
Syntax
file.read(num)
Description
The read() method of the File object starts at the current pointer in the file and reads
num characters in the file. If you try to read characters past the end of the file, the
method will read all the characters and stop. Use the readByte() method if you are try-
ing to read the byte data.
Example
Listing 9.114 reads information from a text file and writes every other character to the
user’s page. The setPosition() method is used to move the pointer correctly, and the
read() method is used to read the data.
</server>
File.readByte()
ES2+
Syntax
file.readByte(num)
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1289
S e r v e r- S i d e 1 2 8 9
Description
The readByte() method of the File object starts at the current pointer in the file and
reads num bytes in the file. If you try to read bytes past the end of the file, the method
will read all the bytes and stop. Use the read() method if you are trying to read the
characters in text data.
Example
Listing 9.115 reads information from a text file and writes every other byte to the user’s
page. The setPosition() method is used to move the pointer correctly, and the
readByte() method is used to read the data.
</server>
File.readln()
ES2+
Syntax
file.readln()
Description
The readln() method of the File object starts at the current pointer position and reads
the rest of the line. When the method is complete, it will return the pointer to the first
character on the next line.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1290
1 2 9 0 C h a p t e r 9 : S e r v e r- S i d e
NOTE
The return (\r) and newline (\n) )characters are not contained in the string this
method returns. However, the newline character determines when the end of the
line is reached.
Example
Listing 9.116 reads in the first line of a file and writes it to the user’s page.
</server> >
File.setPosition()
ES2+
Syntax
file.setPosition(num)
file.setPosition(num, refPoint)
Description
The setPosition() method of the File object sets the pointer’s position to a relative
num location in the file. By default, this is relative to the beginning of the file, but you
can pass a reference point to determine where this relative location is located. The pos-
sible values of this reference point are listed in Table 9.19.
S e r v e r- S i d e 1 2 9 1
Example
Listing 9.117 uses the setPosition() method to access every other character in the
file.
</server>
File.stringToByte()
ES2+
Syntax
File.stringToByte(string)
Description
The stringToByte() method of the File object is used to convert the first character of
the string passed to its binary equivalent.
Example
Listing 9.118 opens two files, one for reading and the other for appending. Strings are
then read using the read() method from the first file, converted back to byte charac-
ters using the stringToByte() method, and then written to the second file. Both files
are closed when the process has after completed.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1292
1 2 9 2 C h a p t e r 9 : S e r v e r- S i d e
// Open the log file for reading and the summary file for
// appending.
myLog.open(“rb”);
mySummary.open(“ab”);
</server>
File.unwatch()
ES3+
Syntax
file.unwatch(property)
Description
The unwatch() method of the File object is used to turn off the watch for a particular
property.
Example
Listing 9.119 shows how the unwatch() method is used to stop watching the user-
defined property p.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1293
S e r v e r- S i d e 1 2 9 3
// Initialize a file.
var myLog = new File(“/data/logs/today.log”);
// watch property
myLog.watch(“type”, alertme);
// change value
myLog.type = null;
1 2 9 4 C h a p t e r 9 : S e r v e r- S i d e
</server>
File.watch()
ES3+
Syntax
file.watch(property, function)
Description
The watch() method of the File object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 9.120 shows how the watch() method is used to start watching the user-defined
property p.
S e r v e r- S i d e 1 2 9 5
// Initialize a file.
var myLog = new File(“/data/logs/today.log”);
// watch property
myLog.watch(“type”, alertme);
// change value
myLog.type = null;
</server>
File.write()
ES2+
Syntax
file.write(string)
Description
The write() method of the File object writes the string passed to the method to the
file on which it was invoked. The method returns true if it was successful and false
otherwise. You should use the read() or readln() methods to read any string infor-
mation from other files that you want to write. If you need to write binary information,
use the writeByte() method.
Example
Listing 9.121 writes “Hello, World!” to the summary file opened.
1 2 9 6 C h a p t e r 9 : S e r v e r- S i d e
</server>
File.writeByte()
ES2+
Syntax
file.writeByte(byte)
Description
The writeByte() method of the File object writes the byte passed to the method to
the file on which it was invoked. The method returns true if it was successful and
false otherwise. You should use the readByte() method to read any byte information
from other files that you want to write. If you need to write text information, use the
write() method.
Example
Listing 9.122 reads data from a binary file and writes it to another file.
// Open the log file for reading and the summary file for
// appending.
myLog.open(“br”);
mySummary.open(“ba”);
S e r v e r- S i d e 1 2 9 7
myByte = myLog.readByte(1);
mySummary.writeByte(myByte);
}
</server>
File.writeln()
ES2+
Syntax
file.writeln(string)
Description
The writeln() method of the File object writes the string passed to the method, fol-
lowed by a carriage return to the file on which it was invoked. The method returns true
if it was successful and false otherwise. You should use the read() or readln() meth-
ods to read any string information from other files you want to write. If you need to
write binary information, use the writeByte() method.
Example
Listing 9.123 writes the line “Hello, World!” to the summary file opened.
1 2 9 8 C h a p t e r 9 : S e r v e r- S i d e
</server>
flush()
ES2+
Syntax
flush()
Description
The flush() function is a top-level function that is not associated with any object. The
JavaScript runtime buffers the HTML page it is constructing in memory, and then sends
it to the client after 64KB has been obtained. This function can be used to send this data
on demand, which is useful when done before large database queries. Note this is not
the same flush as the File.flush() method.
NOTE
The flush() function updates the cookie file as part of the HTTP header. If you
are using a client cookie to maintain the client object, you should make any
changes to this object before calling the flush() function.
Example
Listing 9.124 uses the flush() function to flush the buffer to the page after the initial
write.
Listing 9.124 Using the flush() Function to Flush the Buffer to the
Page
<server>
</server>
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1299
S e r v e r- S i d e 1 2 9 9
getOptionValue()
Nes2+
Syntax
getOptionValue(key, num)
Description
The getOptionValue() function is a top-level function that is not associated with any
object. This function returns the same value as the client-side Option.text property.
The key passed in as an argument represents the name attribute of the <select> tag,
whereas the num parameter is the indexed position of the selected option. Specifying
num to 0 can reference the first selected option, which might not be the first option.
Example
Listing 9.125 displays a multi-select option box that allows a user to select different
sports. When the Submit button is clicked, the form is sent back to itself and the script
then uses a for loop and the getOptionValue() function to write the submitted selec-
tions to the user’s page.
// Iterate through the options and write which ones were selected.
for(var i = 0; i < counter; i++){
1 3 0 0 C h a p t e r 9 : S e r v e r- S i d e
</server>
</body>
</html>
getOptionValueCount()
ES2+
Syntax
getOptionValueCount(key)
Description
The getOptionValueCount() function is a top-level function that is not associated
with any object. This function returns the number of selected options passed to the
function. The key parameter represents the name attribute of the <select> tag on which
you want to invoke the function.
Example
Listing 9.126 shows how to use the getOptionValueCount() function to determine
how many options were selected in a “sports” select box.
</server>
Lock()
ES3+
Syntax
new Lock()
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1301
S e r v e r- S i d e 1 3 0 1
Description
A Lock() object is used when you enter a section of code that can only be accessed
from a single user at a time. Not implementing an instance of this object when needed
can cause you to run out of system resources and will generate a runtime error. This
object has only one property, which is the prototype property.
This property can be used to create new methods and properties for the Lock() object.
Table 9.20 contains the methods accessible from this object.
Example
Listing 9.127 shows how you would create a new Lock() object instance. See the
examples for Lock.lock() and Lock.unlock() for examples on locking and unlocking
your code segments.
</server>
Lock.constructor
ES2+
Syntax
lock.constructor
Description
The constructor property of the Lock object specifies the function that creates the
object.
Example
Listing 9.128 shows an example of the constructor property.
17 0672321416 CH09a was 13a 7/24/01 12:41 PM Page 1302
1 3 0 2 C h a p t e r 9 : S e r v e r- S i d e
if(myLock.constructor == Lock){
write(“Object created”);
}
</server>
Lock.isValid()
ES3+
Syntax
lock.isValid()
Description
The isValid() method of the Lock object verifies whether the lock was properly con-
structed. The method returns true if the lock was constructed successfully and false
otherwise.
Example
Listing 9.129 shows how you can check whether a lock was properly constructed with
an if statement.
</server>
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1303
S e r v e r- S i d e 1 3 0 3
Lock.lock()
ES3+
Syntax
lock.lock()
Description
The lock() method of the Lock object locks the code in which you are working until
you perform an unlock. If the code is already locked, this method will wait until it can
get the lock, a timeout occurs, or an error occurs.
Example
Listing 9.130 assumes that there is a project object with a counter property, num.
Because you only want to increment the counter with each new user request, it must be
locked.
</server>
Lock.prototype
ES3+
Syntax
lock.prototype.method = name
lock.prototype.property = value
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1304
1 3 0 4 C h a p t e r 9 : S e r v e r- S i d e
Description
The prototype property of the Lock object allows you to add methods and properties
to the Lock object. If you are adding a method, you set the instance equal to the name
of the method you have defined.
Example
Listing 9.131 creates a new property and method of the Lock object. An instance is cre-
ated and the new property is set. The new method is then called to verify the property,
and, if it is incorrect, an error message is written to of the page.
</server>
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1305
S e r v e r- S i d e 1 3 0 5
Lock.unlock()
ES3+
Syntax
lock.unlock()
Description
The unlock() method of the Lock object unlocks the code you have locked. This
method returns true if the unlocking was successful and false otherwise.
Example
Listing 9.132 assumes that there is a project object with a counter property, num.
Because you only want to increment the counter with each new user request, it must be
locked. After the counter has been incremented, the project is unlocked.
</server>
Lock.unwatch()
ES3+
Syntax
lock.unwatch(property)
Description
The unwatch() method of the Lock object is used to turn off the watch for a particular
property.
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1306
1 3 0 6 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.133 shows how the unwatch() method is used to stop watching the user-
defined property p.
// watch property
project.myLock.watch(“type”, alertme);
// change value
project.myLock.type = null;
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1307
S e r v e r- S i d e 1 3 0 7
</server>
Lock.watch()
ES3+
Syntax
lock.watch(property, function)
Description
The watch() method of the Lock object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 9.134 shows how the watch() method is used to start watching the user-defined
property p.
1 3 0 8 C h a p t e r 9 : S e r v e r- S i d e
// watch property
project.myLock.watch(“type”, alertme);
// change value
project.myLock.type = null;
</server>
ObjectContext
ASP1+
Syntax
Core ASP environment object
Description
The ObjectContext object is a core ASP environment object. The events and methods
of this object are used to commit or abort a transaction that has been initiated by a
script. This object requires the <%@ Transaction = Required %> directive to execute
properly within your scripts. Table 9.21 contains the events and methods of this object.
S e r v e r- S i d e 1 3 0 9
Example
Listing 9.135 assumes that the variable processData has been set to true or false
previously and, based on its value, either processes the transaction or aborts it.
ObjectContext.OnTransactionAbort
ASP1+
Syntax
function onTransactionAbort(){
code
}
Description
The onTransactionAbort event of the ObjectContext object occurs when a transac-
tion is aborted. When this happens, IIS calls the onTransactionAbort() function, if
one is defined, and executes code.
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1310
1 3 1 0 C h a p t e r 9 : S e r v e r- S i d e
Example
In Listing 9.136 we have defined the onTransactionAbort function that will be exe-
cuted if a transaction is aborted. In the case this event is fired, a message will be written
to output.
ObjectContext.OnTransactionCommit
ASP1+
Syntax
function onTransactionCommit(){
code
}
Description
The onTransactionCommit event of the ObjectContext object occurs when a transac-
tion has completed. When this happens, IIS calls the onTransactionCommit() func-
tion, if one is defined, and executes code.
Example
In Listing 9.137 we have defined the onTransactionCommit() function that will be
executed if a transaction is committed. In the case this event is fired, a message will be
written to output.
ObjectContext.SetAbort()
ASP1+
Syntax
ObjectContext.SetAbort()
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1311
S e r v e r- S i d e 1 3 1 1
Description
The SetAbort() method of the ObjectContext object aborts a transaction.
Example
In Listing 9.138 we have defined the onTransactionAbort() function that will be exe-
cuted when the transaction is aborted, which we will induce with the SetAbort()
method. When fired, a message will be written to be output.
</script>
ObjectContext.SetComplete()
ASP1+
Syntax
ObjectContext.SetComplete()
Description
The SetComplete() method of the ObjectContext object overrides any previous calls
to the SetAbort() method.
Example
In Listing 9.139 we have defined the onTransactionAbort() function that will be exe-
cuted when the transaction is aborted, which we will induce with the SetAbort()
method. When fired, we will stop the abort before the message is written to output.
1 3 1 2 C h a p t e r 9 : S e r v e r- S i d e
</script>
project
ES2+
Syntax
Created by the server-side JavaScript runtime when the application starts.
Description
The project object is shared by all users accessing the application. This object is cre-
ated when the application is started, and destroyed when it is stopped. The project
object is often used to store global properties that need to be accessed or modified by
all user sessions. A common use of this object might be a counter holding the number
of users who have accessed your application.
The object itself has no default properties, but properties can be created simply by
specifying a name and value for the property. The following is an example of how to
create a property and assign it a value, which is the IP address of the client requesting
the application.
var project.lastIP = request.ip;
Table 9.22 contains a list and a description of the methods of the project object.
Example
Listing 9.140 shows how you can create and increment a counter property of the pro-
ject object. Before this counter is incremented, the project is locked and then is
unlocked afterward.
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1313
S e r v e r- S i d e 1 3 1 3
</server>
project.lock()
ES2+
Syntax
project.lock()
Description
The lock() method of the project object locks the code in which you are working
until you perform an unlock. If the code is already locked, this method will wait until
it can get the lock, a timeout occurs, or an error occurs.
Example
Listing 9.141 sets a project object with a counter property, hitCount. Because you
only want to increment the counter with each new user request, it must be locked.
</server>
project.unlock()
ES2+
Syntax
project.unlock()
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1314
1 3 1 4 C h a p t e r 9 : S e r v e r- S i d e
Description
The unlock() method of the project object unlocks the code that you have locked.
This method returns true if the unlocking was successful and false otherwise.
Example
Listing 9.142 sets a project object with a counter property, hitCount. Because you
only want to increment the counter with each new user request, it must be locked. After
the counter has been incremented, the project is unlocked.
</server>
project.unwatch()
ES3+
Syntax
project.unwatch(property)
Description
The unwatch() method of the project object is used to turn off the watch for a par-
ticular property.
Example
Listing 9.143 shows how the unwatch() method is used to stop watching the user-
defined property p.
S e r v e r- S i d e 1 3 1 5
project.type = “work”;
// watch property
project.watch(“type”, alertme);
// change value
project.type = null;
</server>
project.watch()
ES3+
Syntax
project.watch(property, function)
Description
The watch() method of the project object is used to turn on the watch for a particu-
lar property specified by property. Any time the specified property is changed after
the watch() method has been called, the specified function is called.
Example
Listing 9.144 shows how the watch() method is used to start watching the user-defined
property p.
project.type = “work”;
// watch property
project.watch(“type”, alertme);
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1316
1 3 1 6 C h a p t e r 9 : S e r v e r- S i d e
</server>
redirect()
ES2+
Syntax
redirect(URL)
Description
The redirect() function is a top-level function that is not associated with any core
object. This function is used to redirect the requesting browser to the URL it was
passed as a parameter.
NOTE
Use the addClient() function to preserve client object properties and their val-
ues.
Example
Listing 9.145 checks whether the browser asking for the page is Internet Explorer. The
redirect() function is then used to redirect the browser accordingly.
</server>
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1317
S e r v e r- S i d e 1 3 1 7
registerCFunction()
ES2+
Syntax
registerCFunction(JSFuncName, libPath, CFunc)
Description
registerCFunction()is a top-level function that is not associated with any core
object. RegisterCFunction() is used to register a C function in a shared library as a
JavaScript function so it can be used in your scripts. These libraries are the pre-built
.dll files on Windows machines and .so files on Unix machines.
RegisterCFunction() takes the JavaScript name you want to assign the C function,
the path to the library, and the actual name of the C function you want to register in the
library. The function returns a boolean value based on the success of the registration.
After you call this function, you can use the C library with the server-side JavaScript
callC() function. callC() takes the JavaScript name you assigned and any parameters
that need to be passed to the function.
Example
Listing 9.146 registers an external C library, extlib.dll that contains a function
named getMyDate. The registration of this function assigns the name JSExtLib to be
used within the script. If the function successfully registers, the callC function is used
to call the C function and pass it two parameters. The results are written to the user’s
page. If the function does not register properly, an error is written to the user’s page.
</server>
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1318
1 3 1 8 C h a p t e r 9 : S e r v e r- S i d e
Request
ASP1+
Syntax
Core ASP environment object
Description
The Request object is a core ASP environment object. This object provides a means to
retrieve HTTP information passed to the server from the user agent during a request.
Table 9.23 contains the collections, methods, and a property of this object.
Example
Listing 9.147 shows how you can use the Request object to access a specific querys-
tring key, and then write out its value.
Request.BinaryRead()
ASP1+
Syntax
Request.BinaryRead(num)
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1319
S e r v e r- S i d e 1 3 1 9
Description
The BinaryRead() method of the Request object retrieves data sent to the server in a
POST request, and stores the information in an array of unsigned bytes, called a
SafeArray. The num represents the number of bytes to be read into the array.
Example
Listing 9.148 shows how you can check the length of a POST, and then read the data
into a SafeArray.
</script>
Request.ClientCertificate
ASP1+
Syntax
Request.ClientCertificate(field)
Request.ClientCertificate(subfield)
Description
The ClientCertificate collection of the Request object retrieves the certification
fields from a request. If the request uses the SSL3.0/PCT1 protocol (also referred to as
HTTPS) to connect to a server, the server will request certification at which time the
browser sends the certification fields. If no certificate is sent, the ClientCertificate
collection returns EMPTY.
Table 9.24 contains a list of fields that can be passed to this collection, whereas Table
9.25 contains a list of possible subfields.
1 3 2 0 C h a p t e r 9 : S e r v e r- S i d e
NOTE
To use the Flags, you must include the client-certificate include file
(cerjavas.inc) in your ASP page. These files are installed in the
\Inetpub\ASPSamp\Samples directory.
The syntax for the use of subfields can be a bit strange looking, so here is a quick
example. Notice that the subfield is actually the result of concatenating the field in
our previous table with the subfield identifier.
Request.ClientCertificate(“SubjectCN”);
Example
In Listing 9.149 we write out the Subject field of a client certificate present in a
request.
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1321
S e r v e r- S i d e 1 3 2 1
Request.Cookies
ASP1+
Syntax
Request.Cookies(name)
Request.Cookies(name).HasKeys
Request.Cookies(name)(subkey)
Description
The Cookies collection of the Request object provides access to any cookies passed to
the server. You can retrieve the value of the cookie by passing the name of the cookie.
Additionally, you can pass the HasKeys attribute to check if the collection is a cookie
dictionary. If so, you can pass the subkey property to retrieve any subkey values from
cookie dictionaries.
Example
Listing 9.150 shows how you can use the AppendToLog() method in conjunction with
the Request.Cookies collection to access and write the value of a cookie named ID to
the end of the log file.
Request.Form
ASP1+
Syntax
Request.Form(name)
Request.Form(name)(num)
Description
The Form collection of the Request object retrieves the values of form elements that
have been POSTed to the server. This collection is used by passing the name of the ele-
ment you want to retrieve. If multiple values are passed for a given name, you can spec-
ify the num location of the value you want to retrieve.
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1322
1 3 2 2 C h a p t e r 9 : S e r v e r- S i d e
NOTE
This collection can only hold 100KB of information. If your POST is larger than
that, you should use the Request.ReadBinary() method.
Example
Listing 9.151 shows how you can check the number of values for a given form name,
and then write the last value to the page.
Request.Form.Form.Count
ASP1+
Syntax
Request.Form(name).Count
Description
The Count property of the Form collection of the Request object contains the total num-
ber of values for a given form element that has been POSTed to the server. This col-
lection is used by passing the name of the element you want to retrieve a count for.
Example
Listing 9.152 shows how you can check the number of values for a given form name,
and then write the last value to the page.
S e r v e r- S i d e 1 3 2 3
Request.QueryString
ASP1+
Syntax
Request.QueryString(name)
Request.QueryString(name)(num)
Description
The QueryString collection of the Request object retrieves the values of form ele-
ments that have been passed to the server using the GET method. This collection is used
by passing the name of the element you want to retrieve. If multiple values are passed
for a given name, you can specify the num location of the value you want to retrieve.
NOTE
A QueryString is signified as all characters after the first occurrence of the “?”
character.
Example
Listing 9.153 shows how you can check the number of values for a given querystring
name, and then write the last value to the page.
Request.QueryString.Count
ASP1+
Syntax
Request.QueryString(name).Count
Description
The Count property of the QueryString collection of the Request object contains the
total number of values for a given form element that has been sent to the server in a GET
request. This collection is used by passing the name of the element you want to retrieve
a count for.
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1324
1 3 2 4 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.154 shows how you can check the number of values for a given form element,
and then write the last value to the page.
Request.ServerVariables
ASP1+
Syntax
Request.ServerVariables(name)
Description
The ServerVariables collection of the Request object retrieves a list of predefined
server environment variables. You can access the value of a given variable by passing
the variable’s name. Table 9.26 contains a list of possible values for name.
S e r v e r- S i d e 1 3 2 5
Variable Description
CERT_ISSUER Issuer field of the client certificate (O=MS, OU=IAS, CN=user
name, C=USA).
CERT_KEYSIZE Number of bits in Secure Sockets Layer connection key
size.
CERT_SECRETKEYSIZE Number of bits in server certificate private key.
CERT_SERIALNUMBER Serial number field of the client certificate.
CERT_SERVER_ISSUER Issuer field of the server certificate.
CERT_SERVER_SUBJECT Subject field of the server certificate.
CERT_SUBJECT Subject field of the client certificate.
CONTENT_LENGTH Length of the content as given by the client.
CONTENT_TYPE Data type of the content.
GATEWAY_INTERFACE Revision of the CGI specification used by the server.
HTTP_<HeaderName> Value stored in the header HeaderName.
HTTP_ACCEPT Returns the value of the Accept header.
HTTP_ACCEPT_LANGUAGE Returns a string describing the language to use for dis-
playing content.
HTTP_USER_AGENT Returns a string describing the browser that sent the
request.
HTTP_COOKIE Returns the cookie string that was included with the
request.
HTTP_REFERER Returns a string containing the URL of the page that
referred the request, but does not include redirect
requests.
HTTPS Returns ON if request came in through SSL or returns OFF if
the request is for a non-secure channel.
HTTPS_KEYSIZE Number of bits in the Secure Sockets Layer connection
key size.
HTTPS_SECRETKEYSIZE Number of bits in the server certificate private key.
HTTPS_SERVER_ISSUER Issuer field of the server certificate.
HTTPS_SERVER_SUBJECT Subject field of the server certificate.
INSTANCE_ID Textual format ID for the IIS instance.
INSTANCE_META_PATH Metabase path for the instance of IIS.
LOCAL_ADDR Returns the Server Address on which the request came in.
This is important on multihomed machines where multiple
IP addresses can be bound to the machine.
LOGON_USER Windows account the user is logged into.
PATH_INFO Extra path information as given by the client.
PATH_TRANSLATED Translated version that takes the path and performs any
necessary virtual-to-physical mapping.
QUERY_STRING Query information stored in the string following the ques-
tion mark (?).
REMOTE_ADDR IP address of the remote host.
17 0672321416 CH09a was 13a 7/24/01 12:42 PM Page 1326
1 3 2 6 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.155 shows how you can write out the user agent string of the browser mak-
ing the request.
Request.TotalBytes
ASP1+
Syntax
Request.TotalBytes
Description
The TotalBytes property of the Request object is a read-only property that contains
the total number of bytes the user agent sent in the body of the request.
Example
Listing 9.156 shows how you can check the length of a POST, and then read the data
into a SafeArray.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1327
S e r v e r- S i d e 1 3 2 7
</script>
request
ES2+
Syntax
Core object created by JavaScript runtime for each client request.
Description
The request object contains specific information about the client’s request. The object
itself has several properties, as well as any properties that you might be passing from
a form. This object also inherits Object.watch() and Object.unwatch(), which are
defined in Chapter 7, “Core Language.” The properties of this object are listed in
Table 9.27.
Example
Listing 9.157 writes the various properties of a request to the page.
1 3 2 8 C h a p t e r 9 : S e r v e r- S i d e
</server>
request.agent
ES2+
Syntax
request.agent
Description
The agent property of the request object contains the user agent string of the request-
ing application. The following is an example of a user agent string for Navigator 4.5 on
Windows 98.
Mozilla/4.5 (Win98; U)
You can use several methods of the String object in conjunction with this property to
determine the type and version of the browser requesting the page.
Example
Listing 9.158 examines the requesting browser’s agent string and redirects Internet
Explorer browsers to an alternative page.
</server>
request.formKey
ES2+
Syntax
request.formKey
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1329
S e r v e r- S i d e 1 3 2 9
Description
The formKey property of the request object represents any form key that is sent. A key
is specified by the name attribute in any element of an HTML <form>.
Example
Listing 9.159 shows how you can have a form with a “sports” key and use the
request.formKey property to read the value.
}else{
// If this page was called and a form was not submitted, then write the
// form to the page for the user to use.
</server>
</body>
</html>
request.imageX
ES2+
Syntax
request.imageX
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1330
1 3 3 0 C h a p t e r 9 : S e r v e r- S i d e
Description
The imageX property of the request object contains the x coordinate of the imagemap
request sent from the browser. These requests come in the following form, where x is
the numeric x-coordinate and y is the numeric y coordinate:
http://www.purejavascript.com/clickthru.html?x,y
Example
Listing 9.160 pulls out the x and y coordinates passed in the request and writes them
to the user’s page.
</server>
request.imageY
ES2+
Syntax
request.imageY
Description
The imageY property of the request object contains the y coordinate of the imagemap
request sent from the browser. These requests come in the following form, where x is
the numeric x coordinate and y is the numeric y coordinate:
http://www.purejavascript.com/clickthru.html?x,y
Example
Listing 9.161 pulls out the x and y coordinates passed in the request and writes them
to the user’s page.
</server>
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1331
S e r v e r- S i d e 1 3 3 1
request.ip
ES2+
Syntax
request.ip
Description
The ip property of the request object specifies the IP address of the requesting client.
Example
Listing 9.162 checks the IP address of the requesting client. If the IP address is not
within the correct domain, the browser is redirected to an “unauthorized IP” page.
}else{
</server>
request.method
ES2+
Syntax
request.method
Description
The method property of the request object specifies the HTTP method used in the
request. This can either be PUT or GET, depending on the submission type.
Example
Listing 9.163 shows how you can use the same page to display a form and interpret it.
If the method is POST, you know it was a form submission. If it was GET, you display
the form.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1332
1 3 3 2 C h a p t e r 9 : S e r v e r- S i d e
}else{
</server>
request.protocol
ES2+
Syntax
request.protocol
Description
The protocol property of the request object specifies the version of the HTTP proto-
col used in the request. This version is conveyed in the following format:
HTTP/1.0
Example
Listing 9.164 takes a look at the protocol property to see whether the request is HTTP
1.1. You can then insert any processing code needed, based on the protocol version sup-
ported by the client.
}else{
S e r v e r- S i d e 1 3 3 3
</server>
request.unwatch()
ES3+
Syntax
request.unwatch(property)
Description
The unwatch() method of the request object is used to turn off the watch for a par-
ticular property.
Example
Listing 9.165 shows how the unwatch() method is used to stop watching the user-
defined property p.
// watch property
request.watch(“agent”, alertme);
// change value
request.agent = null;
</server>
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1334
1 3 3 4 C h a p t e r 9 : S e r v e r- S i d e
request.watch()
ES3+
Syntax
request.watch(property, function)
Description
The watch() method of the request object is used to turn on the watch for a particu-
lar property specified by property. Any time the specified property is changed after
the watch() method has been called, the specified function is called.
Example
Listing 9.166 shows how the watch() method is used to start watching the user-defined
property p.
// watch property
request.watch(“agent”, alertme);
// change value
request.agent = null;
</server>
Response
ASP1+
Syntax
Core ASP environment object
Description
The Response object is a core ASP environment object. This object is used to send data
back to the user agent making the request. Table 9.28 contains the list of collections,
methods, and properties in this object.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1335
S e r v e r- S i d e 1 3 3 5
Example
In Listing 9.167 we use the Write() method of the Response object to write “Hello
World” to the page.
Response.AddHeader()
ASP1+
Syntax
Response.AddHeader(name, value)
Description
The AddHeader() method of the Response object is used to add the name header, which
is assigned value, to the HTTP header.
Example
In Listing 9.168 we show how you can add a P3P header pointing to your privacy pol-
icy reference file.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1336
1 3 3 6 C h a p t e r 9 : S e r v e r- S i d e
Response.AppendToLog()
ASP1+
Syntax
Response.AppendToLog(string)
Description
The AppendToLog() method/property of the Response object appends string to the end
of the log entry for the given request. If called multiple times for a given request, it will
continue appending to the end of that log entry.
Example
Listing 9.169 shows how you can use the AppendToLog() method in conjunction with
the Request.Cookies collection to access and write the value of a cookie named ID to
the end of the log file.
Response.BinaryWrite()
ASP1+
Syntax
Response.BirnaryWrite(data)
Description
The BinaryWrite() method of the Response object is used to write non-string data
back to the user agent. This parameter should be of type VT_ARRAY or VT_UI1, which is
a variant array of unsigned one-byte characters.
Example
In Listing 9.170 we assume that you have an object that will create binary data, and
then we use the BinaryWrite() method to write out the data.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1337
S e r v e r- S i d e 1 3 3 7
Response.Buffer
ASP1+
Syntax
Response.Buffer = boolean
Description
The Buffer property of the Response object specifies whether the server should buffer
page output or not. When boolean is TRUE, all data is buffered and is not sent to the
user agent until the page has finished processing, or the Response.End() or
Response.Flush() methods are called. Because this property cannot be set after data
has been sent to the agent, this needs to be set in the first line of your file.
Example
Listing 9.171 shows how to tell the server to buffer the content, and then send it when
the Response.Flush() method is called.
Response.CacheControl
ASP1+
Syntax
Response.CacheControl = string
Description
The CacheControl property of the Response object is used to override the Private
default string by setting it to Public. The default setting states that only private
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1338
1 3 3 8 C h a p t e r 9 : S e r v e r- S i d e
caches can cache the content generated by this page, whereas a Public setting informs
proxies and other servers that they can cache the content.
Example
Listing 9.172 shows how you can use the CacheControl property to allow proxies to
cache ASP content.
Response.Charset
ASP1+
Syntax
Response.Charset = charset
Description
The Charset property of the Response object appends the charset to the end of the
content-type HTTP header directive.
Example
Listing 9.173 shows how you can append ISO-LATIN-7 to the end of the content-type
is header.
Response.Clear()
ASP1+
Syntax
Response.Clear()
Description
The Clear() method of the Response object is used to erase any buffered HTTP
response body output, but not HTTP response header output. For this method to work,
you must first set Response.Buffer = TRUE.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1339
S e r v e r- S i d e 1 3 3 9
Example
Listing 9.174 shows how you can use the Clear() method to clear any buffered HTTP
response body data.
// Turn on buffering.
Response.Buffer = TRUE;
Response.ContentType
ASP1+
Syntax
Response.ContentType = contentType
Description
The ContentType property of the Response object sets the content-type header direc-
tive. If no value is passed, text/html is assumed.
Example
Listing 9.175 shows how you can pass back your content as plain ASCII text, rather
than HTML.
Response.Cookies
ASP1+
Syntax
Response.Cookies(name) = value
Response.Cookies(name).attribute = value
Response.Cookies(name)(subkey) = value
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1340
1 3 4 0 C h a p t e r 9 : S e r v e r- S i d e
Description
The Cookies collection of the Response object creates and stores any cookies to pass
to the user agent. You can create a cookie called name of value using the first syntacti-
cal method. It is also possible to pass a subkey, which creates a cookie dictionary and
inserts value as a key in that dictionary. Additionally, you can pass a specific
attribute to just set or change part of the cookie.
Example
Listing 9.176 shows how you can use the Response.Cookie() collection to create, col-
lect, and pass back a cookie with two subkeys.
Response.End()
ASP1+
Syntax
Response.End()
Description
The End() method of the Response object tells the server to stop processing the script
and return the current results.
Example
Listing 9.177 shows how you can call this method to stop execution of the current page.
Response.Expires
ASP1+
Syntax
Response.Expires = num
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1341
S e r v e r- S i d e 1 3 4 1
Description
The Expires property of the Response object sets the expiration header for the returned
document by specifying the num of minutes before the document expires. Browsers use
this to measure the amount of time they should cache the document.
Example
Listing 9.178 shows how you can set an expiration of only five minutes for the given
page.
Response.ExpiresAbsolute
ASP1+
Syntax
Response.ExpiresAbsolute = datetime
Description
The ExpiresAbsolute property of the Response object sets the absolute expiration
date for the returned document by specifying the datetime the document expires.
Browsers use this to measure the amount of time they should cache the document.
Example
Listing 9.179 shows how you can set the expiration to October 31st, 2001 at 8:00 a.m.
for the given page.
Response.Flush()
ASP1+
Syntax
Response.Flush()
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1342
1 3 4 2 C h a p t e r 9 : S e r v e r- S i d e
Description
The Flush() method of the Response object is used to send the currently buffered con-
tent to the user agent. For this method to work properly, the Response.Buffer property
must be set to TRUE.
Example
Listing 9.180 shows how to tell the server to buffer the content, and then send it when
the Response.Flush() method is called.
Response.IsClientConnected
ASP1+
Syntax
Response.IsClientConnected
Description
The IsClientConnected property of the Response object is a boolean value that lets
you see whether a client is still connected.
Example
Listing 9.181 shows how you can evaluate the IsClientConnected property within an
if statement before writing out your content. If the client is not connected, it writes an
error to the Web log file.
Response.PICS
ASP1+
Syntax
Response.PICS(label)
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1343
S e r v e r- S i d e 1 3 4 3
Description
The PICS property of the Response object adds the PICS-label HTTP header directive
to the current output. The label property contains a properly formatted PICS label.
Example
Listing 9.182 shows how you can use the PICS property to add the PICS-label HTTP
header directive to the current output.
Response.Redirect()
ASP1+
Syntax
Response.Redirect(url)
Description
The Redirect() method of the Response object sends back an appropriate 302 HTTP
header directive instructing the browser to request and load the url passed.
Example
Listing 9.183 shows how you can redirect the browser to a new page if a user accesses
your root directory page (for example, www.purejavascript.com).
Response.Status
ASP1+
Syntax
Response.Status = string
Description
The Status property of the Response object specifies the HTTP status of the response.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1344
1 3 4 4 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.184 shows how you can return an error to the user if she has made an illegal
request.
Response.Write()
ASP1+
Syntax
Response.Write(string)
Description
The Write() method of the Response object is used to write an ASCII string to the
output.
Example
Listing 9.185 shows how you can write “Hello World” to output.
Resultset
ES3+
Syntax
Core object created by the Stproc.resultSet().
Description
The Resultset object is one of the core server-side JavaScript objects. This object is
created by the resultSet() method of the Stproc object. For stored procedures run
against DB2, Oracle, Sybase, and ODBC databases, the stored procedure object has
one Resultset object for each SQL SELECT statement executed by the procedure. An
Informix stored procedure, on the other hand, has one Resultset object.
Each instance of this object has a property for each column in the resultset. For Oracle,
Sybase, and ODBC stored procedures, these properties can be referred to by the col-
umn name. Informix and DB2 stored procedures do not have named columns, so you
must use a zero-based numeric index to refer to the column.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1345
S e r v e r- S i d e 1 3 4 5
You should always call the close() method of the Resultset object after you have fin-
ished. The JavaScript runtime will attempt to close the object when the associate
DbPool or database object goes out of scope.
NOTE
After creating a resultset, you must perform all operations on the set before calling
the commitTransaction(), returnValue(), outParameters(),
Connection.cursor(), or Connection.SQLTable() method.
This object has only one property—prototype. This property can be used to create
new methods and properties for the Resultset object. Table 9.29 contains the methods
accessible from this object.
Example
Listing 9.186 creates a connection to a database. After the connection has been veri-
fied, the storedProc() method is used to invoke the fictitious sp_employees stored
procedure. The resultsets for this stored procedure are then held in an instance of the
Resultset object.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if(myConn.connected()){
myConn.beginTransaction();
1 3 4 6 C h a p t e r 9 : S e r v e r- S i d e
</server>
Resultset.close()
ES3+
Syntax
resultset.close()
Description
The close() method of the Resultset object closes the resultset and frees all memory
used to store its information. If successful, the method returns 0; otherwise, it returns
an error code that can be obtained by using the majorErrorCode() and
majorErrorMessage() methods of the Connection or database objects.
Example
Listing 9.187 creates a resultset and then closes it.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
myConn.beginTransaction();
S e r v e r- S i d e 1 3 4 7
</server>
Resultset.columnName()
ES3+
Syntax
resultset.columnName(num)
Description
The columnName() method of the Resultset object takes the zero-based indexed num-
ber location, num, passed to the method and returns the name of the column in that loca-
tion. Note that these names are not returned in any specific order unless you order them
as such. Successive calls to the method, however, will return all the columns. See the
example for more information.
Example
Listing 9.188 has two resultsets. One of the sets returns specific column names and the
other returns all columns. See the comments in the code for the output.
if(myConn.connected()){
1 3 4 8 C h a p t e r 9 : S e r v e r- S i d e
// Writes all column names stored in the second resultset to the page.
for(var i = 0; i <= myResultSet2.columns(); i++){
write(myResultSet2.columnName(i));
}
</server>
Resultset.columns()
ES3+
Syntax
resultset.columns()
Description
The columns() method of the Resultset object returns the number of columns in the
resultset on which it is invoked. If the SQL used to create the resultset specifies a set
number of columns to return, that is the number returned by this method.
Example
Listing 9.189 shows how you can return all the column names of the columns in your
resultset.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1349
S e r v e r- S i d e 1 3 4 9
</server>
Resultset.next()
ES3+
Syntax
resultset.next()
Description
The next() method of the Resultset object moves the pointer in the current row to
the next row in the resultset. This method is used to iterate through each of the rows
returned by the resultset. This method returns true, unless it is the last row of the
resultset; at which time it returns false.
Example
Listing 9.190 creates an instance of the Resultset object and iterates through its
results. This is performed by using the next()method.
Listing 9.190 Using the next() Method to Iterate Through the Rows in
a Resultset
<server>
1 3 5 0 C h a p t e r 9 : S e r v e r- S i d e
</server>
Resultset.prototype
ES3+
Syntax
resultset.prototype.method = name
resultset.prototype.property = value
Description
The prototype property of the Resultset object allows you to create new properties
and methods of the object. If you are adding a method, set the instance equal to the
name of the method you have defined.
Example
Listing 9.191 creates a new property and method of the Resultset object. An instance
is created and the new property is set. The new method is then called to verify the prop-
erty, and, if it is incorrect, an error message is written to the page.
S e r v e r- S i d e 1 3 5 1
</server> >
Resultset.unwatch()
ES3+
Syntax
resultset.unwatch(property)
Description
The unwatch() method of the Resultset object is used to turn off the watch for a par-
ticular property.
Example
Listing 9.192 shows how the unwatch() method is used to stop watching the user-
defined property p.
1 3 5 2 C h a p t e r 9 : S e r v e r- S i d e
// watch property
myResultSet.watch(“type”, alertme);
// change value
myResultSet.type = null;
</server>
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1353
S e r v e r- S i d e 1 3 5 3
Resultset.watch()
ES3+
Syntax
resultset.watch(property, function)
Description
The watch() method of the Resultset object is used to turn on the watch for a partic-
ular property specified by property. Any time the specified property is changed after
the watch() method has been called, the specified function is called.
Example
Listing 9.193 shows how the watch() method is used to start watching the user-defined
property p.
1 3 5 4 C h a p t e r 9 : S e r v e r- S i d e
// watch property
myResultSet.watch(“type”, alertme);
// change value
myResultSet.type = null;
</server>
ScriptingContext
ASP1+
Syntax
Core ASP environment object
Description
The ScriptingContext object is a core, but obsolete, ASP environment object. It will
return the Application, Request, Response, Server, or Session built-in objects.
Rather than using this object, you should use ObjectContext instead.
Example
Please see the examples under the ObjectContext object for methods of accomplish-
ing the same thing as this obsolete object.
SendMail
ES3+
Syntax
new SendMail()
Description
The SendMail object is a core server-side object that is created using the new keyword.
This object provides the properties and methods necessary to send e-mail with your
JavaScript applications. Table 9.30 lists the properties and methods of this object.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1355
S e r v e r- S i d e 1 3 5 5
Using the SendMail object is very straightforward. Simply set the same properties con-
tained in the everyday e-mail you send and invoke the send() method. If an error is
encountered, it can be analyzed by using the error methods supplied.
Example
Listing 9.194 shows the use of the SendMail object to create a page for users to send
e-mail.
1 3 5 6 C h a p t e r 9 : S e r v e r- S i d e
// If there was an error, give the user the email address of who they
// should contact about the error, as well as the error code and message.
write(“There was an error sending your message. Please send email to “);
write(myMail.Errorsto + “ with the following error message”);
write(“Error “ + myMail.errorCode() + “: “ + myMail.errorMessage());
}else{
// If there was not an error, tell the user they were successful.
write(“Your message was sent successfully!”);
}
}else{
// If this page was called and a form was not submitted, then write the
// email form to the page for the user to use.
S e r v e r- S i d e 1 3 5 7
SendMail.Bcc
ES3+
Syntax
sendmail.Bcc
Description
The Bcc property of the SendMail object specifies the e-mail addresses of those recip-
ients you want to blind carbon copy. If you want to specify more than one recipient,
separate their e-mail addresses with commas.
Example
Listing 9.195 shows you how to set the Bcc property of an instance of the SendMail
object.
</server>
SendMail.Body
ES3+
Syntax
sendmail.Body
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1358
1 3 5 8 C h a p t e r 9 : S e r v e r- S i d e
Description
The Body property of the SendMail object specifies the body of the e-mail you want to
send.
Example
Listing 9.196 shows you how to set the Body property of an instance of the SendMail
object.
</server>
SendMail.Cc
ES3+
Syntax
sendmail.Cc
Description
The Cc property of the SendMail object specifies the e-mail addresses of those recipi-
ents you want to carbon copy. If you want to specify more than one recipient, separate
their e-mail addresses with commas.
Example
Listing 9.197 shows you how to set the Cc property of an instance of the SendMail
object.
</server>
SendMail.constructor
ES2+
Syntax
sendmail.constructor
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1359
S e r v e r- S i d e 1 3 5 9
Description
The constructor property of the SendMail object specifies the function that creates
the object.
Example
Listing 9.2198 shows an example of the constructor property.
if(myMail.constructor == SendMail){
write(“Object created”);
}
</server>
SendMail.errorCode()
ES3+
Syntax
sendmail.errorCode()
Description
The errorCode() method of the SendMail object returns one of six error codes after
attempting to send an e-mail. These codes are described in Table 9.31.
Table 9.31 Error Codes Generated from Sending E-mail with the
SendMail.send() Method
Code Description
0 The e-mail was sent successfully.
1 The SMTP sending mail server was not specified.
2 The SMTP sending mail server was down or does not exist.
3 No recipient e-mail address was specified.
4 No sender’s e-mail address was specified.
5 Connection problems and data not sent.
Example
Listing 9.199 tries to send an instance of the SendMail object. If the send() method
fails, the error it encounters is written to the page.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1360
1 3 6 0 C h a p t e r 9 : S e r v e r- S i d e
// If there was an error, give the user the email address of who they
// should contact about the error, as well as the error code and message.
write(“There was an error sending your message. Please send email to “);
write(myMail.Errorsto + “ with the following error message”);
write(“Error “ + myMail.errorCode() + “: “ + myMail.errorMessage());
}else{
// If there was not an error, tell the user they were successful.
write(“Your message was sent successfully!”);
}
</server>
SendMail.errorMessage()
ES3+
Syntax
sendmail.errorMessage()
Description
The errorMessage() method of the SendMail object returns the string error message
generated after attempting to send an e-mail.
Example
Listing 9.200 tries to send an instance of the SendMail object. If the send() method
fails, the error it encounters is written to the page.
// If there was an error, give the user the email address of who they
// should contact about the error, as well as the error code and message.
write(“There was an error sending your message. Please send email to “);
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1361
S e r v e r- S i d e 1 3 6 1
}else{
// If there was not an error, tell the user they were successful.
write(“Your message was sent successfully!”);
}
</server>
SendMail.Errorsto
ES3+
Syntax
sendmail.Errorsto
Description
The Errorsto property of the SendMail object specifies the e-mail address of a recip-
ient that should receive the error message. The default value of this error is the sender’s
address. If you want to specify more than one recipient, separate their e-mail addresses
with commas.
Example
Listing 9.201 shows you how to set the Errorsto property of an instance of the
SendMail object.
</server>
SendMail.From
ES3+
Syntax
sendmail.From
Description
The From property of the SendMail object specifies the e-mail address of the sender of
the message.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1362
1 3 6 2 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.202 shows you how to set the From property of an instance of the SendMail
object.
// Set the From property using the email key in a form sent by the client.
myMail.From = request.email;
</server>
SendMail.Organization
ES3+
Syntax
sendmail.Organization
Description
The Organization property of the SendMail object specifies the organization of the
sender.
Example
Listing 9.203 shows you how to set the Organization property of an instance of the
SendMail object.
</server>
SendMail.prototype
ES3+
Syntax
sendmail.prototype.method = name
sendmail.prototype.property = value
Description
The prototype property of the SendMail object allows you to create new properties
and methods of the object. If you are adding a method, set the instance equal to the
name of the method you have defined.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1363
S e r v e r- S i d e 1 3 6 3
Example
Listing 9.204 creates a new property and method of the SendMail object. An instance
is created and the new property is set. The new method is then called to verify the prop-
erty, and, if it is incorrect, an error message is written to the page.
</server>
SendMail.Replyto
ES3+
Syntax
sendmail.ReplyTo
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1364
1 3 6 4 C h a p t e r 9 : S e r v e r- S i d e
Description
The ReplyTo property of the SendMail object specifies the e-mail addresses to which
the sender wants any replies to be routed.
Example
Listing 9.205 shows you how to set the ReplyTo property of an instance of the
SendMail object.
// Set the ReplyTo property using the email key in a form sent by the client.
myMail.ReplyTo = request.replyto;
</server>
SendMail.send()
ES3+
Syntax
sendmail.send()
Description
The send() method of the SendMail object attempts to send the e-mail from the value
specified in the From property to those specified in the To, Cc, and Bcc properties
through the e-mail server specified in the Smtpserver property. This method returns
true if successful and false otherwise.
Example
Listing 9.206 tries to send a message. If an error occurs when trying to send the mes-
sage, an error message is written to the user’s page.
// If there was an error, give the user the email address of whom they
// should contact about the error, as well as the error code and message.
write(“There was an error sending your message. Please send email to “);
write(myMail.Errorsto + “ with the following error message”);
write(“Error “ + myMail.errorCode() + “: “ + myMail.errorMessage());
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1365
S e r v e r- S i d e 1 3 6 5
}else{
// If there was not an error, tell the user they were successful.
write(“Your message was sent successfully!”);
}
</server>
SendMail.Smtpserver
ES3+
Syntax
sendmail.Smtpserver
Description
The Smtpserver property of the SendMail object specifies the SMTP sending email IP
address or server name. This value defaults to the value set in the Administration Server
settings for the instance of the Enterprise Server under which your application is run-
ning.
Example
Listing 9.207 shows you how to set the Smtpserver property of an instance of the
SendMail object.
</server>
SendMail.Subject
ES3+
Syntax
sendmail.Subject
Description
The Subject property of the SendMail object specifies the subject of the e-mail you
want to send.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1366
1 3 6 6 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.208 shows you how to set the Subject property of an instance of the
SendMail object.
</server>
SendMail.To
ES3+
Syntax
sendmail.To
Description
The To property of the SendMail object specifies the e-mail addresses of the recipients
of the message. If you want to specify more than one recipient, separate their e-mail
addresses with commas.
Example
Listing 9.209 shows you how to set the To property of an instance of the SendMail
object.
</server>
SendMail.unwatch()
ES3+
Syntax
sendmail.unwatch(property)
Description
The unwatch() method of the SendMail object is used to turn off the watch for a par-
ticular property.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1367
S e r v e r- S i d e 1 3 6 7
Example
Listing 9.210 shows how the unwatch() method is used to stop watching the user-
defined property p.
myMail.To = “[email protected]”;
// watch property
myMail.watch(“To”, alertme);
// change value
myMail.To = “[email protected]”;
</server>
SendMail.watch()
ES3+
Syntax
sendmail.watch(property, function)
Description
The watch() method of the SendMail object is used to turn on the watch for a partic-
ular property specified by property. Any time the specified property is changed after
the watch() method has been called, the specified function is called.
Example
Listing 9.211 shows how the watch() method is used to start watching the user-defined
property p.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1368
1 3 6 8 C h a p t e r 9 : S e r v e r- S i d e
myMail.To = “[email protected]”;
// watch property
myMail.watch(“To”, alertme);
// change value
myMail.To = “[email protected]”;
</server>
Server
ASP1+
Syntax
Core ASP environment object
Description
The Server object is a core ASP environment object. This object provides access to the
server’s utility functions. Table 9.32 contains the list of a property and methods of this
object.
S e r v e r- S i d e 1 3 6 9
Example
Listing 9.212 shows how you can use the ScriptTimeout property of the Server object
to specify the number of seconds before a script stops processing.
Server.CreateObject()
ASP1+
Syntax
Server.CreateObject(objID)
Description
The CreateObject() method of the Server object creates an instance of the server
component referenced by objID. This objID is usually in the following format:
Vendor.Component.Version
Example
Listing 9.213 creates an instance of a fictitious Marketing component from the MyCo
company.
Server.Execute()
ASP3+
Syntax
Server.Execute(path)
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1370
1 3 7 0 C h a p t e r 9 : S e r v e r- S i d e
Description
The Execute() method of the Server object executes the ASP file located at path, pro-
cessing it as if it were part of the current page.
Example
Listing 9.214 executes the gettime.asp page while being processed.
Server.GetLastError()
ASP3+
Syntax
Server.GetLastError()
Description
The GetLastError() method of the Server object creates an instance of the ASPError
object that contains a description of the last error that occurred.
Example
Listing 9.215 writes out the last error that has occurred on a page.
Server.HTMLEncode()
ASP1+
Syntax
Server.HTMLEncode(string)
Description
The HTMLEncode() method of the Server object applies HTML encoding to a specified
string.
Example
Listing 9.216 creates a string that includes two HTML tags, and before it is written to
the page, HTML encoding is applied.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1371
S e r v e r- S i d e 1 3 7 1
Server.MapPath()
ASP1+
Syntax
Server.MapPath(path)
Description
The MapPath() method of the Server object maps the relative or virtual path to a phys-
ical directory on the file system.
Example
Listing 9.217 will write out the file system path for the requested URL.
Server.ScriptTimeout
ASP1+
Syntax
Server.ScriptTimeout
Description
The ScriptTimeout property of the Server object specifies the number of seconds that
should elapse before the currently executing script times out.
Example
Listing 9.218 shows how you can use the ScriptTimeout property of the Server object
to specify the number of seconds before a script stops processing.
1 3 7 2 C h a p t e r 9 : S e r v e r- S i d e
Server.Transfer()
ASP3+
Syntax
Server.Transfer(path)
Description
The Transfer() method of the Server object sends all the processed information
available for the current page to the ASP file located at path.
Example
Listing 9.219 shows how the current script passes its data on to another script.
Server.Transfer(“/scripts/logversion.asp”);
</script>
Server.URLEncode()
ASP1+
Syntax
Server.URLEncode(string)
Description
The URLEncode() method of the Server object applies URL encoding to a specified
string.
Example
Listing 9.220 creates a string that includes two HTML tags and some whitespace.
Before it is written to the page, URL encoding is applied.
S e r v e r- S i d e 1 3 7 3
server
ES2+
Syntax
Core object created when the instance of Enterprise Server is started.
Description
The server object is one of the core server-side objects. An instance of this object is
created for each instance of the Enterprise server you have running. This object is
destroyed when the server process is stopped.
This object should be used to store global data you want to share and manage across
your applications. Because of this, you will need to lock and unlock your code if you
are changing any properties you have defined in your applications. The server object
has the properties and methods listed in Table 9.33. Note that the properties are all
read-only.
Example
Listing 9.221 uses the lock() and unlock() methods of the server object to lock the
working code while the property, totalHits, is modified.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1374
1 3 7 4 C h a p t e r 9 : S e r v e r- S i d e
</server>
server.host
ES2+
Syntax
server.host
Description
The host property of the server object contains the server name, any sub-domain, and
domain name of the Web server.
Example
Listing 9.222 writes the host of the server to the user’s page.
</server>
server.hostname
ES2+
Syntax
server.hostname
Description
The hostname property of the server object contains the server name, any sub-domain,
domain name, and port of the Web server. This property is the same as concatenating
the host property with the port property and separating them with a colon.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1375
S e r v e r- S i d e 1 3 7 5
Example
Listing 9.223 writes the hostname of the server to the user’s page.
</server>
server.lock()
ES2+
Syntax
server.lock()
Description
The lock() method of the server object locks the code in which you are working until
you perform an unlock. If the code is already locked, this method will wait until it can
get the lock, a timeout occurs, or an error occurs.
Example
Listing 9.224 sets a server object with a counter property, totalHits. Because you
only want to increment the counter with each new user request on each application, it
must be locked.
</server>
server.port
ES2+
Syntax
server.port
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1376
1 3 7 6 C h a p t e r 9 : S e r v e r- S i d e
Description
The port property of the server object contains the port number to which the Web
server is responding.
Example
Listing 9.225 writes the port of the server to the user’s page.
</server>
server.protocol
ES2+
Syntax
server.protocol
Description
The protocol property of the server object contains the protocol to which the server
is responding. This includes the information up to the first colon, as in http:.
Example
Listing 9.226 writes the protocol of the server to the user’s page.
</server>
server.unlock()
ES2+
Syntax
server.unlock()
Description
The unlock() method of the server object unlocks the code that you have locked.
This method returns true if the unlocking was successful and false otherwise.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1377
S e r v e r- S i d e 1 3 7 7
Example
Listing 9.227 sets a server object with a counter property, hitCount. Because you
only want to increment the counter with each new user request, it must be locked.
When the counter has been incremented, the project is unlocked.
</server>
server.unwatch()
ES3+
Syntax
server.unwatch(property)
Description
The unwatch() method of the server object is used to turn off the watch for a partic-
ular property.
Example
Listing 9.228 shows how the unwatch() method is used to stop watching the user-
defined property p.
</server>
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1378
1 3 7 8 C h a p t e r 9 : S e r v e r- S i d e
server.watch()
ES3+
Syntax
server.watch(property, function)
Description
The watch() method of the server object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 9.229 shows how the watch() method is used to start watching the user-defined
property p.
</server>
Session
ASP1+
Syntax
Core ASP environment object
Description
The Session object is a core ASP environment object. This object is used to store infor-
mation about a particular user in a session. This information will last for the user’s
entire session, not just the current page she is on. The server automatically creates this
object when a user without a session makes a request. Table 9.34 contains the list of
collections, events, methods, and properties available from this object.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1379
S e r v e r- S i d e 1 3 7 9
Example
Listing 9.230 shows how you can use the Timeout property of the Session object to
specify the number of minutes before a script session ends.
Session.Abandon()
ASP1+
Syntax
Session.Abandon()
Description
The Abandon() method of the Session object destroys all items that have been added
to a given Session instance, and frees all resources they were consuming. If this
method is not called explicitly, the server invokes it when a session has ended.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1380
1 3 8 0 C h a p t e r 9 : S e r v e r- S i d e
NOTE
When this method is called, the resources and items are not cleared until the page
finishes processing. So, it is possible to use items that have been marked for aban-
donment on the current page, but not on subsequent pages.
Example
Listing 9.231 creates an item for the session, destroys all items in the session, and then
creates a new item. After this has completed, the script attempts to write both items to
the page. Because these are both on the same page as the Abandon() method call, both
will be written. However, the version item will not be accessible on subsequent pages
in the same session.
// Create a “version” item that will only last for this page.
Session(“version”) = “1.0”;
// Destroy session.
Session.Abandon();
Session.CodePage
ASP1+
Syntax
Session.CodePage(codepage)
Description
The CodePage property of the Session object determines the code page that will be
used for displaying dynamic content. Code page is a numeric value for the character
set that is used to identify different languages and locales.
Example
Listing 9.232 sets the CodePage property to represent American English ANSI content.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1381
S e r v e r- S i d e 1 3 8 1
Session.Contents
ASP1+
Syntax
Session.Contents(name)
Description
The Contents collection of the Session object contains a collection of items that have
been created for the session instance without the use of the <object> element. You can
access specific items by their name. This collection also has Remove() and
RemoveAll() methods.
Example
Listing 9.233 shows how you can add items to a Session object instance, access spe-
cific items through the Contents collection, and then clear all the items using the
RemoveAll() method.
Session.Contents.Remove()
ASP1+
Syntax
Session.Contents.Remove(name)
Session.Contents.Remove(num)
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1382
1 3 8 2 C h a p t e r 9 : S e r v e r- S i d e
Description
The Remove() method of the Contents collection of the Session object can be used to
remove the name item from the collection. Additionally, you can specify the num index
location and remove the items using this method as well.
Example
Listing 9.234 shows how you can add items to a Session object instance, access spe-
cific items through the Contents collection, and then clear the item using the Remove()
method.
Session.Contents.RemoveAll()
ASP1+
Syntax
Session.Contents.RemoveAll()
Description
The RemoveAll() method of the Contents collection of the Session object removes all
items that have been added to the session.
Example
Listing 9.235 shows how you can add items to a Session object instance, access spe-
cific items through the Contents collection, and then clear all the items using the
RemoveAll() method.
S e r v e r- S i d e 1 3 8 3
Session.LCID
ASP1+
Syntax
Session.LCID
Description
The LCID property of the Session object sets the locale identifier to display dynamic
content. This explicit setting will override any @LCID directives you might have set in
your file.
Example
Listing 9.236 shows how you can set the locale identifier to British English.
Session.SessionID
ASP1+
Syntax
Session.SessionID
Description
The SessionID property of the Session object contains the unique identifier generated
by the server for the current Session object instance.
Example
Listing 9.237 writes out the value of the current SessionID property.
1 3 8 4 C h a p t e r 9 : S e r v e r- S i d e
Session.Session_OnEnd
ASP1+
Syntax
function Session_OnEnd(){
code
}
Description
The Session_OnEnd event function of the Session object is called when the
Session_OnEnd event is fired. This occurs when a session ends or times out.
Example
Listing 9.238 shows how you can append a string to the end of the log file of the last
request of a session.
Session.Session_OnStart
ASP1+
Syntax
function Session_OnStart(){
code
}
Description
The Session_OnStart event function of the Session object is called when the
Session_OnStart event is fired. This occurs when the session starts.
Example
Listing 9.239 shows how you can append a string to the end of the log file on the first
request of a session.
S e r v e r- S i d e 1 3 8 5
Session.StaticObjects
ASP1+
Syntax
Session.StaticObjects(name)
Description
The StaticObjects collection of the Session object stores all the objects created with
<object> elements within the scope of a given session. These are referenced by the
name given to each instance of the elements.
Example
Listing 9.240 shows how you can grab the instance myControl from your current ASP
page.
Session.Timeout
ASP1+
Syntax
Session.Timeout
Description
The Timeout property of the Session object specifies the number of minutes that
should elapse before the current session times out.
Example
Listing 9.241 shows how you can use the Timeout property of the Session object to
specify the number of minutes before a session ends.
ssjs_generateClientID()
ES3+
Syntax
ssjs_generateClientID()
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1386
1 3 8 6 C h a p t e r 9 : S e r v e r- S i d e
Description
The ssjs_generateClientID() function is a top-level function that is not associated
with any core server-side object. This function returns a unique identifier from the run-
time engine. This allows you to track a user’s session across several pages when using
client-side maintenance. You might want to store the identifier as a property of the
client object, but be careful to keep it from being accessed by other clients.
Example
Listing 9.242 shows how you can assign a property of the client object an identifier
to track a user.
</server>
ssjs_getCGIVariable()
ES3+
Syntax
_ssjs_getCGIVariable(envVariable)
Description
The ssjs_getCGIVariable() function is a top-level function that is not associated
with any core server-side object. This function allows you to retrieve environment vari-
ables that are available to your CGI processes. When a variable cannot be found, the
function returns null. Table 9.35 contains the default list of variables you can access.
S e r v e r- S i d e 1 3 8 7
Variable Description
PATH_TRANSLATED The actual path to the file you want to retrieve. This would
be something similar to
/netscape/suitespot/docs/sports/baseball.html.
QUERY_STRING Any information after a ? character in the URL.
REMOTE_ADDR The IP address of the host submitting the request.
REMOTE_HOST The hostname address of the host submitting the request.
DNS must be turned on for this feature.
REMOTE_USER The name of the local HTTP user of the Web browser, if
access authorization is turned on for this URL.
REQUEST_METHOD The type of request that is being made, such as GET or POST.
SCRIPT_NAME The filename you are trying to retrieve, such as index.html.
SERVER_NAME The hostname or IP under which the server is running.
SERVER_PORT The port number to which the server is responding.
SERVER_PROTOCOL The protocol version supported by the requesting client, such
as HTTP/1.0.
SERVER_URL The URL a user would have to enter to access the server,
such as http://www.purejavascript.com:6969.
Example
Listing 9.243 returns the SERVER_URL variable to a property of the server object.
</server>
ssjs_getClientID()
ES3+
Syntax
ssjs_getClientID()
Description
The ssjs_getClientID() function is a top-level function that is not associated with
any core server-side object. This function returns a unique identifier from the runtime
engine. This allows you to track a user’s session across several pages when using
server-side maintenance. When using this function, there is no need to store the iden-
tifier as a property of the client object.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1388
1 3 8 8 C h a p t e r 9 : S e r v e r- S i d e
Example
Listing 9.244 writes the identifier generated by the ssjs_getClientID() function to
the page.
</server>
Stproc
ES3+
Syntax
Core object created by the storedProc() method of the database or Connection
objects.
Description
The Stproc object is a core server-side object that is created by the storedProc()
method of the database or Connection objects. Because of the nature of connections
to a database, you should call the close() method of this object when you have com-
pleted your processing. This will free any and all memory used by the stored proce-
dure. Otherwise, the object will be destroyed when the database or Connection
objects go out of scope.
The object itself has only one property—prototype. This property can be used to add
methods and properties to the object as needed. Table 9.36 lists the methods of the
Stproc object.
S e r v e r- S i d e 1 3 8 9
Example
Listing 9.245 creates an instance of the Stproc object, via a Connection.
storedProc() method call, and then closes it.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
myConn.beginTransaction();
</server>
Stproc.close()
ES3+
Syntax
stproc.close()
Description
The close() method of the Stproc object closes the stored procedure and frees all
memory used to store its information. If successful, the method returns 0; otherwise, it
returns an error code that can be obtained by using the majorErrorCode() and
majorErrorMessage() methods of the Connection or database objects.
Example
Listing 9.246 creates a stored procedure and then closes it.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
myConn.beginTransaction();
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1390
1 3 9 0 C h a p t e r 9 : S e r v e r- S i d e
</server>
Stproc.outParamCount()
ES3+
Syntax
stproc.outParamCount()
Description
The outParamCount() method of the Stproc object returns the number of output para-
meters from the stored procedure. Be sure to call this method before calling the
outParameters() method to make sure that parameters have been returned.
NOTE
Informix stored procedures do not have output parameters, so this method always
returns 0 when run against an Informix database.
Example
Listing 9.247 opens a connection to the database and runs a stored procedure. Based
on the number of output parameters, the script writes the parameters to the user’s
screen.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
myConn.beginTransaction();
S e r v e r- S i d e 1 3 9 1
</server>
Stproc.outParameters()
ES3+
Syntax
stproc.outParameters(num)
Description
The outParameters() method of the Stproc object returns the output parameter from
the stored procedure that is indexed at the num location. The return value of this method
can be a string, number, double, or object. Be sure to call the outParamCount()
method before calling this method to make sure that parameters have been returned.
NOTE
Informix stored procedures do not have output parameters, so there is no need to
run this method.
Example
Listing 9.248 opens a connection to the database and runs a stored procedure. Based
on the number of output parameters, the script writes the parameters to the user’s
screen.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
myConn.beginTransaction();
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1392
1 3 9 2 C h a p t e r 9 : S e r v e r- S i d e
</server>
Stproc.prototype
ES2+
Syntax
stproc.prototype.method = name
stproc.prototype.property = value
Description
The prototype property of the Stproc object allows you to create new properties and
methods of the object. If you are adding a method, set the instance equal to the name of
the method you have defined.
Example
Listing 9.249 creates a new property and method of the Stproc object. An instance is
created and the new property is set. The new method is then called to verify the prop-
erty, and, if it is incorrect, an error message is written to the page.
S e r v e r- S i d e 1 3 9 3
}else{
return false;
}
}
</server>
Stproc.resultSet()
ES3+
Syntax
stproc.resultSet()
Description
The resultSet() method of the Stproc object creates a Resultset object for storing
the results of running a stored procedure. For stored procedures run against DB2,
Oracle, Sybase, and ODBC databases, the stored procedure object has one Resultset
object for each SQL SELECT statement executed by the procedure. An Informix stored
procedure, on the other hand, has one Resultset object.
Each instance of this object has a property for each column in the result set. For Oracle,
Sybase, and ODBC stored procedures, these properties can be referred to by the col-
umn name. Informix and DB2 stored procedures do not have named columns, so you
must use a zero-based numeric index to refer to the column.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1394
1 3 9 4 C h a p t e r 9 : S e r v e r- S i d e
You should always call the close() method of the Stproc object after you have fin-
ished. The JavaScript runtime will attempt to close the object when the associated
DbPool or database object goes out of scope.
NOTE
After creating a resultset, you must perform all operations on the set before calling
the commitTransaction(), returnValue(), outParameters(),
Connection.cursor(), or Connection.SQLTable() method.
Example
Listing 9.250 creates a connection to a database. After the connection has been veri-
fied, the storedProc() method is used to invoke the fictitious sp_employees stored
procedure. The resultsets for this stored procedure are then held in an instance of the
Resultset object that was created with the resultSet() method.
// Open a connection.
var myConn = database.connect(“ORACLE”, “mySID”, “myApp”, “appsPWD”, “myTNS”);
if(myConn.connected()){
myConn.beginTransaction();
myResultSet = myStproc.resultSet();
</server>
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1395
S e r v e r- S i d e 1 3 9 5
Stproc.returnValue()
ES3+
Syntax
stproc.returnValue()
Description
The returnValue() method of the Stproc object returns the return value of the stored
procedure. For DB2, Informix, and ODBC, this method always returns null. Oracle
only returns null if the stored procedure did not return a value. Sybase always returns
a value.
NOTE
Before you call this method, you must retrieve any Resultset objects. When this
method is called, no more data can be obtained from the current resultset and no
more resultsets can be created.
Example
Listing 9.251 calls a stored procedure, creates a resultset, and obtains the result value.
This value is then written to the user’s page.
// Generate a resultset.
var myResultset = myStproc.resultSet();
</server>
Stproc.unwatch()
ES3+
Syntax
stproc.unwatch(property)
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1396
1 3 9 6 C h a p t e r 9 : S e r v e r- S i d e
Description
The unwatch() method of the Stproc object is used to turn off the watch for a partic-
ular property.
Example
Listing 9.252 shows how the unwatch() method is used to stop watching the user-
defined property p.
// watch property
myStproc.watch(“type”, alertme);
// change value
myStproc.type = null;
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1397
S e r v e r- S i d e 1 3 9 7
</server>
Stproc.watch()
ES3+
Syntax
stproc.watch(property, function)
Description
The watch() method of the stproc object is used to turn on the watch for a particular
property specified by property. Any time the specified property is changed after the
watch() method has been called, the specified function is called.
Example
Listing 9.253 shows how the watch() method is used to start watching the user defined
property p.
1 3 9 8 C h a p t e r 9 : S e r v e r- S i d e
// watch property
myStproc.watch(“type”, alertme);
// change value
myStproc.type = null;
</server>
write()
ES2+
Syntax
write(string)
write(num)
write(expression)
Description
The write function is a top-level function that is not associated with any object. This
function writes information to the HTML page the script is generating to send back to
the client. This function can take and write a string, numeric value, or an expression
that returns an alphanumeric result. To write data to a file, see the entry for
File.write() and File.writeln().
TIP
The JavaScript runtime buffers all write data until 64KB have been collected. Then
the buffer is flushed to the file. You can manually call the top-level flush function
to improve performance of your pages, if they are waiting on database query
results, by calling the function before you run the query.
Example
Listing 9.254 writes a string “Hello, World!” to the user’s page.
18 0672321416 CH09b was 13b 7/24/01 12:48 PM Page 1399
S e r v e r- S i d e 1 3 9 9
</server>
31 0672321416 Index 7/30/01 2:03 PM Page CD:2169
31 0672321416 Index 7/30/01 2:03 PM Page CD:2170
31 0672321416 Index 7/30/01 2:03 PM Page CD:2169
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1403
DOM Core
CHAPTER 10
DOM Core
This chapter contains a reference to all of the DOM Level 2
Core language bindings for ECMAScript (that is, Netscape
JavaScript and MS JScript). The DOM Level 2 Core API pro-
vides the programmer with tools to create valid and well-
formed XML documents. In addition, functionality exists in
the API to navigate XML documents as well as modify the
underlying structure. For those familiar with the DOM Java
language bindings, you will notice that the ECMAScript bind-
ings bear a striking resemblance to the Java DOM API.
Attr
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
Attr represents an attribute in an Element. Attr inherits all
methods and properties from Node. DOM considers Attrs not
to be part of the document tree. Therefore, parentNode,
previousSibling, and nextSibling are all null. Table 10.1
lists all the properties of the Attr object.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1404
Example
An Attr is created by using the CreateAttribute() method of the Document object.
Attr.Name
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
attrObj.name
Description
The name property of the Attr object returns the name of this attribute.
Example
Listing 10.1 iterates through a list of attributes and writes out each attribute’s name.
Listing 10.1 Writing an Attribute’s Name Using the name Property of the
Attr Object
<html>
<script language=”JScript”>
<!--
var attrList = nodeObj.attributes;
var i = 0;
while(i < attrList.length) {
var attrObj = attrList.item(i);
writeAttrName(attrObj.name);
i++;
}
// -->
</script>
</html>
Attr.specified
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1405
Syntax
attrObj.specified
Description
The read-only property specified of the Attr object returns true if this attribute’s
value was explicitly assigned in the original document.
Example
Listing 10.2 iterates through a list of attributes checking to see which ones were spec-
ified in the original XML document.
Attr.value
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
attrObj.Value
Description
The value property of the Attr object returns the value for this attribute as a string. A
DOMException object can be raised with value NO_MODIFICATION_ALLOWED_ERR if this
node is read-only.
Example
Listing 10.3 checks the value of a size attribute.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1406
Attr.ownerElement
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
attrObj.ownerElement
Description
The ownerElement property of the Attr object returns the Element node that this
attribute is attached to.
Example
Listing 10.4 retrieves the owner element for an attribute and then removes the attribute
from the element.
CDATASection
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1407
Description
The CDATASection object inherits all methods and properties from the Text object and
the CharacterData object. The CDATASection encapsulates XML CDATA sections that
are used to escape blocks of text that shouldn’t be interpreted as markup.
Example
A CDATASection object is instantiated using the CreateCDATASection() method of the
Document object.
CharacterData
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
This object is inherited by other objects that need to access character data in DOM.
CharacterData inherits all properties and methods from Node in addition to those
listed in Table 10.2.
Example
CharacterData objects are never directly instantiated. They exist through subclasses
such as Text and Comment.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1408
CharacterData.data
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
characterDataObj.data
Description
The readonly property data of the CharacterData object returns the character data of
this node.
Example
Listing 10.5 retrieves string data from a Text node and displays it.
Listing 10.5 Retrieving String Data from a Text Node Using the data
Property of the CharacterData Object
<html>
<script language=”JScript”>
<!--
var textData = textObj.data;
write(textData);
// -->
</script>
</html>
CharacterData.length
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
characterDataObj.length
Description
The read-only property length of the CharacterData object returns the length of data
in 16-bit units.
Example
Listing 10.6 queries a Text node for the length of its data field.
Listing 10.6 Checking Text Data Length Using the length Property of
the CharacterData Object
<html>
<script language=”JScript”>
<!--
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1409
CharacterData.substringData()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
characterDataObj.substringData(offset, count)
Description
The substringData() method of the CharacterData object returns a range of data
from the node with the offset character at position offset and at length of count. A
DOMException object can be raised with value INDEX_SIZE_ERR if the specified offset
is negative or greater than the Length, or with value NO_MODIFICATION_ALLOWED_ERR
if this node is read-only.
Example
Listing 10.7 creates a substring from the given Text node’s data.
CharacterData.appendData()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
characterDataObj.appendData(arg)
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1410
Description
The appendData() method of the CharacterData object appends the string arg to the
end of Data. A DOMException object can be raised with value NO_MODIFICATION_
ALLOWED_ERR if the node is read-only.
Example
Listing 10.8 adds a string to the end of a Text node’s data property.
CharacterData.insertData()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
characterDataObj.insertData(offset, arg)
Description
The insertData() method of the CharacterData object inserts a string arg at the
specified position offset. A DOMException object can be raised with value
INDEX_SIZE_ERR if the specified offset is negative or greater than Length or with the
value NO_MODIFICATION_ALLOWED_ERR if this node is read-only.
Example
Listing 10.9 inserts a string into a Text node’s Data property.
CharacterData.deleteData()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
characterDataObj.deleteData(offset, count)
Description
The deleteData() method of the CharacterData object removes a range of data from
the node beginning at position offset and removing count characters. A
DOMException object can be raised with the value INDEX_SIZE_ERR if the specified off-
set is negative or exceeds Length or with the value NO_MODIFICATION_ALLOWED_ERR
raised if the node is read-only.
Example
Listing 10.10 deletes a string from a Text node’s Data property.
CharacterData.replaceData()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
characterDataObj.replaceData(offset, count, arg)
Description
The replaceData() method of the CharacterData object replaces the characters of
data contained in this node beginning at position offset and length count with the
string arg.
Example
Listing 10.11 illustrates replacing one string for another in a Text node’s Data
property.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1412
Comment
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
Comment inherits all methods and properties from the CharacterData object and repre-
sents the contents of an XML comment.
Example
A Comment is instantiated using the createComment() method of the Document object.
Document
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
A Document object is created using the CreateDocument() method of the
DOMImplementation object. Table 10.3 lists all properties and methods of the Document
object.
Example
Listing 10.12 uses a DOMImplementation object to create a Document object.
Document.createAttribute()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createAttribute(name)
Description
The createAttribute() method of the Document object creates and returns an Attr
object with the given name. A DOMException object can be raised with value
INVALID_CHARACTER_ERR if the specified name contains an illegal character.
Example
Listing 10.13 illustrates adding a new attribute to the root element of a previously cre-
ated document object.
Document.createAttributeNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createAttributeNS(namespaceURI, qualifiedName)
Description
The createAttributeNS() method of the Document object creates and returns an Attr
of type qualifiedName residing in the namespace nameSpaceURI. The Attr returned
has its nodeName set to qualifiedName, its nameSpaceURI attribute set to
nameSpaceURI, its prefix attribute set to a prefix as extracted from qualifiedName or
null if there is no prefix, its localName attribute set to the local name as extracted from
qualifiedName, its name attribute set to qualifiedName, and its nodeValue attribute set
to empty string.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1415
Example
Listing 10.14 illustrates creating an attribute using namespace references.
Document.createCDATASection()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createCDATASection(data)
Description
The createCDATASection() method of the Document object creates and returns a new
instance of CDATASection with its value set to data. A DOMException object with the
value NOT_SUPPORTED_ERR can be raised if this document is an HTML document.
Example
Listing 10.15 illustrates how to create and add a CDATA section to a previously cre-
ated document.
Document.createComment()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createComment(data)
Description
The createComment() method of the Document object creates and returns a new
Comment node using the DOMString data.
Example
Listing 10.16 uses a previously created Document object to create and add a new
Comment to the current XML document.
Document.createDocumentFragment()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createDocumentFragment()
Description
The createDocumentFragment() method of the Document object creates an empty
DocumentFragment object.
Example
Listing 10.17 uses a Document object to create a new DocumentFragment.
Document.createElement()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createElement(tagName)
Description
The createElement() method of the Document object creates a new element of the
type specified by tagName. This method returns a new instance of Element with its
nodeName attribute set to tagName and its other attributes set to Null. A DOMException
object can be thrown with value INVALID_CHARACTER_ERR if the specified tagName con-
tains an illegal character.
Example
Listing 10.18 uses a Document object to create a new element.
Document.createElementNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.CreateElementNS(nameSpaceURI, qualifiedName)
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1418
Description
The createElementNS() method of the Document object creates and returns an
Element of type qualifiedName residing in the namespace nameSpaceURI. The
Element returned has its nodeName set to qualifiedName, its nameSpaceURI attribute
set to nameSpaceURI, its prefix attribute set to the prefix as extracted from
qualifiedName, its localName attribute set to the localName as extracted from
qualifiedName, and its tagName attribute set to qualifiedName. It should be noted that
implementations aren’t required to implement this method of Document. A
DOMException object can be raised with the value INVALID_CHARACTER_ERR if
qualifiedName contains an illegal character or a value of NAMESPACE_ERR if
qualifiedName is malformed, the qualifiedName has a prefix and namespaceURI is
null, or if qualifiedName has a prefix that is xml and the namespaceURI is other than
http://www.w3.org/XML/1998/namespace.
Example
Listing 10.19 shows how to add an element to the current document.
Document.createEntityReference()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createEntityReference(name)
Description
The createEntityReference() method of the Document object creates and returns a
new instance of an EntityReference object given the name of the entity to reference.
If the named entity is already known, the child list of the EntityReference node is
made the same as that of the corresponding entity. A DOMException object can be raised
with the value INVALID_CHARACTER_ERR if the given name contains an illegal character
or the value NOT_SUPPORTED_ERR if this document is an HTML document.
Example
Listing 10.20 illustrates using a previously created Document object to create an entity
reference.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1419
Document.createProcessingInstruction()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createProcessingInstruction(target, data)
Description
The createProcessingInstruction() method of the Document object creates an
instance of a ProcessingInstruction node with DOMStrings target and data and
returns it. A DOMException object with value INVALID_CHARACTER_ERR can be raised if
the target contains an illegal character or with the value NOT_SUPPORTED_ERR if this
document is an HTML document.
Example
Listing 10.21 illustrates adding a CDATA section to a previously created document.
Document.createTextNode()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.createTextNode(data)
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1420
Description
The createTextNode() method of the Document object uses the string data to create a
new text node for this Document. It returns a new instance of a Text object that has its
data attribute set to data.
Example
Listing 10.22 uses a previously created Document object to create a new text node in
the current document.
Document.doctype
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.docType
Description
The doctype property of the Document object returns the document type declaration
associated with this document. This attribute is read only and cannot be manipulated
with methods inherited from Node such as insertNode() or removeNode(). The return
type is DocumentType. For HTML documents, this property returns Null.
Example
Listing 10.23 shows how to check the document type declaration of the current
document.
// -->
</script>
</html>
Document.documentElement
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.documentElement
Description
The read-only property documentElement of the Document object allows direct access
to the root element of this document. It’s return value is type Element.
Example
Listing 10.24 illustrates using the Document object to retrieve the root element of the
current document.
Document.getElementById()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.getElementById(elementId)
Description
The getElementById() method of the Document object returns the Element whose ID
is specified by elementId in this Document.
Example
Listing 10.25 shows how to retrieve an element using its element identifier.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1422
Document.getElementsByTagName()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.getElementsByTagName(tagName)
Description
The getElementsByTagName() method of the Document object returns a NodeList of
all Elements with the specified tagName. The Elements returned in the NodeList occur
in the order in which they were encountered in the Document. If tagName is set to *, the
returned NodeList will contain a list of all Elements in this document.
Example
Listing 10.26 illustrates getting all elements in a previously created Document object
and iterating through the list.
Document.getElementsByTagNameNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.getElementByTagNameNS(namespaceURI, localName)
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1423
Description
The getElementsByTagNameNS() method of the Document object returns a NodeList of
all Elements in this Document with the given localName in the given name space as
specified in nameSpaceURI in the order in which they are encountered in a preorder tra-
versal of the Document.
Example
Listing 10.27 shows how to retrieve all elements in a document given a tag name.
Document.implementation
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.implementation
Description
The read-only property implementation of the Document object returns the
DOMImplementation object associated with this document. This property is simply here
for convenience.
Example
Listing 10.28 illustrates using a Document object to return the current
DOMImplementation.
Document.importNode()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentObj.importNode(importedNode, deep)
Description
The importNode() method of the Document object imports a Node specified in the para-
meter importNode from another document into this document and returns it. The
returned Node has its parentNode attribute set to null. The importNode is not removed
from the original document; it is simply copied into this document. If deep is set to
true, the subtree beneath importNode will also be copied from the source document
recursively. A DOMException object can be raised with value NOT_SUPPORTED_ERR if
this document is an HTML document.
Example
Listing 10.29 shows a previously created node being imported into the current docu-
ment and then made a child of an element.
DocumentFragment
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1425
Description
A DocumentFragment object represents a portion of an XML document’s tree. It differs
from Document in that it is lightweight in nature. It is useful for rearranging document
structure in a simple fashion. It can be seen as analogous to the clipboard in cut-and-
paste scenarios. The DocumentFragment object inherits all methods and properties of
its parent Node.
Example
Listing 10.30 illustrates how a Document object is used to create a new
DocumentFragment.
DocumentType
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
The DocumentType object provides access to the list of entities that are defined in the
XML document’s DTD. DocumentType inherits all properties and methods from Node.
Table 10.4 lists all properties of the DocumentType object.
Example
A DocumentType object is created using the CreateDocumentType() method of the
DOMImplementation object. The DocumentType represents the actual DTD used for
building XML documents. It inherits all properties and methods of Node.
DocumentType.entities
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentTypeObj.entities
Description
The read-only property entities of the DocumentType object returns a NamedNodeMap
containing external and internal entities declared in the DTD.
Example
Listing 10.31 iterates through a list of entities and prints out their notation names.
DocumentType.internalSubset
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentTypeObj.InternalSubset
Description
The read-only property internalSubset of the DocumentType object returns a string
representation of the internal subset.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1427
Example
Listing 10.32 retrieves the internal subset from a DocumentType object.
DocumentType.name
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentTypeObj.name
Description
The read-only property name of the DocumentType object returns the name of this DTD.
Example
Listing 10.33 illustrates retrieving the Name of a DTD using the name property of the
DocumentType object.
DocumentType.notations
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentTypeObj.notations
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1428
Description
The read-only property notations of the DocuementType object returns a
NamedNodeMap containing all notations declared in the DTD.
Example
Listing 10.34 iterates through a list of notations and writes out their public identifiers.
DocumentType.publicId
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentTypeObj.publicId
Description
The read-only property publicId of the DocumentType object returns the public iden-
tifier of the external subset.
Example
Listing 10.35 retrieves the public identifier from a DocumentType object.
DocumentType.systemId
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
documentTypeObj.systemId
Description
The read-only property systemId of the DocumentType object returns the system iden-
tifier of the external subset.
Example
Listing 10.36 retrieves the system identifier from a DocumentType object.
DOMException
JavaScript1.5+, JScript5.0+
Syntax
Core DOM object.
Description
The DOMException object encapsulates all exception situations that are seen through-
out the Core DOM DOM Level 2 API. Table 10.5 lists all of the exception types as well
as the property of the DOMException object.
Example
Listing 10.37 creates a new DOMException object with code value NAMESPACE_ERR and
throws it.
DOMException.code
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
domExceptionObj.code
Description
The code property of the DOMException object returns a number indicating which
exception has occurred.
Example
Listing 10.38 illustrates catching a DOMException object and interrogating the code
property to handle the appropriate error.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1431
DOMImplementation
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Core object.
Description
DOMImplementation is used to create XML documents and document types in a non-
implementation specific manner. The object provides several convenient methods for
performing tasks independent of the DOM implementation used. Table 10.6 lists all
methods of the DOMImplementation object.
Example
Listing 10.39 creates a DOMImplementation object and creates a Document.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1432
DOMImplementation.createDocument()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOMImplementation.CreateDocument(namespaceURI, qualifiedName, doctype)
Description
The createDocument() method of the DOMImplementation object takes the two
DOMString arguments namespaceURI and qualifiedName along with the
DocumentType argument doctype to create and return a new XML Document object of
the specified type. This method raises a DOMException object with its code set to the
following:
INVALID_CHARACTER_ERR if qualifiedName contains an illegal character
NAMESPACE_ERR if qualifiedName is malformed or qualifiedName if prefixed
with xml and namespaceURI is something other than
http://www.w3.org/XML/1998/namespace
Example
Listing 10.40 uses a DOMImplementation object to create a new Document.
DOMImplementation.createDocumentType()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOMImplementation.createDocumentType
➥(qualifiedName, publicId, systemId)
Description
The createDocumentType() method of the DOMImplementation object takes the three
string arguments qualifiedName, publicId, and systemId and returns a new empty
DocumentType object. This method raises a DOMException with its code set to
INVALID_CHARACTER_ERR if qualifiedName contains an illegal character or NAME-
SPACE_ERR if qualifiedName is malformed.
Example
Listing 10.41 uses a DOMImplementation object to create a new empty XML document
type.
DOMImplementation.hasFeature()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOMImplementation.hasFeature(feature, version)
Description
The hasFeature() method of the DOMImplementation object takes the DOMString
arguments feature and version and returns a Boolean value indicating whether the
feature is available in the DOMImplementation implementation.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1434
Example
Listing 10.42 uses a DOMImplementation object to check whether level 2.0 contains
support for HTML Events.
Element
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
The Element object represents an element in an XML or HTML document. An
Element object inherits all methods and properties from Node. Table 10.7 lists all prop-
erties and methods of the Element object.
Example
Listing 10.43 creates an Element from a Document object.
Element.getAttribute()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.getAttribute(name)
Description
The getAttribute() method of the Element object returns the string value for the
attribute name.
Example
Listing 10.44 gets a quantity attribute from an element representing a line item on a
purchase order.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1436
Element.getAttributeNode()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.getAttributeNode(name)
Description
The getAttributeNode() method of the Element object retrieves the attribute speci-
fied by name and returns it as an Attr. If there is no such Attr object, null is returned.
Example
Listing 10.45 gets an attribute node from an element and sets its value.
Element.getAttributeNodeNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.getAttributeNodeNS(namespaceURI, localName)
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1437
Description
The getAttributeNodeNS() method of the Element object returns the Attr value con-
taining the specified namespaceURI and localName.
Example
Listing 10.46 retrieves an attribute node representing a quantity from an element rep-
resenting a line item.
Element.getAttributeNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.getAttributeNS(namespaceURI, localName)
Description
The getAttributeNS() method of the Element object returns the string value of the
attribute specified by the given namespaceURI and localName.
Example
Listing 10.47 gets an element’s attribute using namespace URI and local name.
Element.getElementsByTagName()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.getElementsByTagName(name)
Description
The getElementsByTagName() method of the Element object returns a NodeList con-
taining all Elements named name.
Example
Listing 10.48 gets a list of line items from an element representing an invoice.
Element.getElementsByTagNameNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.getElementsByTagNameNS(namespaceURI, localName)
Description
The getElementsByTageNameNS() method of the Element object returns a NodeList of
all descendant Elements with the given namespaceURI and localName.
Example
Listing 10.49 gets a list of line items from an element representing an invoice.
Element.hasAttribute()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.hasAttribute(name)
Description
The hasAttribute() method of the Element object returns true if this element has
an attribute named name.
Example
Listing 10.50 determines whether a line item element has an attribute for price set.
Element.hasAttributeNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.hasAttributeNS(namespaceURI, localName)
Description
The hasAttributeNS() method of the Element object returns True if there exists an
attribute of this element that has the specified namespaceURI and localName.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1440
Example
Listing 10.51 determines whether a line item element has an attribute for price set.
Element.removeAttribute()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.removeAttribute(name)
Description
The removeAttribute() method of the Element object removes the named attribute
specified by the string name from this element.
Example
Listing 10.52 removes the quantity attribute from an element representing a line item.
Element.removeAttributeNode()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.removeAttributeNode(oldAttr)
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1441
Description
The removeAttributeNode() method of the Element object removes oldAttr. A
DOMException object is raised with the value NO_MODIFICATION_ALLOWED_ERR if this
node is read-only or with value NOT_FOUND_ERR if oldAttr isn’t an attribute of this ele-
ment.
Example
Listing 10.53 Removes an attribute node from an element.
Element.removeAttributeNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.removeAttributeNS(namespaceURI, localName)
Description
The removeAttributeNS() method of the Element object removes the attribute speci-
fied by the given namespaceURI and localName. A DOMException object can be raised
with value NO_MODIFICATION_ALLOWED_ERR if this node is read-only.
Example
Listing 10.54 removes the quantity attribute from an element representing an invoice.
Element.setAttribute()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.setAttribute(name, value)
Description
The setAttribute() method of the Element object adds a new attribute named name
to value. If the attribute is already present, its value is changed to value. A
DOMException object can be raised with value INVALID_CHARACTER_ERR if the specified
name contains an illegal character or with a value NO_MODIFICATION_ALLOWED_ERR if
this node is read-only.
Example
Listing 10.55 sets a quantity attribute for an element that represents a line item.
Element.setAttributeNode()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.setAttributeNode(newAttr)
Description
The setAttributeNode() method of the Element object adds a new attribute node
newAttr. The newly placed Attr is returned. If newAttr is already an attribute of this
element, Null is returned.
Example
Listing 10.56 sets a attribute node representing a quantity for an element representing
a line item.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1443
Element.setAttributeNodeNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.setAttributeNodeNS(newAttr)
Description
The setAttributeNodeNS() method of the Element object adds a new attribute
newAttr. If an attribute with matching local name and namespace URI already exists,
it will be replaced. A DOMException object can be raised with value WRONG_DOCU-
MENT_ERR if newAttr was created by a document other than the one that created this
element or with value INUSE_ATTRIBUTE_ERR if newAttr is already an attribute of
another element. In this case, the newAttr needs to be cloned for reuse.
Example
Listing 10.57 sets a new quantity attribute for an element representing a line item.
Element.setAttributeNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.setAttributeNS(namespaceURI, qualifiedName, value)
Description
The setAttributeNS() method of the Element object adds a new attribute to this ele-
ment. If an attribute with the same namespaceURI and qualifiedName already exists,
its value will be replaced with the new value.
Example
Listing 10.58 sets an attribute using its namespace URI.
Element.tagName
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
elementObj.tagName
Description
The read-only property tagName of the Element object returns the name of this ele-
ment.
Example
Listing 10.59 queries an Element for its tagName.
Entity
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
The Entity object represents an XML entity that is either parsed or unparsed. It inher-
its all methods and properties of Node. Table 10.8 lists the properties for the Entity
object.
Example
An Entity is instantiated using the createEntity() method of the Document object.
Entity inherits all methods and properties from the Node object.
Entity.notationName
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
entityObj.notationName
Description
The read-only property notationName of the Entity object returns the name of the
notation for this entity if it is unparsed. If the entity is parsed, this returns null.
Example
Listing 10.60 retrieves the notation name from a Entity object.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1446
Entity.publicId
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
entityObj.publicId
Description
The read-only property publicId of the Entity object returns the public identifier
associated with this entity. If it isn’t specified, null is returned.
Example
Listing 10.61 retrieves the public identifier from an Entity object.
Entity.systemId
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
entityObj.systemId
Description
The read-only property systemId of the Entity object returns the system identifier
associated with this entity. If the system ID isn’t specified, this returns null.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1447
Example
Listing 10.62 retrieves the system identifier from an Entity object.
EntityReference
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
An EntityReference object inherits all methods and properties from Node.
Example
An EntityReference is instantiated using the createEntityReference() method
from the Document object.
NamedNodeMap
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object
Description
This is a list of DOM nodes with names associated with each. Table 10.9 lists all prop-
erties and methods of the NamedNodeMap object.
Example
Listing 10.63 retrieves the NamedNodeList attributes property from a
HTMLBodyElement object and reads its bgColor property.
NamedNodeMap.getNamedItem()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
namedNodeMapObj.getNamedItem(name)
Description
The getNamedItem() method of the NamedNodeMap object returns a node specified by
name.
Example
Listing 10.64 retrieves an attribute object by name from a NamedNodeMap and
processes it.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1449
NamedNodeMap.getNamedItemNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
namedNodeMap.getNamedItemNS(namespaceURI, localName)
Description
The getNamedItemNS() method of the NamedNodeMap object returns the node specified
by localName and namespaceURI. This method returns Null if no node exists for the
specified localName or namespaceURI.
Example
Listing 10.65 retrieves an attribute object by localName and a namespace URI from a
NamedNodeMap and processes it.
NamedNodeMap.item()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
namedNodeMapObj.item(index)
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1450
Description
The item() method of the NamedNodeMap object returns the node in position index in
this map. If no node exists at this position, null is returned.
Example
Listing 10.66 iterates through an attribute list processing each one.
NamedNodeMap.length
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
namedNodeMapObj.length
Description
The length property of the NamedNodeMap object returns the number of nodes con-
tained in this named node map.
Example
Listing 10.67 checks to see whether a node has any attributes. If it does, the attributes
are iterated over and processed. The attrList is an example of a NamedNodeMap.
i++;
}
}
// -->
</script>
</html>
NamedNodeMap.removeNamedItem()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
namedNodeMapObj.removeNamedItem(name)
Description
The removeNamedItem() method of the NamedNodeMap object removes the node speci-
fied by name and returns it. A DOMException can be raised with the value
NOT_FOUND_ERR if no name node is in this map, or with value
NO_MODIFICATION_ALLOWED_ERR if this map is read-only.
Example
Listing 10.68 removes a named item from an attribute list.
NamedNodeMap.removeNamedItemNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
namedNodeMapObj.removeNamedItemNS(name)
Description
The removeNamedItemNS() method of the NamedNodeList object removes a node spec-
ified by name and returns it. If no node exists with the name specified, null is returned.
Example
Listing 10.69 removes an item from an attribute list.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1452
NamedNodeMap.setNamedItem()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nameNodeMapObj.setNamedItem(node)
Description
The setNamedItem() method of the NamedNodeMap object adds a node using its
NodeName property. If a node is already present in this named node map with the same
name, it will be replaced. The newly added node is returned. A DOMException object
can be raised with one of the following values:
WRONG_DOCUMENT_ERR if the node was created from a different document than the
one that created this map
NO_MODIFICATION_ALLOWED_ERR if this map is read-only
INUSE_ATTRIBUTE_ERR if node is an Attr that is already an attribute of another
Element object. If this is the case, the DOM user must clone the Attr for reuse
Example
Listing 10.70 sets a new named attribute in an attribute list.
NamedNodeMap.setNamedItemNS()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
namedNodeMapObj.setNamedItemNS(node)
Description
The setNamedItemNS() method of the NamedNodeMap object adds a node to the map
using its namespaceURI and localName properties as keys on the map. If a node already
exists at the specified keys, it is replaced. A DOMException object can be raised with
one of the following values:
WRONG_DOCUMENT_ERR if the node was created by a document other than the one
that created this map
NO_MODIFICATION_ALLOWED_ERR if this map is read-only
INUSE_ATTRIBUTE_ERR if node is an Attr that is already an attribute of another
Element object. In this case, the DOM user must explicitly clone the Attr node
for reuse
Example
Listing 10.71 sets a new named attribute in an attribute list.
Node
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
The Node object represents a node of an XML document. Table 10.10 lists all constants,
properties, and methods of the Node object.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1454
Example
Because Node is a parent object to all DOM Core objects, it is never instantiated on its
own. Instead, its methods and properties are accessed via its child objects.
Node.attributes
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.attributes
Description
The read-only property attributes of the Node object returns a NamedNodeMap con-
taining all attributes of this node.
Example
Listing 10.72 iterates through a list of node attributes and processes them.
Node.appendChild()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.appendChild(newChild)
Description
The appendChild() method of the Node object adds newChild to the list of children for
this node. If newChild is already in the tree, it is first removed. The newly added child
node is returned. A DOMException can be raised with the value
HIERARCHY_REQUEST_ERR if this node is of a type that doesn’t accept children of the
newChild type, with value WRONG_DOCUMENT_ERR if newChild was created by a docu-
ment other than the one that created this node, or with value
NO_MODIFICATION_ALLOWED if this node is read-only.
Example
Listing 10.73 adds a new child to a node.
Node.childNodes
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.childNodes
Description
The childNodes attribute of the Node object returns a NodeList containing all children
of this node.
Example
Listing 10.74 returns all children of a node and then iterates through the list, printing
out the text contents if the node is a text node.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1458
Node.cloneNode()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.cloneNode(deep)
Description
The cloneNode() method of the Node object returns a duplicate copy of this node. If
deep is true, the subtree under this node is cloned along with this node.
Example
Listing 10.75 clones a node and then adds the clone as a child to another node.
Node.firstChild
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1459
Syntax
nodeObj.firstChild
Description
The read-only property firstChild of the Node object returns the first child of this
node.
Example
Listing 10.76 checks to see the type of the first child of this node.
Node.hasAttributes()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.hasAttributes()
Description
The hasAttributes() method of the Node object returns True if this node has any
attributes attached to it.
Example
Listing 10.77 checks to see whether a node has any attributes and iterates the list if it
does.
Node.hasChildNodes()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.hasChildNodes()
Description
The hasChildNodes() method of the Node object returns true if this node has children.
Example
Listing 10.78 tests to see if a node has children.
Node.insertBefore()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.insertBefore(newChild, refChild)
Description
The insertBefore() method of the Node object inserts the node newChild before the
existing child node refChild. If newChild is already in the tree, it is first removed. The
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1461
newly inserted child node is returned. A DOMException object can be raised with one
of the following values:
HIERARCHY_REQUEST_ERR if this node is a type that doesn’t allow children of the
newChild type
Example
Listing 10.79 inserts a new child node before a reference child node.
Node.isSupported()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.isSupported(feature, version)
Description
The isSupported() method of the Node object returns whether the specified feature
and version are supported by this node.
Example
Listing 10.80 queries a node for the availability of a certain feature.
Node.lastChild
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.lastChild
Description
The read-only property lastChild of the Node object returns the last child of this node.
Example
Listing 10.81 checks to see the type of the last child of this node.
Node.localName
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.localName
Description
The read-only property localName of the Node object returns the local part of the qual-
ified name for this node.
Example
Listing 10.82 takes the local name of a node and prepends the prefix to give the quali-
fied name of the node.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1463
Node.namespaceURI
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.namespaceURI
Description
The read-only property namespaceURI of the Node object returns a string containing
the namespace URI for this node.
Example
Listing 10.83 checks the prefix against the namespace URI and throws an exception if
the prefix is foo and the namespace URI is not http://foo.com/namespace.
Node.nextSibling
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.nextSibling
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1464
Description
The read-only property nextSibling of the Node object returns the node immediately
after this node.
Example
Listing 10.84 checks to see the type of the next sibling of this node.
Node.nodeName
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.nodeName
Description
The nodeName property of the Node object returns the name of this node as indicated by
the nodeType attribute.
Example
Listing 10.85 takes a Node and performs a particular operation depending on the
nodeName.
Node.nodeType
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.nodeType
Description
The nodeType property of the Node object returns a number indicating the node type of
this node as represented by the constants listed previously.
Example
Listing 10.86 checks the type of a node and processes it accordingly.
Node.nodeValue
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.nodeValue
Description
The nodeValue property of the Node object returns the value of this node depending on
its nodeType attribute
Example
Listing 10.87 illutstrates iterating through a list of elements processing each object’s
nodeValue property.
Node.normalize()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.normalize()
Description
The normalize() method of the Node object puts all Text nodes in the full depth of the
subtree underneath this node. This can be used to ensure that the DOM view of the
document is the same as if it were saved and reloaded.
Example
Listing 10.88 demonstrates normalizing a node before saving it to a file.
Node.ownerDocument
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.ownerDocument
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1467
Description
The read-only property ownerDocument of the Node object returns the Document object
associated with this node.
Example
Listing 10.89 retrieves the owner document of this node and creates a new element.
Node.parentNode
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.parentNode
Description
The parentNode property of the Node object returns the parent of this node.
Example
Listing 10.90 checks to see whether a node object has a parent.
Node.prefix
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.prefix
Description
The prefix property of the Node object returns the namespace prefix for this node. A
DOMException object can be raised with one of the following values:
Example
Listing 10.91 checks the prefix against the namespace URI and throws an exception if
the prefix is foo and the namespace URI isn’t http://foo.com/namespace.
Node.previousSibling
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.previousSibling
Description
The read-only property previousSibling of the Node object returns the node immedi-
ately before this node.
Example
Listing 10.92 illustrates checking to see the type of the previous sibling of this node.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1469
Node.removeChild()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.removeChild(oldChild)
Description
The removeChild() method of the Node object removes the child node specified by
oldChild from the list of children of this node. A DOMException object can by raised
with value NO_MODIFICATION_ALLOWED_ERR if this node is read-only, or with value
NOT_FOUND_ERR if oldChild isn’t a child of this node.
Example
Listing 10.93 removes a child from a node.
Node.replaceChild()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
nodeObj.replaceChild(newChild, oldChild)
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1470
Description
The replaceChild() method of the Node object replaces the child node oldChild with
a new child node newChild. If newChild is already in the tree, it is first removed. A
DOMException object is raised with one of the following values:
Example
Listing 10.94 replaces an existing child node with a new node.
Notation
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
Notation inherits all properties and methods from its parent class Node. A Notation
declares an unparsed entity in an XML document. Table 10.11 lists all properties of the
Notation object.
Example
A Notation is instantiated using the createNotation() method of the Document
object.
Notation.publicId
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
notationObj.publicId
Description
The read-only property publicId of the Notation object returns the public identifier
of this notation. If the PublicId is not specified for this notation, it returns null.
Example
Listing 10.95 retrieves the public identifier from a Notation object.
Notation.systemId
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
notationObj.systemId
Description
The read-only property systemId of the Notation object returns the system identifier
of this notation. If the systemId isn’t specified for this notation, it returns null.
Example
Listing 10.96 retrieves the system identifier from a Notation object.
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1472
ProcessingInstruction
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
ProcessingInstruction inherits all properties and methods from Node.
ProcessingInstruction represents an XML processing instruction that is used to
keep parser specific information in the text of the XML document. Table 10.12 lists the
properties of the ProcessingInstruction object.
Example
A ProcessingInstruction is instantiated using the
createProcessingInstruction() method of the Document object.
ProcessingInstruction.data
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
processingInstructionObj.data
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1473
Description
The read-only property data of the ProcessingInstruction object returns the content
of the processing instruction. A DOMException object can be raised with the value
NO_MODIFICATION_ALLOWED_ERR when this node is read-only.
Example
Listing 10.97 illustrates the retrieval of the data property.
ProcessingInstruction.target
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
processingInstructionObj.target
Description
The readonly property target if the ProcessingInstruction object returns the target
of this processing instruction.
Example
Listing 10.97 illustrates the retrieval of the target property.
Text
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
Core DOM object.
Description
A Text object represents textual content in an XML document. If no markup is present
in an element’s content, it is stored as a Text object. Text inherits all methods and
properties of CharacterData, which, in turn, inherits from Node. An argument associ-
ated with the Text object is as follows:
Type Item Description
Method splitText() Breaks this node into two nodes at a specified
offset
Example
A Text object is created by the createTextNode() method of the Document object.
Text.splitText()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
textObj.splitText(offset)
Description
The splitText() method of the Text object breaks this text node into two nodes at the
given offset. After the text is split, the new node becomes a sibling of this node and
will contain all the text after the offset. The new Text node is returned. A
DOMException can be raised with the value INDEX_SIZE_ERR if the specified offset is
negative or greater than the size of the contained text data or with the value NO_MODI-
FICATION_ALLOWED_ERR if this node is read-only.
Example
Listing 10.98 demonstrates splitting a Text node’s Data into another Text node.
Listing 10.98 Splitting Text Using the splitText() Method of the Text
Object
<html>
<script language=”JScript”>
<!--
var textObj = documentObject.createTextNode(“This is some text”);
var splitTextObj = textObj.splitText(5);
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1475
// -->
</script>
</html>
22 0672321416 CH10 was 9 7/30/01 1:30 PM Page CD:1476
31 0672321416 Index 7/30/01 2:03 PM Page CD:2169
31 0672321416 Index 7/30/01 2:03 PM Page CD:2170
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1479
DOM HTML
CHAPTER 11
DOM HTML
This chapter extends the DOM Level 2 Core API to describe
objects and methods specific to HTML documents. In general,
the functionality needed to manipulate hierarchical document
structures, elements, and attributes will be found in the core
section; functionality that depends on the specific elements
defined in HTML will be found in this chapter.
The goals of the HTML-specific DOM API are
• To specialize and add functionality that relates specifi-
cally to HTML documents and elements.
• To address issues of backward compatibility with the
DOM Level 0.
• To provide convenience mechanisms, where appropri-
ate, for common and frequent operations on HTML
documents.
The key differences between the core DOM and the HTML
application of DOM is that the HTML Document Object
Model exposes a number of convenience methods and proper-
ties that are consistent with the existing DOM Level 1 and 0
models and are more appropriate to script writers. In many
cases, these enhancements aren’t applicable to a general DOM
because they rely on the presence of a predefined DTD. The
transitional and frameset DTDs for HTML 4.0 are assumed.
Interoperability between implementations is only guaranteed
for elements and attributes that are specified in the HTML 4.0
DTDs.
More specifically, this document includes the following spe-
cializations for HTML:
• An HTMLDocument interface, derived from the core
Document interface. HTMLDocument specifies the
operations and queries that can be made on a HTML
document.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1480
NOTE
At the time of this writing, the DOM HTML Level 2 specification was at a working
draft state, whereas all other portions of Level 2 (Core, Events, and so on) were
complete and a full recommendation. For that reason, some of the descriptions
and information in this chapter could change before the specification is final.
HTMLAnchorElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
The HTMLAnchorElement object represents an HTML anchor element. The
HTMLAnchorElement inherits all methods and properties from the HTMLElement object.
Table 11.1 contains a list of properties and methods for this object.
Example
Listing 11.1 illustrates the creation of an HTMLBodyElement using the HTMLDocument
object element and then setting its Alink property.
// -->
</script>
</html>
HTMLAnchorElement.accessKey
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.accessKey
Description
The accessKey property of the HTMLAnchorElement object is a single character access
key to give access to the form control.
Example
Listing 11.2 illustrates the creation of an HTMLAnchorElement using the HTMLDocument
object element and then setting its accessKey property.
HTMLAnchorElement.blur()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.blur()
Description
The blur() method of the HTMLAnchorElement object removes keyboard focus from
this element.
Example
Listing 11.3 illustrates the creation of an HTMLAnchorElement using the HTMLDocument
object element and then calling its blur() method.
HTMLAnchorElement.charset
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.charset
Description
The charset property of the HTMLAnchorElement object represents the character
encoding of the linked resource.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1483
Example
Listing 11.4 illustrates the creation of an HTMLAnchorElement object using the
HTMLBodyElement object and then setting its charset property.
HTMLAnchorElement.coords
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.coords
Description
The coords property of the HTMLAnchorElement object is a comma-separated list of
lengths, defining an active region’s geometry. See also shape for the shape of the
region.
Example
Listing 11.5 illustrates the creation of an HTMLAnchorElement object using the
HTMLBodyElement object and then setting its coords property.
HTMLAnchorElement.focus()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.focus()
Description
The focus() method of the HTMLAnchorElement object gives keyboard focus to this
element.
Example
Listing 11.6 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object and the invocation of its focus() method.
HTMLAnchorElement.href
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.href
Description
The href property of the HTMLAnchorElement object represents the URI of the linked
resource.
Example
Listing 11.7 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object and then setting its href property.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1485
HTMLAnchorElement.hrefLang
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.hrefLang
Description
The hrefLang property of the HTMLAnchorElement object represents the language code
of the linked resource.
Example
Listing 11.8 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object element and then setting its hrefLang property.
HTMLAnchorElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.name
Description
The name property of the HTMLAnchorElement object represents the anchor name.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1486
Example
Listing 11.9 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object and then setting its name property.
HTMLAnchorElement.rel
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.rel
Description
The rel property of the HTMLAnchorElement object represents a forward link type.
Example
Listing 11.10 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object element and then setting its rel property.
HTMLAnchorElement.rev
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.rev
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1487
Description
The rev property of the HTMLAnchorElement object represents a reverse link type.
Example
Listing 11.11 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object and then setting its rev property.
HTMLAnchorElement.shape
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.shape
Description
The shape property of the HTMLAnchorElement object represents the shape of the active
area. The coordinates are given by coords.
Example
Listing 11.12 illustrates the creation of an HTMLAnchorElement using the HTMLBody
object and then setting its shape property.
HTMLAnchorElement.tabIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.tabIndex
Description
The tabIndex property of the HTMLAnchorElement object represents the index that rep-
resents the element’s position in the tabbing order.
Example
Listing 11.13 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object and then setting its tabIndex property.
HTMLAnchorElement.target
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.target
Description
The target property of the HTMLAnchorElement object represents the frame to render
the resource in.
Example
Listing 11.14 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object and then setting its target property.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1489
HTMLAnchorElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAnchorObj.type
Description
The type property of the HTMLAnchorElement object represents an advisory content
type.
Example
Listing 11.15 illustrates the creation of an HTMLAnchorElement using the
HTMLBodyElement object and then setting its type property.
HTMLAppletElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1490
Description
This object represents an HTML applet element. The HTMLAppletElement inherits all
properties and methods of the HTMLElement object. Table 11.2 contains a list of prop-
erties and methods for this object.
Example
Listing 11.16 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its align property.
HTMLAppletElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.align
Description
The align property of the HTMLAppletElement object aligns this object (vertically or
horizontally) with respect to its surrounding text.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1491
Example
Listing 11.17 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its align property.
HTMLAppletElement.alt
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.alt
Description
The alt property of the HTMLAppletElement object represents the alternate text for
user agents not rendering the normal content of this element.
Example
Listing 11.18 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its alt property.
HTMLAppletElement.archive
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.archive
Description
The archive property of the HTMLAppletElement object is a comma-separated archive
list.
Example
Listing 11.19 illustrates the creation of an HTMLAppletElement using the
HTMLBodyObject object and then setting its archive property.
HTMLAppletElement.code
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.code
Description
The code property of the HTMLAppletElement object is the applet class file.
Example
Listing 11.20 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object element and then setting its code property.
<!--
var appletObj = bodyObj.createElement(“applet”);
appletObj.code = “foo.bar.applets.FooApplet”;
// -->
</script>
</html>
HTMLAppletElement.codeBase
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.codeBase
Description
The codeBase property of the HTMLAppletElement object is an optional base URI for
applet.
Example
Listing 11.21 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its codeBase property.
HTMLAppletElement.height
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.height
Description
The height property of the HTMLAppletElement object allows you to override height.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1494
Example
Listing 11.22 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its height property.
HTMLAppletElement.hspace
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.hspace
Description
The hspace property of the HTMLAppletElement object represents the horizontal space
to the left and right of this applet.
Example
Listing 11.23 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its hspace property.
HTMLAppletElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.name
Description
The name property of the HTMLAppletElement object contains the name of the applet.
Example
Listing 11.24 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its name property.
HTMLAppletElement.object
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.object
Description
The object property of the HTMLAppletElement object represents the serialized applet
file.
Example
Listing 11.25 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its object property.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1496
HTMLAppletElement.vspace
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.vspace
Description
The vspace property of the HTMLAppletElement object represents the vertical space
above and below the applet.
Example
Listing 11.26 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its vspace property.
HTMLAppletElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAppletObj.width
Description
The width property of the HTMLAppletElement object allows you to override width.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1497
Example
Listing 11.27 illustrates the creation of an HTMLAppletElement using the
HTMLBodyElement object and then setting its width property.
HTMLAreaElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML area element. Table 11.3 contains a list of properties
and methods for this object.
Example
Listing 11.28 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object and then setting its accessKey property.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1498
HTMLAreaElement.accessKey
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAreaObj.accessKey
Description
The accessKey property of the HTMLAreaElement object is a single character access
key to give access to the form control.
Example
Listing 11.29 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object and then setting its accessKey property.
HTMLAreaElement.alt
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAreaObj.alt
Description
The alt property of the HTMLAreaElement object represents the alternate text for user
agents not rendering the normal content of this element.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1499
Example
Listing 11.30 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object element and then setting its alt property.
// -->
</script>
</html>
HTMLAreaElement.coords
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAreaObj.coords
Description
The coords property of the HTMLAreaElement object is a comma-separated list of
lengths, defining an active region’s geometry.
Example
Listing 11.31 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object and then setting its coords property.
// -->
</script>
</html>
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1500
HTMLAreaElement.href
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAreaObj.href
Description
The href property of the HTMLAreaElement object represents the URI of the linked
resource.
Example
Listing 11.32 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object and then setting its href property.
// -->
</script>
</html>
HTMLAreaElement.noHref
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAreaObj.noHref
Description
The noHref property of the HTMLAreaElement object specifies that this area is inactive;
that is, it has no associated action.
Example
Listing 11.33 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object and then setting its noHref property.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1501
// -->
</script>
</html>
HTMLAreaElement.shape
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAreaObj.shape
Description
The shape property of the HTMLAreaElement object represents the shape of the active
area. The coordinates are given by coordinates.
Example
Listing 11.34 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object and then setting its shape property.
// -->
</script>
</html>
HTMLAreaElement.tabIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAreaObj.tabIndex
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1502
Description
The tabIndex property of the HTMLAreaElement object is a index that represents the
element’s position in the tabbing order.
Example
Listing 11.35 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object and then setting its tabIndex property.
// -->
</script>
</html>
HTMLAreaElement.target
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlAreaObj.target
Description
The target property of the HTMLAreaElement object represents the frame to render the
resource in.
Example
Listing 11.36 illustrates the creation of an HTMLAreaElement using the
HTMLMapElement object and then setting its target property.
</script>
</html>
HTMLBaseElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
The HTMLBaseElement object encapsulates the Document base URI. HTMLBaseElement
inherits all methods and properties from HTMLElement. Table 11.4 contains a list of
properties and methods for this object.
Example
Listing 11.37 illustrates the creation of an HTMLBaseElement using the HTMLDocument
object.
HTMLBaseElement.href
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBaseElemObj.href
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1504
Description
The href property of the HTMLBaseElement object represents the base URI for this ele-
ment.
Example
Listing 11.38 illustrates the creation of an HTMLBaseElement using the HTMLDocument
object element and then setting its href and target properties.
// -->
</script>
</html>
HTMLBaseElement.target
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBaseElemObj.target
Description
The target property of the HTMLBaseElement object represents the default target
frame.
Example
Listing 11.39 illustrates the creation of an HTMlBaseElement using the HTMLDocument
object element and then setting its target property.
baseElement.target = “MainFrame”;
// -->
</script>
</html>
HTMLBaseFontElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML BASEFONT element. The HTMLBaseFontElement inher-
its all methods and properties from the HTMLElement object. Table 11.5 contains a list
of properties for this object.
Example
Listing 11.40 illustrates the creation of an HTMLBaseFontElement using the
HTMLBodyElement object.
// -->
</script>
</html>
HTMLBaseFontElement.color
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBaseFontObj.color
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1506
Description
The color property of the HTMLBaseFontElement object represents the color of this
font.
Example
Listing 11.41 illustrates the creation of an HTMLBaseFontElement using the HTMLBody
object and then setting its color property.
HTMLBaseFontElement.face
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBaseFontObj.face
Description
The face property of the HTMLBaseFontElement object is the font face identifier.
Example
Listing 11.42 illustrates the creation of an HTMLBaseFontElement using the
HTMLBodyElement object and then setting its face property.
HTMLBaseFontElement.size
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBaseFontObj.size
Description
The size property of the HTMLBaseFontElement object is the font size.
Example
Listing 11.43 illustrates the creation of an HTMLBaseFontElement using the
HTMLBodyElement object and then setting its size property.
HTMLBodyElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object encapsulates the HTML document body. This element is always present in
the DOM API, even if the tags are not present in the source document.
HTMLBodyElement inherits all methods and properties from HTMLElement. Table 11.6
contains a list of properties for this object.
Example
Listing 11.44 illustrates the creation of an HTMLBodyElement.
// -->
</script>
</html>
HTMLBodyElement.aLink
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBodyObj.aLink
Description
The aLink property of the HTMLBodyElement object represents the color of active links
(after mouse button down, but before mouse button up).
Example
Listing 11.45 illustrates the creation of an HTMLBodyElement using the HTMLDocument
object element and then setting its aLink property.
// -->
</script>
</html>
HTMLBodyElement.background
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBodyObj.background
Description
The background property of the HTMLBodyElement object is the URI of the background
texture tile image.
Example
Listing 11.46 illustrates the creation of an HTMLBodyElement using the HTMLDocument
object and then setting its background property.
HTMLBodyElement.bgColor
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBodyObj.bgColor
Description
The bgColor property of the HTMLBodyElement object is the document background
color.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1510
Example
Listing 11.47 illustrates the creation of an HTMLBodyElement using the HTMLDocument
object element and then setting its bgColor property.
HTMLBodyElement.link
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBodyObj.link
Description
The link property of the HTMLBodyElement object is the color of links that are inactive
and unvisited.
Example
Listing 11.48 illustrates the creation of an HTMLBodyElement using the HTMLDocument
object element and then setting its link property.
HTMLBodyElement.text
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBodyObj.text
Description
The text property of the HTMLBodyElement object is the document text color.
Example
Listing 11.49 illustrates the creation of an HTMLBodyElement using the HTMLDocument
object element and then setting its text property.
HTMLBodyElement.vLink
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBodyObj.vLink
Description
The vLink property of the HTMLBodyElement object represents the color of links that
have been visited by the user.
Example
Listing 11.50 illustrates the creation of an HTMLBodyElement using the HTMLDocument
object element and then setting its vLink property.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1512
HTMLBRElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents the HTML element that forces a line break. The HTMLBRElement
inherits all methods and properties of the HTMLElement object. The property for this
object is as follows:
Item Description
clear Controls flow of text
Example
Listing 11.51 illustrates the creation of an HTMLBRElement using the HTMLBodyElement.
// -->
</script>
</html>
HTMLBRElement.clear
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlBRObj.clear
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1513
Description
The clear property of the HTMLBRElement object controls flow of text around floats.
Example
Listing 11.52 illustrates the creation of an HTMLBRElement using the HTMLBodyElement
object and then setting its clear property.
HTMLButtonElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML button element. It inherits all methods and properties
of the HTMLElement object. Table 11.7 contains a list of properties for this object.
Example
Listing 11.53 illustrates the creation of a HTMLButtonElement using a
HTMLFormElement and setting its type property.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1514
HTMLButtonElement.accessKey
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlButtonObj.accessKey
Description
The accessKey property of the HTMLButtonElement object is a single character access
key to give access to the form control.
Example
Listing 11.54 illustrates the creation of an HTMLButtonElement using the
HTMLFormElement object and then setting its accessKey property.
HTMLButtonElement.disabled
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlButtonObj.disabled
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1515
Description
The disable property of the HTMLButtonElement object allows you to disable button
instances.
Example
Listing 11.55 illustrates the creation of an HTMLButtonElement using the
HTMLFormElement object and then setting its disabled property.
HTMLButtonElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlButtonObj.form
Description
The form property of the HTMLButtonElement object returns the FORM element con-
taining this control. It returns Null if this control isn’t within the context of a form.
Example
Listing 11.56 illustrates the creation of an HTMLButtonElement using the
HTMLFormElement object and then reading its form Property.
HTMLButtonElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlButtonObj.name
Description
The name property of the HTMLButtonElement object represents a form control or
object name when submitted with a form.
Example
Listing 11.57 illustrates the creation of an HTMLButtonElement using the
HTMLFormElement object and then setting its name property.
HTMLButtonElement.tabIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlButtonObj.tabIndex
Description
The tabIndex property of the HTMLButtonElement object is the index that represents
the element’s position in the tabbing order.
Example
Listing 11.58 illustrates the creation of an HTMLButtonElement using the
HTMLFormElement object and then setting its tabIndex property.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1517
HTMLButtonElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlButtonObj.type
Description
The type property of the HTMLButtonElement object represents the type of button.
Example
Listing 11.59 illustrates the creation of an HTMLButtonElement using the
HTMLFormElement object element and then setting its type property.
HTMLButtonElement.value
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlButtonObj.value
Description
The value property of the HTMLButtonElement object is the current form control value.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1518
Example
Listing 11.60 illustrates the creation of an HTMLButtonElement using the
HTMLFormElement object element and then setting its value property.
HTMLCollection
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
An HTMLCollection is a list of nodes. An individual node can be accessed by either
ordinal index or the node’s name or ID attributes.
NOTE
Collections in the HTML DOM are assumed to be live meaning that they are auto-
matically updated when the underlying document is changed.
Table 11.8 contains a list of the property and methods for this object.
Example
Listing 11.61 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object then iterating through that document’s images prop-
erty processing each image.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1519
}
</script>
</html>
HTMLCollection.item()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlCollectionObj.item(index)
Description
The item() method of the HTMLCollection object retrieves a node specified by num-
ber index. Nodes are numbered in tree order (depth-first traversal order).
Example
Listing 11.63 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then iterating through that document’s images
property processing each image.
HTMLCollection.length
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlCollectionObj.length
Description
The length property of the HTMLCollection object specifies the length or size of the
list.
Example
Listing 11.62 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then iterating through that document’s images
property processing each image.
}
</script>
</html>
HTMLCollection.namedItem()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlCollectionObj.namedItem(name)
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1521
Description
The namedItem() method of the HTMLCollection object retrieves a Node using a name.
It first searches for a Node with a matching ID attribute. If it doesn’t find one, it then
searches for a Node with a matching name attribute, but only on those elements that are
allowed a name attribute.
Example
Listing 11.64 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and the iteration through that document’s images
property processing each image.
HTMLDirectoryElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML directory element. The HTMLDirectoryElement object
inherits all methods and properties from HTMLElement. The property for this object is
as follows:
Item Description
compact Reduces the spacing between list items when true
Example
Listing 11.65 illustrates the creation of an HTMLDirectoryElement using the
HTMLDListElement.
23 0672321416 CH11 was 10 7/30/01 1:34 PM Page CD:1522
// -->
</script>
</html>
HTMLDirectoryElement.compact
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDirectoryObj.compact
Description
The compact property of the HTMLDirectoryElement object reduces the spacing
between list items.
Example
Listing 11.66 illustrates the creation of an HTMLDirectoryElement using the
HTMLDListElement object and then setting its compact property.
HTMLDivElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1523
Description
This object represents an HTML generic block container. The HTMLDivElement object
inherits all methods and properties from HTMLElement. The property for this object is
as follows:
Item Description
align Horizontal text alignment for this DIV element
Example
Listing 11.67 illustrates the creation of an HTMLDivElement using the
HTMLBodyElement object and then setting its align property.
HTMLDivElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDivObj.align
Description
The align property of the HTMLDivElement object represents the horizontal text align-
ment.
Example
Listing 11.68 illustrates the creation of an HTMLDivElement using the
HTMLBodyElement object and then setting its align property.
HTMLDListElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML directory list element. The HTMLDListElement object
inherits all methods and properties from HTMLElement. The property for this object is
as follows:
Item Description
compact Reduces the spacing between list items if true
Example
Listing 11.69 illustrates the creation of an HTMLDListElement using the
HTMLBodyElement object element and then setting its compact property.
HTMLDListElement.compact
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDListObj.compact
Description
The compact property of the HTMLDListElement object reduces the spacing between
list items.
Example
Listing 11.70 illustrates the creation of an HTMLDListElement using the
HTMLBodyElement object element and then setting its compact property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1525
HTMLDocument
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
An HTMLDocument is the root of the HTML hierarchy and holds the entire content.
Besides providing access to the hierarchy, it also provides some convenience methods
for accessing certain sets of information from the document. Table 11.9 contains a list
of properties and methods for this object.
Example
Listing 11.71 creates a new HTMLDocument object using the createHTMLDocument()
method of HTMLDOMImplementation.
HTMLDocument.anchors
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.anchors
Description
The anchors property of the HTMLDocument object is a collection of all the anchor (A)
elements in a document with a value for the name attribute.
NOTE
For reasons of backward compatibility, the returned set of anchors only contains
those anchors created with the name attribute, not those created with the ID
attribute.
Example
Listing 11.72 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object then iterating through that document’s anchors prop-
erty processing each anchor element.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1527
HTMLDocument.applets
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.applets
Description
The applets property of the HTMLDocument object is a collection of all the OBJECT ele-
ments that include applets and APPLET (deprecated) elements in a document.
Example
Listing 11.73 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object then iterating through that document’s applets prop-
erty processing each applet.
HTMLDocument.body
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.body
Description
The body property of the HTMLDocument object is the element that contains the content
for the document. In documents with BODY contents, this returns the BODY element. In
frameset documents, this returns the outermost FRAMESET element.
Example
Listing 11.74 creates a new HTMLDocument object using the createHTMLDocument()
method of HTMLDOMImplementation and then changes the background color of the
body property.
HTMLDocument.close()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.close()
Description
The close() method of the HTMLDocument object closes a document stream opened by
open() and forces rendering.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1529
Example
Listing 11.75 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then using the open() method to open this docu-
ment for writing. A cookie is added and then the document is closed using close().
HTMLDocument.cookie
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.cookie
Description
The cookie property of the HTMLDocument object represents the cookies associated
with this document. If there are none, the value is an empty string. Otherwise, the value
is a string: a semicolon-delimited list of name=value pairs for all the cookies associ-
ated with the page; for example, name=value;expires=date.
Example
Listing 11.76 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then accessing the cookie property and setting its
value.
HTMLDocument.domain
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.domain
Description
The domain property of the HTMLDocument object represents the domain name of the
server that served the document, or Null if the server cannot be identified by a domain
name.
Example
Listing 11.77 creates a new HTMLDocument object using the createHTMLDocument()
method of HTMLDOMImplementation and then inspects the domain property to see
which domain the page originated from.
HTMLDocument.forms
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.forms
Description
The forms property of the HTMLDocument object is a collection of all the forms of a doc-
ument.
Example
Listing 11.78 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then iterating through that document’s forms
property processing the form with the name “emailForm”.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1531
HTMLDocument.getElementsByName()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.getElementsByName(name)
Description
The getElementsByName() method of the HTMLDocument object returns the (possibly
empty) collection of elements whose name value is given by name.
Example
Listing 11.79 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then iterating through that document’s list of
images using the getElementsByName() method processing each image element.
HTMLDocument.images
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.images
Description
The images property of the HTMLDocument object is a collection of all the IMG ele-
ments in a document. The behavior is limited to IMG elements for backward compat-
ibility.
Example
Listing 11.80 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then iterating through that document’s images
property processing each image.
HTMLDocument.links
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.links
Description
The links property of the HTMLDocument object is a collection of all AREA elements and
anchor (A) elements in a document with a value for the href attribute.
Example
Listing 11.81 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then iterating through that document’s links
property processing each applet.
HTMLDocument.open()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.open()
Description
The open() method of the HTMLDocument object is used to open a document stream for
writing. If a document exists in the target, this method clears it.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1534
Example
Listing 11.82 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then using the open() method to open this docu-
ment for writing.
HTMLDocument.referrer
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.referrer
Description
The referrer property of the HTMLDocument object returns the URI of the page that
linked to this page. The value is an empty string if the user navigated to the page
directly (not through a link, but, for example, via a bookmark).
Example
Listing 11.83 creates a new HTMLDocument object using the createHTMLDocument()
method of HTMLDOMImplementation and then inspects the referrer property to see
which server the page originated from.
HTMLDocument.title
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.title
Description
The title property of the HTMLDocument object represents the title of a document as
specified by the TITLE element in the head of the document.
Example
Listing 11.84 creates a new HTMLDocument object using the createHTMLDocument()
method of HTMLDOMImplementation and then changes the title.
HTMLDocument.URL
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.URL
Description
The URL property of the HTMLDocument object represents the complete URI of the doc-
ument.
Example
Listing 11.85 creates a new HTMLDocument object using the createHTMLDocument()
method of HTMLDOMImplementation and then creates a TEXTAREA element and sets its
value to be that of the URL property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1536
HTMLDocument.write()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.write(string)
Description
The write() method of the HTMLDocument object is used to write a string to a docu-
ment stream opened by open(). The string is parsed into the document’s structure
model.
Example
Listing 11.86 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then using the write() method to write text data
to this document.
// -->
</html>
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1537
HTMLDocument.writeln()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDoc.writeln(string)
Description
The writeln() method of the HTMLDocument object is used to write a string followed
by a newline character to a document stream opened by open(). The string is parsed
into the document’s structure model.
Example
Listing 11.87 illustrates the creation of an HTMLDocument using the
HTMLDOMImplementation object and then using the writeln() method to write text
data to this document.
HTMLDOMImplementation
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
The HTMLDOMImplementation object inherits all properties and methods of the
DOMImplementation object with a method for creating an HTML document instance.
The method for this object is as follows:
Item Description
createHTMLDocument() Creates an HTML Document and returns it
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1538
Example
Listing 11.88 creates a new HTMLDocument object using the createHTMLDocument()
method of HTMLDOMImplementation.
HTMLDOMImplementation.createHTMLDocument()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlDOMImpl.createHTMLDocument(documentTitle);
Description
The createHTMLDocument() method of the HTMLDOMImplementation object creates an
HTMLDocument object with the minimal tree made of the following elements: HTML,
HEAD, TITLE, and BODY.
The documentTitle parameter names the title of the document to be set as the content
of the TITLE element, through a child Text node.
Example
Listing 11.89 creates a new HTMLDocument object using the createHTMLDocument()
method of HTMLDOMImplementation.
HTMLElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
All HTML element objects inherit from this object. The base HTMLElement object rep-
resents elements that only expose the HTML core attributes.
These elements are as follows:
• HEAD
• special: SUB, SUP, SPAN, BDO
• font: TT, I, B, U, S, STRIKE, BIG, SMALL
• phrase: EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ACRONYM, ABBR
• list: DD, DT
• NOFRAMES, NOSCRIPT
• ADDRESS, CENTER
Example
Listing 11.90 illustrates the creation of a BaseElement object interrogating its id to
verify the correct type.
HTMLElement.className
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlElemObj.className
Description
The className property of the HTMLElement object is the class attribute of the element.
Example
Listing 11.91 illustrates the creation of a TextAreaElement object and setting its
className property.
HTMLElement.dir
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlElemObj.dir
Description
The dir property of the HTMLElement object specifies the base direction of direction-
ally neutral text and the directionality of tables.
Example
Listing 11.92 illustrates the setting the dir property of the HTMLElement object.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1541
HTMLElement.id
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlElemObj.id
Description
The id property of the HTMLElement object represents the element’s identifier.
Example
Listing 11.93 illustrates the creation of a BaseElement object interrogating its ID to
verify the correct type.
HTMLElement.lang
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlElemObj.lang
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1542
Description
The lang property of the HTMLElement object represents the language code defined in
RFC 1766, which can be found at http://www.ietf.org.
Example
Listing 11.94 illustrates writing if the lang property of the HTMLElement object.
HTMLElement.title
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlElemObj.title
Description
The title property of the HTMLElement object is the element’s advisory title.
Example
Listing 11.95 illustrates the creation of a HTMLElement and setting its title.
HTMLFieldSetElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
The HTMLFieldSetElement organizes form controls into logical groups. This object
inherits all properties and methods from the HTMLElement object. The property for this
object is as follows:
Item Description
form The form in which this field set element resides
Example
Listing 11.96 illustrates the creation of HTMLFieldSetElement object
HTMLFieldSetElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormSetObj.form
Description
The form property of the HTMLFieldSetElement returns the FORM element containing
this control. Returns Null if this control isn’t within the context of a form.
Example
Listing 11.97 illustrates the creation of an HTMLFieldSetElement using the
HTMLFormElement object and then checking its form property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1544
HTMLFontElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML Font element. HTMLFontElement inherits all methods
and properties of HTMLElement. Table 11.11 contains a list of properties for this object.
Example
Listing 11.98 illustrates the creation of an HTMLFontElement using the
HTMLBodyElement object.
// -->
</script>
</html>
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1545
HTMLFontElement.color
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFontObj.color
Description
The color property of the HTMLFontElement object represents the font color.
Example
Listing 11.99 illustrates the creation of an HTMLFontElement using the
HTMLBodyElement object and then setting its color property.
HTMLFontElement.face
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFontObj.face
Description
The face property of the HTMLFontElement object represents the font face identifier.
Example
Listing 11.100 illustrates the creation of an HTMLFontElement using the
HTMLBodyElement object and then setting its face property.
HTMLFontElement.size
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFontObj.size
Description
The size property of the HTMLFontElement object represents the font size.
Example
Listing 11.101 illustrates the creation of an HTMLFontElement using the
HTMLBodyElement object element and then setting its size property.
HTMLFormElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
The FORM element encompasses behavior similar to a collection and an element. It
provides direct access to the contained input elements as well as the attributes of the
form element. This object inherits all methods and properties from HTMLElement. Table
11.12 contains a list of properties and methods for this object.
Example
Listing 11.102 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then the iteration through its elements property.
HTMLFormElement.acceptCharset
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.acceptCharset
Description
The acceptCharset property of the HTMLFormElement object is a list of character sets
supported by the server.
Example
Listing 11.103 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then setting its acceptCharset property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1548
HTMLFormElement.action
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.action
Description
The action property of the HTMLFormElement object is a server-side form handler.
Example
Listing 11.104 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then setting its action property.
HTMLFormElement.elements
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.elements
Description
The elements property of the HTMLFormElement object returns a collection of all con-
trol elements in the form.
Example
Listing 11.105 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then the iteration through its elements property.
HTMLFormElement.enctype
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.enctype
Description
The enctype property of the HTMLFormElement object is the content type of the sub-
mitted form, generally “application/x-www-form-urlencoded”.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1550
Example
Listing 11.106 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then setting its enctype property.
HTMLFormElement.length
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.length
Description
The length property of the HTMLFormElement object is the number of form controls in
the form.
Example
Listing 11.107 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then reading its length property.
HTMLFormElement.method
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.method
Description
The method property of the HTMLFormElement object is the HTTP method used to sub-
mit form.
Example
Listing 11.108 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then setting its method property.
HTMLFormElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.name
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1552
Description
The name property of the HTMLFormElement object names the form.
Example
Listing 11.109 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then setting its name property.
HTMLFormElement.reset()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.reset()
Description
The reset() method of the HTMLFormElement object restores a form element’s default
values. It performs the same action as a reset button.
Example
Listing 11.110 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then the invocation of its reset() method.
// -->
</script>
</html>
HTMLFormElement.submit()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.submit()
Description
The submit() method of the HTMLFormElement object submits the form. It performs
the same action as a submit button.
Example
Listing 11.111 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then the invocation of its submit() method.
HTMLFormElement.target
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFormObj.target
Description
The target property of the HTMLFormElement object is the frame to render the
resource in.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1554
Example
Listing 11.112 illustrates the creation of an HTMLFormElement using the
HTMLBodyElement object and then setting its target property.
HTMLFrameElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML frame element. It is used to create a frame. The
HTMLFrameElement inherits all properties and methods from HTMLElement. Table 11.13
contains a list of properties for this object.
Example
Listing 11.113 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1555
HTMLFrameElement.contentDocument
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.contentDocument
Description
The contentDocument property of the HTMLFrameElement object is the document this
frame contains, if there is one and it is available, or Null otherwise.
Example
Listing 11.114 illustrates reading the contentDocument property of a
HTMLFrameElement object.
HTMLFrameElement.frameBorder
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.frameBorder
Description
The frameBorder property of the HTMLFrameElement object is the request frame
borders.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1556
Example
Listing 11.115 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object and then setting its frameBorder property.
HTMLFrameElement.longDesc
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.longDesc
Description
The longDesc property of the HTMLFrameElement object is the URI designating a long
description of this image or frame.
Example
Listing 11.116 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object and then setting its longDesc property.
HTMLFrameElement.marginHeight
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.marginHeight
Description
The marginHeight property of the HTMLFrameElement object is the frame margin
height, in pixels.
Example
Listing 11.117 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object and then setting its marginHeight property.
HTMLFrameElement.marginWidth
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.marginWidth
Description
The marginWidth property of the HTMLFrameElement object is the frame margin width,
in pixels.
Example
Listing 11.118 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object and then setting its marginWidth property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1558
HTMLFrameElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.name
Description
The name property of the HTMLFrameElement object is the frame name (object of the
target attribute).
Example
Listing 11.119 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object element and then setting its name property.
HTMLFrameElement.noResize
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.noResize
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1559
Description
The noResize property of the HTMLFrameElement object forbids user from resizing
frame when true.
Example
Listing 11.120 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object and then setting its noResize property.
HTMLFrameElement.scrolling
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.scrolling
Description
The scrolling property of the HTMLFrameElement object specifies whether the frame
should have scrollbars.
Example
Listing 11.121 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object and then setting its scrolling property.
HTMLFrameElement.src
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameObj.src
Description
The src property of the HTMLFrameElement object is a URI designating the initial
frame contents.
Example
Listing 11.122 illustrates the creation of an HTMLFrameElement using the
HTMLFrameSetElement object and then setting its src property.
HTMLFrameSetElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML frameset element and is used to create a grid of
frames. The HTMLFrameSetElement object inherits all properties and methods from
HTMLElement. Table 11.14 contains a list of properties for this object.
Example
Listing 11.123 illustrates the creation of an HTMLFrameSetElement using the
HTMLDocument object.
// -->
</script>
</html>
HTMLFrameSetElement.cols
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameSetObj.cols
Description
The cols property of the HTMLFrameSetElement object is the number of columns of
frames in the frameset.
Example
Listing 11.124 illustrates the creation of an HTMLFrameSetElement using the
HTMLDocument object and then setting its cols property.
HTMLFrameSetElement.rows
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlFrameSetObj.rows
Description
The rows property of the HTMLFrameSetElement object is the number of rows of frames
in the frameset.
Example
Listing 11.125 illustrates the creation of an HTMLFrameSetElement using the
HTMLDocument object element and then setting its rows property.
HTMLHeadElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents this document’s header information. This object inherits all
methods and properties from the HTMLElement object. The property for this object is as
follows:
Item Description
profile URI specifying the metadata profile
Example
Listing 11.126 illustrates the creation of an HTMlHeadlElement using the HTMLDocument
object.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1563
// -->
</script>
</html>
HTMLHeadElement.profile
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlHeadElemObj.profile
Description
The profile property of the HTMLHeadElement object represents the URI designating
a metadata profile.
Example
Listing 11.127 illustrates the creation of an HTMLHeadlElement using the
HTMLDocument object element and then setting its profile property.
HTMLHeadingElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents HTML heading elements H1 to H6. The HTMLHeadingElement
object inherits all properties and methods from the HTMLElement object. The property
for this object is as follows:
Item Description
align The horizontal alignment for this heading element
Example
Listing 11.128 illustrates the creation of an HTMLHeadingElement using the
HTMLBodyElement object element and then setting its align property.
HTMLHeadingElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlHeadingingObj.align
Description
The align property of the HTMLHeadingElement object is the horizontal text alignment.
Example
Listing 11.129 illustrates the creation of an HTMLHeadingElement using the
HTMLBodyElement object and then setting its align property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1565
HTMLHRElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML horizontal rule element. The HTMLHRElement inherits
all properties and methods from HTMLElement. Table 11.15 contains a list of properties
for this object.
Example
Listing 11.130 illustrates the creation of an HTMLHRElement using the
HTMLBodyElement object and then setting its align property.
HTMLHRElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlHRObj.align
Description
The align property of the HTMLHRElement object aligns the rule on the page.
Example
Listing 11.131 illustrates the creation of an HTMLHRElement using the
HTMLBodyElement object and then setting its align property.
HTMLHRElement.noShade
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlHRObj.noShade
Description
The noShade property of the HTMLHRElement object indicates to the user agent that
there should be no shading in the rendering of this element.
Example
Listing 11.132 illustrates the creation of an HTMLHRElement using the
HTMLBodyElement object and then setting its noShade property.
// -->
</script>
</html>
HTMLHRElement.size
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlHRObj.size
Description
The size property of the HTMLHRElement object is the height of the rule.
Example
Listing 11.133 illustrates the creation of an HTMLHRElement using the
HTMLBodyElement object and then setting its size property.
HTMLHRElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlHRObj.width
Description
The width property of the HTMLHRElement object is the width of the horizontal rule.
Example
Listing 11.134 illustrates the creation of an HTMLHRElement using the
HTMLBodyElement object element and then setting its width property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1568
HTMLHtmlElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents the root of an HTML document. HTMLHtmlElement inherits all
properties and methods of the HTMLElement object. The property for this object is as
follows:
Item Description
version Version information about this document’s DTD
Example
Listing 11.135 illustrates the creation of an HTMlHtmlElement using the HTMLDocument
object element.
// -->
</script>
</html>
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1569
HTMLHtmlElement.version
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlHtmlElementObj.version
Description
The version property of the HTMLHtmlElement represents version information about
the document’s DTD.
Example
Listing 11.136 illustrates the creation of an HTMlHtmlElement using the HTMLDocument
object element and then setting its version property.
// -->
</script>
</html>
HTMLIFrameElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML internal frame element. The HTMLIFrameElement
object inherits all properties and methods of the HTMLElement object. Table 11.16 con-
tains a list of properties for this object.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1570
Example
Listing 11.137 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement.
// -->
</script>
</html>
HTMLIFrameElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.align
Description
The align property of the HTMLFrameElement object aligns this object (vertically or
horizontally) with respect to its surrounding text.
Example
Listing 11.138 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its align property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1571
HTMLIFrameElement.contentDocument
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.contentDocument
Description
The contentDocument property of the HTMLIFrameElement object represents the doc-
ument this frame contains, if there is one and it is available, or Null otherwise.
Example
Listing 11.139 illustrates reading an HTMLIFrameElement’s contentDocument
property.
HTMLIFrameElement.frameBorder
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.frameBorder
Description
The frameBorder property of the HTMLIFrameElement object requests the frame bor-
ders for this object.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1572
Example
Listing 11.140 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its frameBorder property.
HTMLIFrameElement.height
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.height
Description
The height property of the HTMLIFrameElement object represents the frame height.
Example
Listing 11.141 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its height property.
HTMLIFrameElement.longDesc
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.longDesc
Description
The longDesc property of the HTMLIFrameElement object represents the URI designat-
ing a long description of this image or frame.
Example
Listing 11.142 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its longDesc property.
HTMLIFrameElement.marginHeight
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.marginHeight
Description
The marginHeight property of the HTMLIFrameObject represents the frame margin
height, in pixels.
Example
Listing 11.143 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its marginHeight property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1574
HTMLIFrameElement.marginWidth
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.marginWidth
Description
The marginWidth property of the HTMLIFrameElement represents the frame margin
width, in pixels.
Example
Listing 11.144 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its marginWidth property.
HTMLIFrameElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.name
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1575
Description
The name property of the HTMLIFrameElement object represents the frame name (object
of the target attribute).
Example
Listing 11.145 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its name property.
HTMLIFrameElement.scrolling
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.scrolling
Description
The scrolling property of the HTMLIFrameElement object specifies whether the frame
should have scrollbars.
Example
Listing 11.146 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its scrolling property.
HTMLIFrameElement.src
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.src
Description
The src property of the HTMLIFrameElement object represent a URI designating the
initial frame contents.
Example
Listing 11.147 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its src property.
HTMLIFrameElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIFrameObj.width
Description
The width property of the HTMLIFrameElement object represents the frame width.
Example
Listing 11.148 illustrates the creation of an HTMLIFrameElement using the
HTMLBodyElement object and then setting its width property.
<!--
var iFrameObj = bodyObj.createElement(“iframe”);
iFrameObj.width = 100;
// -->
</script>
</html>
HTMLImageElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML image element. The HTMLImageElement object inher-
its all methods and properties from the HTMLElement object. Table 11.17 contains a list
of properties for this object.
Example
Listing 11.149 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its lowSrc property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1578
HTMLImageElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.align
Description
The align property of the HTMLImageElement object aligns this object (vertically or
horizontally) with respect to its surrounding text.
Example
Listing 11.150 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its align property.
HTMLImageElement.alt
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.alt
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1579
Description
The alt property of the HTMLImageElement object represents alternate text for user
agents not rendering the normal content of this element.
Example
Listing 11.151 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its alt property.
HTMLImageElement.border
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.border
Description
The border property of the HTMLImageElement indicates the width of border around
image.
Example
Listing 11.152 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its border property.
HTMLImageElement.height
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.height
Description
The height property of the HTMLImageElement object overrides the height of the
image.
Example
Listing 11.153 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object element and then setting its height property.
HTMLImageElement.hspace
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.hspace
Description
The hspace property of the HTMLImageElement object indicates the horizontal space to
the left and right of this image.
Example
Listing 11.154 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its hspace property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1581
HTMLImageElement.isMap
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.isMap
Description
The isMap property of the HTMLImageElement object indicates whether or not to use a
server-side image map.
Example
Listing 11.155 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its isMap property.
HTMLImageElement.longDesc
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.longDesc
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1582
Description
The longDesc property of the HTMLImageELement object indicates the URI designating
a long description of this image or frame.
Example
Listing 11.156 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its longDesc property.
HTMLImageElement.lowSrc
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.lowSrc
Description
The lowSrc property of the HTMLImageElement object indicates the URI designating
the source of this image for low-resolution output.
Example
Listing 11.157 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object element and then setting its lowSrc property.
HTMLImageElement.src
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.src
Description
The src property of the HTMLImageElement object indicates the URI designating the
source of this image.
Example
Listing 11.158 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object element and then setting its src property.
HTMLImageElement.useMap
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.useMap
Description
The useMap property of the HTMLImageElement object indicates the name of the client-
side image map to use.
Example
Listing 11.159 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object element and then setting its useMap property.
HTMLImageElement.vspace
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.vspace
Description
The vspace property of the HTMLImageElement object indicates the vertical space
above and below this image.
Example
Listing 11.160 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its vspace property.
HTMLImageElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlImageObj.width
Description
The width property of the HTMLImageElement object overrides width of the image.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1585
Example
Listing 11.161 illustrates the creation of an HTMLImageElement using the
HTMLBodyElement object and then setting its width property.
HTMLInputElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents a form control used for text input.
NOTE
Depending on the environment in which the page is being viewed, the value prop-
erty might be read-only for the file upload input type. For the password input type,
the actual value returned might be masked to prevent unauthorized use.
This object inherits all methods and properties of the HTMLElement object.
Table 11.18 contains a list of properties and methods for this object.
Example
Listing 11.162 illustrates the creation of an HTMLInputElement using the
HTMLFormElement.
HTMLInputElement.accept
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.accept
Description
The accept property of the HTMLInputElement object is a comma-separated list of con-
tent types that a server processing this form will handle correctly.
Example
Listing 11.163 illustrates the accept property of an HTMLInputElement object.
HTMLInputElement.accessKey
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.accessKey
Description
The accessKey property of the HTMLInputElement object is a single character access
key to give access to the form control.
Example
Listing 11.164 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object element and then setting its accessKey property.
HTMLInputElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.align
Description
The align property of the HTMLInputElement object aligns this object (vertically or
horizontally) with respect to its surrounding text.
Example
Listing 11.165 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its align property.
HTMLInputElement.alt
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.alt
Description
The alt property of the HTMLInputElement object is alternate text for user agents not
rendering the normal content of this element.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1589
Example
Listing 11.166 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object element and then setting its alt property.
HTMLInputElement.blur()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.blur()
Description
The blur() method of the HTMLInputElement object removes keyboard focus from this
element.
Example
Listing 11.167 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then the invocation of its blur() method.
HTMLInputElement.checked
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.checked
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1590
Description
The checked property of the HTMLInputElement object is relevant when the type
attribute of the element has the value “Radio” or “Checkbox”, this represents the cur-
rent state of the form control, in an interactive user agent. Changes to this attribute
change the state of the form control, but do not change the value of the HTML value
attribute of the element.
Example
Listing 11.168 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its checked property.
HTMLInputElement.click()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.click()
Description
The click() method of the HTMLInputElement object simulates a mouse click. For
INPUT elements whose type attribute has one of the following values: “Button”,
“Checkbox”, “Radio”, “Reset”, or “Submit”.
Example
Listing 11.169 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then the invocation of its click() method.
HTMLInputElement.defaultChecked
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.defaultChecked
Description
The defaultChecked property of the HTMLInputElement object is relevant when type
has the value “Radio” or “Checkbox”, this represents the HTML checked attribute of
the element. The value of this attribute doesn’t change if the state of the corresponding
form control, in an interactive user agent, changes. Changes to this attribute, however,
resets the state of the form control.
Example
Listing 11.170 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its defaultChecked property.
HTMLInputElement.defaultValue
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.defaultValue
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1592
Description
The defaultValue property of the HTMLInputElement object is relevant when the type
attribute of the element has the value “Text”, “File”, or “Password”, this represents
the HTML value attribute of the element. The value of this attribute doesn’t change if
the contents of the corresponding form control, in an interactive user agent, changes.
Changing this attribute, however, resets the contents of the form control.
Example
Listing 11.171 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its defaultValue property.
HTMLInputElement.disabled
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.disabled
Description
The disabled property of the HTMLInputElement object is used to disable the input
object instance.
Example
Listing 11.172 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its disabled property.
inputObj.disabled = true;
// -->
</html>
HTMLInputElement.focus()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.focus()
Description
The focus() method of the HTMLInputElement object gives keyboard focus to this ele-
ment.
Example
Listing 11.173 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object element and then the invocation of its focus() method.
HTMLInputElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.Form
Description
The form property of the HTMLInputElement object returns the FORM element con-
taining this control. Returns Null if this control isn’t within the context of a form.
Example
Listing 11.174 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then reading its form property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1594
HTMLInputElement.maxLength
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.maxLength
Description
The maxLength property of the HTMLInputElement object is the maximum number of
characters for text fields, when type has the value “Text” or “Password”.
Example
Listing 11.175 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its maxLength property.
HTMLInputElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.name
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1595
Description
The name property of the HTMLInputElement object is the form control or object name
when submitted with a form.
Example
Listing 11.176 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its name property.
HTMLInputElement.readOnly
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.readOnly
Description
The readOnly property of the HTMLInputElement object indicates that this control is
read-only. Relevant only when type has the value “Text” or “Password”.
Example
Listing 11.177 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object element and then setting its readOnly property.
HTMLInputElement.select()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.select()
Description
The select() method of the HTMLInputElement object selects the contents of the text
area. For INPUT elements whose type attribute has one of the following values:
“Text”, “File”, or “Password”.
Example
Listing 11.178 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then the invocation of its select() method.
HTMLInputElement.size
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.size
Description
The size property of the HTMLInputElement object indicates the size information. The
precise meaning is specific to each type of field.
Example
Listing 11.179 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its size property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1597
HTMLInputElement.src
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.src
Description
The src property of the HTMLInputElement object is relevant when the type attribute
has the value “Image”, this attribute specifies the location of the image to be used to
decorate the graphical submit button.
Example
Listing 11.180 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object element and then setting its src property.
HTMLInputElement.tabIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.tabIndex
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1598
Description
The tabInded property of the HTMLInputElement object is the index that represents the
element’s position in the tabbing order.
Example
Listing 11.181 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its tabIndex property.
HTMLInputElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.type
Description
The type property of the HTMLInputElement object is the type of control created.
Example
Listing 11.182 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object element and then setting its type property.
HTMLInputElement.useMap
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.useMap
Description
The useMap property of the HTMLInputElement object indicates the name of the client-
side image map to use.
Example
Listing 11.183 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its useMap property.
HTMLInputElement.value
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlInputObj.value
Description
The value property of the HTMLInputElement object is relevant when the type attribute
of the element has the value “Text”, “File”, or “Password”, this represents the cur-
rent contents of the corresponding form control, in an interactive user agent. Changing
this attribute changes the contents of the form control, but doesn’t change the value of
the HTML value attribute of the element. When the type attribute of the element has
the value “Button”, “Hidden”, “Submit”, “Reset”, “Image”, “Checkbox”, or “Radio”,
this represents the HTML value attribute of the element.
Example
Listing 11.184 illustrates the creation of an HTMLInputElement using the
HTMLFormElement object and then setting its value property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1600
HTMLIsIndexElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This element is used for single-line text input. HTMLIsIndexElement inherits all meth-
ods and properties from HTMLElement. Table 11.19 contains a list of properties for this
object.
Example
Listing 11.185 illustrates the creation of an HTMlIsIndexElement using the
HTMLDocument object.
}
</html>
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1601
HTMLIsIndexElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIsIndexObj.form
Description
The form property of the HTMLIsIndexElement object returns the FORM element con-
taining this control. Returns Null if this control isn’t within the context of a form.
Example
Listing 11.186 illustrates the creation of an HTMLIsIndexElement using the
HTMLFormElement object element and then reading its form property.
HTMLIsIndexElement.prompt
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlIsIndexObj.prompt
Description
The prompt property of the HTMLIsIndexElement object is the prompt message.
Example
Listing 11.187 illustrates the creation of an HTMlIsIndexElement using the
HTMLDocument object element and then setting its prompt properties.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1602
HTMLLabelElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML form field text label. This object inherits all methods
and properties of the HTMLElement object. Table 11.20 contains a list of properties for
this object.
Example
Listing 11.188 illustrates the creation of an HTMLLabelElement using the
HTMLFormElement object.
// -->
</html>
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1603
HTMLLabelElement.accessKey
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLabelObj.accessKey
Description
The accessKey property of the HTMLLabelElement object is a single character access
key to give access to the form control.
Example
Listing 11.189 illustrates the creation of an HTMLLabelElement using the
HTMLBodyElement object and then setting its accessKey property.
HTMLLabelElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLabelObj.form
Description
The form property of the HTMLLabelElement returns the FORM element containing this
control. Returns Null if this control isn’t within the context of a form.
Example
Listing 11.190 illustrates the creation of an HTMLLabelElement using the
HTMLFormElement object and then reading its form property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1604
HTMLLabelElement.htmlFor
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLabelObj.htmlFor
Description
The htmlFor property of the HTMLLabelElement object links this label with another
form control by the id attribute.
Example
Listing 11.191 illustrates the creation of an HTMLLabelElement using the
HTMLFormElement object element and then setting its htmlFor property.
HTMLLegendElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1605
Description
This object represents a caption for a FIELDSET grouping. HTMLLegendElement inher-
its all properties and methods of the HTMLElement object. Table 11.21 contains a list of
properties for this object.
Example
Listing 11.192 illustrates the creation of an HTMLLegendElement using the
HTMLFormElement object.
HTMLLegendElement.accessKey
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLegendObj.accessKey
Description
The accessKey property of the HTMLLegendElement object is a single character access
key to give access to the form control.
Example
Listing 11.193 illustrates the creation of an HTMLLegendElement using the
HTMLFormElement object and then setting its accessKey property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1606
HTMLLegendElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLegendObj.align
Description
The align property of the HTMLLegendElement object is the text alignment relative to
FIELDSET.
Example
Listing 11.194 illustrates the creation of an HTMLLegendElement using the
HTMLFormElement object and then setting its align property.
HTMLLegendElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLegendObj.form
Description
The form property of the HTMLLegendElement object returns the FORM element con-
taining this control. Returns Null if this control isn’t within the context of a form.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1607
Example
Listing 11.195 illustrates the creation of an HTMLLegendElement using the
HTMLFormElement object and then reading its form property.
HTMLLIElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML list item element. HTMLLIElement inherits all proper-
ties and methods of HTMLElement. Table 11.22 contains a list of properties for this
object.
Example
Listing 11.196 illustrates the creation of an HTMLLIElement using the HTMLOLElement
object.
HTMLLIElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLIObj.type
Description
The type property of the HTMLLIElement object is the list item bullet style.
Example
Listing 11.197 illustrates the creation of an HTMLLIElement using the HTMLOLElement
object and then setting its type property.
liObj.type = “item”;
// -->
</script>
</html>
HTMLLIElement.value
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLIObj.value
Description
The value property of the HTMLLIelement object resets the sequence number when
used in OL.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1609
Example
Listing 11.198 illustrates the creation of an HTMLLIElement using the HTMLOLElement
object and then setting its value property.
HTMLLinkElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
The LINK element specifies a link to an external resource, and defines this document’s
relationship to that resource (or vice versa). Table 11.23 contains a list of properties for
this object.
Example
Listing 11.199 illustrates the creation of an HTMLLinkElement using the HTMLDocument
object element and then setting its href property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1610
HTMLLinkElement.charset
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLinkObj.charset
Description
The charset property of the HTMLLinkElement object is the character encoding of the
resource being linked to.
Example
Listing 11.200 illustrates the creation of and displaying the charset property of a
HTMLLinkElement object.
HTMLLinkElement.disabled
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLinkObj.disabled
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1611
Description
The disabled property of the HTMLLinkElement enables/disables the link. This is cur-
rently only used for style sheet links, and can be used to activate or deactivate style
sheets.
Example
Listing 11.201 illustrates the creation of an HTMLLinkElement using the HTMLDocument
object element and then setting its disabled property to true.
HTMLLinkElement.href
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLinkObj.href
Description
The href property of the HTMLLinkElement object is the URI of the linked resource.
Example
Listing 11.202 illustrates the creation of an HTMLLinkElement using the HTMLDocument
object element and then setting its href property.
HTMLLinkElement.hreflang
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLinkObj.hreflang
Description
The hrefLang property of the HTMLLinkElement is the language code of the linked
resource.
Example
Listing 11.203 illustrates the creation of an HTMLLinkElement using the HTMLDocument
object element and then setting its href and hreflang properties.
Listing 11.203 Creating an HTMLLinkElement and Setting Its href and hre-
flang Properties
<html>
<script language=”JavaScript” type=”text/javascript”>
<!--
var htmlDoc = HTMLDOMImplementation.createHTMLDocument(“My HTML Doc”);
htmlDoc.open();
var linkElement = htmlDoc.createElement(“link”);
linkElement.href = “http://foo.bar/ “;
linkElement.hreflang = “us/english”;
}
</script>
</html>
HTMLLinkElement.media
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLinkObj.media
Description
The media property of the HTMLLinkgElement object is designed for use with one or
more target media.
Example
Listing 11.204 illustrates the creation of a HTMLLinkElement and setting its media
property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1613
HTMLLinkElement.rel
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLink.rel
Description
The rel property of the HTMLLinkElement object is the forward link type.
Example
Listing 11.205 illustrates setting the rel property of the HTMLLinkElement object
HTMLLinkElement.rev
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLinkObj.rev
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1614
Description
The rev property of the HTMLLinkElement object is the reverse link type.
Example
Listing 11.206 illustrates setting of the rev property of the HTMLLinkElement object.
HTMLLinkElement.target
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLinkObj.target
Description
The target property of the HTMLLinkElement object is the frame to render the resource
in.
Example
Listing 11.207 illustrates the creation of an HTMLLinkElement using the HTMLDocument
object element and setting its target property.
HTMLLinkElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlLinkObj.type
Description
The type property of the HTMLLinkElement object is the advisory content type.
Example
Listing 11.208 illustrates the creation of an HTMlLinkElement using the HTMLDocument
object element and then setting its type property.
HTMLMapElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML element for a client-side image map. The
HTMLMapElement object inherits all methods and properties of the HTMLElement object.
Table 11.24 contains a list of properties for this object.
Example
Listing 11.209 illustrates the creation of an HTMLMapElement using the
HTMLBodyElement object.
// -->
</html>
HTMLMapElement.areas
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlMapObj.areas
Description
The areas property of the HTMLMapElement object is the list of areas defined for the
image map are contained in an HTMLCollection.
Example
Listing 11.210 illustrates the creation of an HTMLMapElement using the
HTMLBodyElement object and then reading its areas property.
HTMLMapElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlMapObj.name
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1617
Description
The name property of the HTMLMapElement object names the map (for use with
UseMap).
Example
Listing 11.211 illustrates the creation of an HTMLMapElement using the
HTMLBodyElement object and then setting its name property.
HTMLMenuElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML menu element. The property for this object is as fol-
lows:
Item Description
compact Reduces line spacing between list items when true
Example
Listing 11.212 illustrates the creation of an HTMLMenuElement using the
HTMLBodyElement.
// -->
</script>
</html>
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1618
HTMLMenuElement.compact
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlMenuObj.compact
Description
The compact property of the HTMLMenuElement object indicates whether or not to
reduce spacing between list items.
Example
Listing 11.213 illustrates the creation of an HTMLMenuElement using the
HTMLBodyElement object and then setting its compact property.
HTMLMetaElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core object represents DOM HTML object.
Description
This object represents generic meta-information about the document.
HTMLMetaElement inherits all properties and methods from HTMLElement. Table 11.25
contains a list of properties for this object.
Example
Listing 11.214 illustrates the creation of an HTMLMetaElement using the HTMLDocument
object.
HTMLMetaElement.content
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlMetaDataObj.content
Description
The content property of the HTMLMetaDataElement object represents associated infor-
mation contained in the metadata.
Example
Listing 11.215 illustrates the creation of an HTMLMetaElement using the HTMLDocument
object element and then setting its content property.
HTMLMetaElement.httpEquiv
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlMetaDataObj.httpEquiv
Description
The httpEquiv property of the HTMLMetaElement object is the HTTP response header
name.
Example
Listing 11.216 illustrates the creation of an HTMLMetaElement using the HTMLDocument
object element and then setting its httpEquiv property.
HTMLMetaElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlMetaDataObj.name
Description
The name property of the HTMLMetaDataElement object is the meta information name.
Example
Listing 11.217 illustrates the creation of an HTMLMetaElement using the HTMLDocument
object element and then setting its name property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1621
HTMLMetaElement.scheme
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlMetaDataObj.scheme
Description
The scheme property of the HTMLMetaElement object is the select form of content.
Example
Listing 11.218 illustrates the creation of an HTMLMetaElement using the HTMLDocument
object element and then setting its scheme property.
HTMLModElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents a notice of modification to part of a document. The
HTMLModElement object inherits all methods and properties from HTMLElement. Table
11.26 contains a list of properties for this object.
Example
Listing 11.219 illustrates the creation of an HTMLModElement using the
HTMLBodyElement object.
// -->
</script>
</html>
HTMLModElement.cite
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlModObj.cite
Description
The cite property of the HTMLModElement object is a URI designating a document that
describes the reason for the change.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1623
Example
Listing 11.220 illustrates the creation of an HTMLModElement using the
HTMLBodyElement object element and then setting its cite property.
HTMLModElement.dateTime
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlModObj.dateTime
Description
The dateTime property of the HTMLModElement is the date and time of the change.
Example
Listing 11.221 illustrates the creation of an HTMLModElement using the
HTMLBodyElement object and then setting its dateTime property.
HTMLObjectElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML object element. The HTMLObjectElement object inher-
its all methods and properties from the HTMLElement object. Table 11.27 contains a list
of properties for this object.
Example
Listing 11.222 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then reading its form property.
HTMLObjectElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.align
Description
The align property of the HTMLObjectElement object aligns this object (vertically or
horizontally) with respect to its surrounding text.
Example
Listing 11.223 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its align property.
HTMLObjectElement.archive
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.archive
Description
The archive property of the HTMLObjectElement object is the space-separated list of
archives.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1626
Example
Listing 11.224 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its archive property.
HTMLObjectElement.border
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.border
Description
The border property of the HTMLObjectElement object is the width of border around
the object.
Example
Listing 11.225 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its border property.
HTMLObjectElement.code
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.code
Description
The code property of the HTMLObjectElement object is an applet class file. See the
code attribute for HTMLAppletElement.
Example
Listing 11.226 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its code property.
HTMLObjectElement.codeBase
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.codeBase
Description
The codeBase property of the HTMLObjectElement object is the base URI for classid,
data, and archive attributes.
Example
Listing 11.227 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its codeBase property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1628
HTMLObjectElement.codeType
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.codeType
Description
The codeType property of the HTMLObjectElement is the content type for data down-
loaded via classid attribute.
Example
Listing 11.228 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its codeType property.
HTMLObjectElement.contentDocument
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.contentDocument
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1629
Description
The contentDocument property of the HTMLObjectElement is the document this object
contains, if there is any and it is available, or Null otherwise.
Example
Listing 11.229 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then reading its contentDocument property.
HTMLObjectElement.data
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.data
Description
The data property of the HTMLObjectElement object is a URI specifying the location
of the object’s data.
Example
Listing 11.230 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object.
// -->
</script>
</html>
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1630
HTMLObjectElement.declare
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.declare
Description
The declare property of the HTMLObjectElement object declares (for future reference),
but does not instantiate, this object.
Example
Listing 11.231 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its declare property.
HTMLObjectElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.form
Description
The form property of the HTMLObjectElement object returns the FORM element con-
taining this control. Returns Null if this control isn’t within the context of a form.
Example
Listing 11.232 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object element and then reading its form property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1631
HTMLObjectElement.height
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.height
Description
The height property of the HTMLObjectElement object overrides the height.
Example
Listing 11.233 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its height property.
HTMLObjectElement.hspace
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.hspace
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1632
Description
The hspace property of the HTMLObjectElement is the horizontal space to the left and
right of this image, applet, or object.
Example
Listing 11.234 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its hspace property.
HTMLObjectElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.name
Description
The name property of the HTMLObjectElement object is the form control or object name
when submitted with a form.
Example
Listing 11.235 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its name property.
HTMLObjectElement.standby
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.standby
Description
The standby property of the HTMLObjectElement object is the message to render while
loading the object.
Example
Listing 11.236 illustrates the creation of an HTMLObjectElement using the
HTMLBodyelement object and then setting its standby property.
HTMLObjectElement.tabIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.tabIndex
Description
The tabIndex property of the HTMLObjectElement is the index that represents the ele-
ment’s position in the tabbing order.
Example
Listing 11.237 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its tabIndex property.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1634
HTMLObjectElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.type
Description
The type property of the HTMLObjectElement object is the content type for data down-
loaded via data attribute.
Example
Listing 11.238 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its type property.
HTMLObjectElement.useMap
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.useMap
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1635
Description
The useMap property of the HTMLObjectElement object indicates whether or not to use
a client-side image map.
Example
Listing 11.239 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its useMap property.
HTMLObjectElement.vspace
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.vspace
Description
The vspace property of the HTMLObjectElement object is the vertical space above and
below this image, applet, or object.
Example
Listing 11.240 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its vspace property.
HTMLObjectElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlObjectObj.width
Description
The width property of the HTMLObjectElement object overrides the width of the object.
Example
Listing 11.241 illustrates the creation of an HTMLObjectElement using the
HTMLBodyElement object and then setting its width property.
HTMLOListElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML ordered list element. The HTMLOListElement object
inherits all methods and properties of the HTMLElement object. Table 11.28 contains a
list of properties for this object.
Example
Listing 11.242 illustrates the creation of an HTMLOListElement using the
HTMLBodyElement object.
HTMLOListElement.compact
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOListObj.compact
Description
The compact property of the HTMLOListElement object reduces spacing between list
items.
Example
Listing 11.243 illustrates the creation of an HTMLOListElement using the
HTMLBodyElement object and then setting its compact property.
HTMLOListElement.start
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOListObj.start
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1638
Description
The start property of the HTMLOListElement object is the starting sequence number.
Example
Listing 11.244 illustrates the creation of an HTMLOListElement using the
HTMLBodyElement object and then setting its start property.
HTMLOListElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOListObj.type
Description
The type property of the HTMLOListElement object indicates its numbering style.
Example
Listing 11.245 illustrates the creation of an HTMLOListElement using the
HTMLBodyElement object and then setting its type property.
HTMLOptGroupElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
Group options together in logical subdivisions. This object inherits all methods and
properties from HTMLElement. Table 11.29 contains a list of properties for this object.
Example
Listing 11.246 illustrates the creation of an HTMLOptGroupElement using the
HTMLSelectElement object.
HTMLOptGroupElement.disabled
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptGroupObj.disabled
Description
The disabled property of the HTMLOptGroupElement is used to disable the option
group of elements.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1640
Example
Listing 11.247 illustrates the creation of an HTMLOptGroupElement using the
HTMLSelectElement object and then setting its disabled property.
HTMLOptGroupElement.label
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptGroupObj.label
Description
The label property of the HTMLOptGroupElement assigns a label to this option group.
Example
Listing 11.248 illustrates the creation of an HTMLOptGroupElement using the
HTMLSelectElement object and then setting its label property.
optionGrp.label = “Colors”;
// -->
</script>
</html>
HTMLOptionElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML option element that resized in a select element. This
object inherits all methods and properties from HTMLElement. Table 11.30 contains a
list of properties for this object.
Example
Listing 11.249 illustrates the creation of an HTMLOptionElement using the
HTMLOptGroupElement object.
HTMLOptionElement.defaultSelected
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptionObj.defaultSelected
Description
The defaultSelected property of the HTMLOptionElement object represents the value
of the HTML selected attribute. The value of this attribute doesn’t change if the state
of the corresponding form control, in an interactive user agent, changes. Changing
defaultSelected, however, resets the state of the form control.
Example
Listing 11.250 illustrates the creation of an HTMLOptionElement using the
HTMLOptGroupElement object and then setting its defaultSelected property.
HTMLOptionElement.disabled
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptionObj.disabled
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1643
Description
The disabled property of the HTMLOptionElement object is used to disable the option
instance.
Example
Listing 11.251 illustrates the creation of an HTMLOptionElement using the
HTMLSelectElement object and then setting its disabled property.
HTMLOptionElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptionObj.form
Description
The form property of the HTMLOptionElement object returns the FORM element con-
taining this control. Returns Null if this control isn’t within the context of a form.
Example
Listing 11.252 illustrates the creation of an HTMLOptionElement using the
HTMLSelectElement object and then reading its form property.
HTMLOptionElement.index
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptionObj.index
Description
The index property of the HTMLOptionElement object is the index of this option in its
parent SELECT, starting from 0.
Example
Listing 11.253 illustrates the creation of an HTMLOptionElement using the
HTMLSelectElement object and then reading its index property.
HTMLOptionElement.label
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptionObj.label
Description
The label property of the HTMLOptionElement object is the option label for use in hier-
archical menus.
Example
Listing 11.254 illustrates the creation of an HTMLOptionElement using the
HTMLSelectElement object and then setting its label property.
HTMLOptionElement.selected
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptionObj.selected
Description
The selected property of the HTMLOptionElement object represents the current state
of the corresponding form control, in an interactive user agent. Changing this attribute
changes the state of the form control, but does not change the value of the HTML
selected attribute of the element.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1646
Example
Listing 11.255 illustrates the creation of an HTMLOptionElement using the
HTMLSelectElement object and then setting its selected property.
HTMLOptionElement.text
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptionObj.text
Description
The text property of the HTMLOptionElement object is the text contained within the
option element.
Example
Listing 11.256 illustrates the creation of an HTMLOptionElement using the
HTMLSelectElement object and then setting its text property.
HTMLOptionElement.value
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlOptionObj.value
Description
The value property of the HTMLOptionElement object is the current form control value.
Example
Listing 11.257 illustrates the creation of an HTMLOptionElement using the
HTMLSelectElement object and then setting its value property.
HTMLParagraphElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1648
Description
This object represents an HTML paragraph element. The HTMLParagraph element
inherits all methods and properties of the HTMLElement object. The property for this
object is as follows:
Item Description
align The horizontal text alignment for this paragraph element
Example
Listing 11.258 illustrates the creation of an HTMLParagraphElement using the
HTMLBodyElement object and then setting its align property.
HTMLParagraphElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlParagraphObj.align
Description
The align property of the HTMLParagraphElement object is the horizontal text align-
ment.
Example
Listing 11.259 illustrates the creation of an HTMLParagraphElement using the
HTMLBodyElement object and then setting its align property.
// -->
</script>
</html>
HTMLParamElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML parameter element. The HTMLParamElement object
inherits all methods and properties of the HTMLElement object. Table 11.31 contains a
list of properties for this object.
Example
Listing 11.260 illustrates the creation of an HTMLParamElement using the
HTMLMetaElement object.
// -->
</script>
</html>
HTMLParamElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlParamObj.name
23 0672321416 CH11 was 10 7/30/01 1:35 PM Page CD:1650
Description
The name property of the HTMLParamElement object is the name of a runtime parame-
ter.
Example
Listing 11.261 illustrates the creation of an HTMLParamElement using the
HTMLMetaElement object and then setting its name.
// -->
</script>
</html>
HTMLParamElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlParamObj.type
Description
The type property of the HTMLParamElement is the content type for the value attribute
when valuetype has the value “ref”.
Example
Listing 11.262 illustrates the creation of an HTMLParamElement using the
HTMLMetaElement object and then setting its name, value, and type properties.
// -->
</script>
</html>
HTMLParamElement.value
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlParamObj.value
Description
The value property of the HTMLParamElement object is the value of a runtime parame-
ter.
Example
Listing 11.263 illustrates the creation of an HTMLParamElement using the
HTMLMetaElement object and then setting its value property.
paramObj.value = “horses,cows,sheep”;
// -->
</script>
</html>
HTMLParamElement.valueType
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlParamObj.valueType
Description
The valueType property of the HTMLParamElement object is information about the
meaning of the value attribute value.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1652
Example
Listing 11.264 illustrates the creation of an HTMLParamElement using the
HTMLMetaElement object element and then setting its valueType and name properties.
HTMLPreElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML pre-formatted text element. The HTMLPreElement
inherits all properties and methods of HTMLElement. The property for this object is as
follows:
Item Description
width The fixed width for the contents of the PRE element
Example
Listing 11.265 illustrates the creation of an HTMLPreElement using the
HTMLBodyElement object.
// -->
</script>
</html>
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1653
HTMLPreElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlPreObj.width
Description
The width property of the HTMLPreElement object is the fixed width for content.
Example
Listing 11.266 illustrates the creation of an HTMLPreElement using the
HTMLBodyElement object and then setting its width property.
HTMLQuoteElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents both HTML Q and BLOCKQUOTE elements. The
HTMLQuoteElement inherits all properties and methods from HTMLElement. The prop-
erty for this object is as follows:
Item Description
cite URI designating source message
Example
Listing 11.267 illustrates the creation of an HTMLQuoteElement using the
HTMLBodyElement object.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1654
// -->
</script>
</html>
HTMLQuoteElement.cite
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlQuoteObj.cite
Description
The cite property of the HTMLQuoteElement object is a URI designating a source doc-
ument or message.
Example
Listing 11.268 illustrates the creation of an HTMLQuoteElement using the
HTMLBodyElement object and then setting its cite property.
HTMLScriptElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1655
Description
This object represents an HTML script element. HTMLScriptElement inherits all prop-
erties and methods from the HTMLElement object. Table 11.32 contains a list of proper-
ties for this object.
Example
Listing 11.269 illustrates the creation of an HTMLScriptElement using the
HTMLBodyElement object and then setting its text property.
// -->
</script>
</html>
HTMLScriptElement.charset
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlScriptObj.charset
Description
The charset property of the HTMLScriptElement object is the character encoding of
the linked resource.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1656
Example
Listing 11.270 illustrates the creation of an HTMLScriptElement using the
HTMLBodyElement object and then setting its charset property.
// -->
</script>
</html>
HTMLScriptElement.defer
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlScriptObj.defer
Description
The defer property of the HTMLScriptElement object indicates that the user agent can
defer processing of the script.
Example
Listing 11.271 illustrates the creation of an HTMLScriptElement using the
HTMLBodyElement object and then setting its defer property.
HTMLScriptElement.event
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
htmlScript.event
Description
The event property of the HTMLScriptElement object is reserved for future use.
HTMLScriptElement.htmlFor
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlScriptObj.htmlFor
Description
The htmlFor property of the HTMLScriptElement object is reserved for future use.
HTMLScriptElement.src
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlScriptObj.src
Description
The src property of the HTMLScriptElement object is a URI designating an external
script.
Example
Listing 11.272 illustrates the creation of an HTMLScriptElement using the
HTMLBodyElement object.
// -->
</script>
</html>
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1658
HTMLScriptElement.text
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlScriptObj.text
Description
The text property of the HTMLScriptElement object is the script content of the ele-
ment.
Example
Listing 11.273 illustrates the creation of an HTMLScriptElement using the
HTMLBodyElement object element and then setting its text property.
// -->
</script>
</html>
HTMLScriptElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlScriptObj.type
Description
The type property of the HTMLScriptElement is the content type of the script language.
Example
Listing 11.274 illustrates the creation of an HTMLScriptElement using the
HTMLBodyElement object and then setting its type property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1659
// -->
</script>
</html>
HTMLSelectElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
The select element allows the selection of an option. The contained options can be
directly accessed through the select element as a collection. This object inherits all
methods and properties from HTMLElement. Table 11.33 contains a list of properties and
methods for this object.
Example
Listing 11.275 illustrates the creation of an HTMLSelectElement using the
HTMLFormElement object.
HTMLSelectElement.add()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.add(element, before)
Description
The add() method of the HTMLSelectElement object adds a new element to the col-
lection of OPTION elements for this SELECT. This method is equivalent to the
AppendChild() method of the Node object if the before parameter is Null. It is equiv-
alent to the InsertBefore() method on the parent of before in all other cases.
Example
Listing 11.276 illustrates the creation of a HTMLSelectElement and invoking its add()
method.
// -->
<script>
</html>
HTMLSelectElement.blur()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.blur()
Description
The blur() method of the HTMLSelectElement object removes keyboard focus from
this element.
Example
Listing 11.277 illustrates the creation of a HTMLSelectElement and invoking its blur()
method.
HTMLSelectElement.disabled
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.disabled
Description
The disabled property of the HTMLSelectElement object is used to disable the select
element instance.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1662
Example
Listing 11.278 illustrates the creation of an HTMLSelectElement using an
HTMLFormElement object and setting its disabled property.
HTMLSelectElement.focus()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.focus()
Description
The focus() method of the HTMLSelectElement object gives keyboard focus to this
element.
Example
Listing 11.279 illustrates the creation of a HTMLSelectElement and invoking its
focus() method.
HTMLSelectElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.form
Description
The form property of the HTMLSelectElement object returns the FORM element con-
taining this control. Returns Null if this control isn’t within the context of a form.
Example
Listing 11.280 illustrates the reading an HTMLSelectElement’s form property.
HTMLSelectElement.length
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.length
Description
The length property of the HTMLSelectElement object is the number of options in this
SELECT.
Example
Listing 11.281 illustrates the creation of a HTMLSelectObject and reading its length
property.
HTMLSelectElement.multiple
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.multiple
Description
The multiple property of the HTMLSelectElement object indicates whether or not mul-
tiple OPTION elements can be selected in this SELECT.
Example
Listing 11.282 illustrates the creation of a HTMLSelectElement and setting its multi-
ple property.
HTMLSelectElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.name
Description
The name property of the HTMLSelectElement object is the form control or object name
when submitted with a form.
Example
Listing 11.283 illustrates the creation of a HTMLSelectElement and setting its name
property.
HTMLSelectElement.options
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.options
Description
The options property of the HTMLSelectElement object is the collection of OPTION ele-
ments contained by this element.
Example
Listing 11.284 illustrates the creation of a HTMLSelectElement and iterating through its
options property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1666
HTMLSelectElement.remove()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.remove(index)
Description
The remove() method of the HTMLSelectElement object removes an element from the
collection of OPTION elements for this SELECT. Does nothing if no element has the given
index.
Example
Listing 11.285 illustrates the creation of a HTMLSelectElement and invoking its
remove() method.
// -->
</script>
</html>
HTMLSelectElement.selectedIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.selectedIndex
Description
The selectedIndex property of the HTMLSelectElement object is the ordinal index of
the selected option, starting from 0. The value -1 is returned if no element is selected.
If multiple options are selected, the index of the first selected option is returned.
Example
Listing 11.286 illustrates the creation of an HTMLSelectElement using the
HTMLFormElement object and then setting its selectedIndex property.
HTMLSelectElement.size
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.size
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1668
Description
The size property of the HTMLSelectElement object is the number of visible rows.
Example
Listing 11.287 illustrates the creation of an HTMLSelectElement and setting its size
property.
HTMLSelectElement.tabIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.tabIndex
Description
The tabIndex property of the HTMLSelectElement is the index that represents the ele-
ment’s position in the tabbing order.
Example
Listing 11.288 illustrates the creation of an HTMLSelectElement and setting its
tabIndex property.
HTMLSelectElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.type
Description
The type property of the HTMLSelectElement object is the type of this form control.
This is the string “select-multiple” when the multiple attribute is True and the string
“select-one” when False.
Example
Listing 11.289 illustrates the creation of an HTMLSelectElement using the
HTMLFormElement object and then setting its type property.
HTMLSelectElement.value
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlSelectObj.value
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1670
Description
The value property of the HTMLSelectElement object is the current form control value.
Example
Listing 11.290 illustrates the creation of an HTMLSelectElement using the
HTMLFormElement object and then setting its value property.
HTMLStyleElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
Represents style information contained in a style sheet. HTMLStyleElement inherits all
methods and properties from HTMLElement. Table 11.34 contains a list of properties for
this object.
Example
Listing 11.291 illustrates the creation of an HTMLStyleElement using the
HTMLDocument.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1671
// -->
</script>
</html>
HTMLStyleElement.disabled
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
styleInfoObj.disabled
Description
The disabled property of the HTMLStyleElement enables/disables the style sheet.
Example
Listing 11.292 illustrates the creation of an HTMLStyleObject using the HTMLDocument
object element and then disabling it.
HTMLStyleElement.media
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
styleInfoObj.media
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1672
Description
The media property of the HTMLStyleElement object is designed for use with one or
more target media.
Example
Listing 11.293 illustrates the creation of an HTMLStyleObject using the HTMLDocument
object element and then setting its media property.
HTMLStyleElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
styleInfoObj.type
Description
The type property of the HTMLStyleElement object is the content type of the style sheet
language.
Example
Listing 11.294 illustrates the creation of an HTMLStyleObject using the HTMLDocument
object element and then setting its type property.
// -->
</script>
</html>
HTMLTableCaptionElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML table caption element. HTMLTableCaptionElement
inherits all properties and methods from HTMLElement. The property for this object is
as follows:
Item Description
align Aligns caption with respect to the table it resides in
Example
Listing 11.295 illustrates the creation of an HTMLTableCaptionElement using the
HTMLTableElement object.
// -->
</script>
</html>
HTMLTableCaptionElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCaptionObj.align
Description
The align property of the HTMLTableCaptionElement is the caption alignment with
respect to the table.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1674
Example
Listing 11.296 illustrates the creation of an HTMLTableCaptionElement using the
HTMLTableElement object and then setting its align property.
HTMLTableCellElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object is used to represent the TH and TD elements. The HTMLTableCellElement
object inherits all methods and properties from the HTMLElement object. Table 11.35
contains a list of properties for this object.
Example
Listing 11.297 illustrates the creation of an HTMLTableCellElement using the
insertRow() method of the HTMLTableRowElement object.
HTMLTableCellElement.abbr
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.abbr
Description
The abbr property of the HTMLTableCellElement object is an abbreviation for header
cells.
Example
Listing 11.298 illustrates the creation of an HTMLTableCellElement using the
HTMLTableRowElement object and then setting its abbr property.
HTMLTableCellElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.align
Description
The align property of the HTMLTableCellElement object is the horizontal alignment
of data in cell.
Example
Listing 11.299 illustrates the creation of an HTMLTableCellElement using the
HTMLTableRow object and then setting its align property.
HTMLTableCellElement.axis
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.axis
Description
The axis property of the HTMLTableCellElement object names group of related head-
ers.
Example
Listing 11.300 illustrates the creation of an HTMLTableCellElement and then setting its
axis property.
<!--
cellObj.axis = “Colors”;
// -->
</script>
</html>
HTMLTableCellElement.bgColor
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.bgColor
Description
The bgColor property of the HTMLTableCellElement object is the cell background
color.
Example
Listing 11.301 illustrates the creation of an HTMLTableCellElement and then setting its
bgColor property.
HTMLTableCellElement.cellIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.cellIndex
Description
The cellIndex property of the HTMLTableCellElement object is the index of this cell
in the row, starting from 0. This index is in document tree order and not display order.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1678
Example
Listing 11.302 illustrates the creation of an HTMLTableCellElement and then reading
its cellIndex property.
HTMLTableCellElement.ch
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.ch
Description
The ch property of the HTMLTableCellElement object is the alignment character for
cells in a column.
Example
Listing 11.303 illustrates the creation of an HTMLTableCellElement and then setting its
ch property.
HTMLTableCellElement.chOff
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.chOff
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1679
Description
The chOff property of the HTMLTableCellElement object is the offset of alignment
character.
Example
Listing 11.304 illustrates the creation of an HTMLTableCellElement and then setting its
chOff property.
HTMLTableCellElement.colSpan
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.colSpan
Description
The colSpan property of the HTMLTableCellElement object is the number of columns
spanned by cell.
Example
Listing 11.305 illustrates the creation of an HTMLTableCellElement and then setting its
colSpan property.
HTMLTableCellElement.headers
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.headers
Description
The headers property of the HTMLTableCellElement object is a list of id attribute val-
ues for header cells.
Example
Listing 11.306 illustrates the creation of an HTMLTableCellElement and then setting its
headers property.
HTMLTableCellElement.height
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.height
Description
The height property of the HTMLTableCellElement object is the cell height.
Example
Listing 11.307 illustrates the creation of an HTMLTableCellElement and then setting its
height property.
cellObj.height = 25;
// -->
</script>
</html>
HTMLTableCellElement.noWrap
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.noWrap
Description
The noWrap property of the HTMLTableCellElement object Suppresses word wrapping
when true.
Example
Listing 11.308 illustrates the creation of an HTMLTableCellElement and then setting its
noWrap property.
HTMLTableCellElement.rowSpan
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.rowSpan
Description
The rowSpan property of the HTMLTableCellElement object is the number of rows
spanned by cell.
Example
Listing 11.309 illustrates the creation of an HTMLTableCellElement and then setting its
rowSpan property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1682
HTMLTableCellElement.scope
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.scope
Description
The scope property of the HTMLTableCellElement object is the scope covered by
header cells.
Example
Listing 11.310 illustrates the creation of an HTMLTableCellElement and then setting its
scope property.
HTMLTableCellElement.vAlign
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.vAlign
Description
the vAlign property of the HTMLTableCellElement object is the vertical alignment of
data in cell.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1683
Example
Listing 11.311 illustrates the creation of an HTMLTableCellElement and then setting its
vAlign property.
HTMLTableCellElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableCellObj.width
Description
The width property of the HTMLTableCellElement object is the cell width.
Example
Listing 11.312 illustrates the creation of an HTMLTableCellElement and then setting its
width property.
HTMLTableColElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1684
Description
This object represents both the HTML COL and COLGROUP elements.
HTMLTableColElement object inherits all properties and methods from HTMLElement.
Table 11.36 contains a list of properties for this object.
Example
Listing 11.313 illustrates the creation of an HTMLTableColElement using the
HTMLTableRowElement object.
// -->
</script>
</html>
HTMLTableColElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableColObj.align
Description
The The align property of the HTMLTableColElement object is the horizontal align-
ment of cell data in column.
Example
Listing 11.314 illustrates the creation of an HTMLTableColElement using the
HTMLTableRowElement object and then setting its align property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1685
HTMLTableColElement.ch
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableColObject.ch
Description
The ch property of the HTMLTableColElement object is the alignment character for
cells in a column.
Example
Listing 11.315 illustrates the creation of an HTMLTableColElement using the
HTMLTableRowElement object and then setting its ch property.
HTMLTableColElement.chOff
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableColObject.chOff
Description
The chOff property of the HTMLTableColElement object is the offset of alignment char-
acter.
Example
Listing 11.316 illustrates the creation of an HTMLTableColElement using the
HTMLTableRowElement object element and then setting its chOff property.
HTMLTableColElement.span
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableColObj.span
Description
The span property of the HTMLTableColElement object indicates the number of
columns in a group or affected by a grouping.
Example
Listing 11.317 illustrates the creation of an HTMLTableColElement using the
HTMLTableRowElement object and then setting its span property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1687
HTMLTableColElement.vAlign
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableColObj.vAlign
Description
The vAlign property of the HTMLTableColElement object is the vertical alignment of
cell data in column.
Example
Listing 11.318 illustrates the creation of an HTMLTableColElement using the
HTMLTableRowElement object and then setting its vAlign property.
HTMLTableColElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableColObj.width
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1688
Description
The width property of the HTMLTableColElement object is the default column width.
Example
Listing 11.319 illustrates the creation of an HTMLTableColElement using the
HTMLTableRowElement object element and then setting its width property.
HTMLTableElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML table element. HTMLTableElement inherits all proper-
ties and methods from the HTMLElement object. Table 11.37 contains a list of proper-
ties and methods for this object.
Example
Listing 11.320 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its caption property.
HTMLTableElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.align
Description
The align property of the HTMLTableElement object specifies the table’s position with
respect to the rest of the document.
Example
Listing 11.321 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its align property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1690
HTMLTableElement.bgColor
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.bgColor
Description
The bgColor property of the HTMLTableElement object is the cell background color.
Example
Listing 11.322 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its bgColor property.
HTMLTableElement.border
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.border
Description
The border property of the HTMLTableElement object is the width of the border around
the table.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1691
Example
Listing 11.323 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its border property.
HTMLTableElement.caption
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.caption
Description
The caption property of the HTMLTableElement object returns the table’s CAPTION, or
void if none exists.
Example
Listing 11.324 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its caption property.
HTMLTableElement.cellPadding
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.cellPadding
Description
The cellPadding property of the HTMLTableElement object specifies the horizontal
and vertical space between cell content and cell borders.
Example
Listing 11.325 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its cellPadding property.
HTMLTableElement.cellSpacing
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.cellSpacing
Description
The cellSpacing property of the HTMLTableElement object specifies the horizontal
and vertical separation between cells.
Example
Listing 11.326 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its cellSpacing property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1693
HTMLTableElement.createCaption()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.createCaption()
Description
The createCaption() method of the HTMLTableElement object creates a new table
caption object or return an existing one.
Example
Listing 11.327 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then the invocation of its creatCaption()method.
HTMLTableElement.createTFoot()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.createTFoot()
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1694
Description
The createTFoot() method of the HTMLTableElement object creates a table footer row
or return an existing one.
Example
Listing 11.328 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object element and then the invocation of its createTFoot()
method.
HTMLTableElement.createTHead()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.createTHead()
Description
The createTHead() method of the HTMLTableElement object
Example
Listing 11.329 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then the invocation of its createTHead() method.
HTMLTableElement.deleteCaption()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.deleteCaption()
Description
The deleteCaption() method of the HTMLTableElement object deletes the table cap-
tion, if one exists.
Example
Listing 11.330 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then the invocation of its deleteCaption() method.
HTMLTableElement.deleteRow()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.deleteRow(index)
Description
The deleteRow() method of the HTMLTableElement object deletes the index table row.
Example
Listing 11.331 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then the invocation of its deleteRow() method.
HTMLTableElement.deleteTFoot()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.deleteTFoot()
Description
The deleteTFoot() method of the HTMLTableElement object deletes the footer from
the table, if one exists.
Example
Listing 11.332 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then the invocation of its deleteTFoot() method.
HTMLTableElement.deleteTHead()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.deleteTHead()
Description
The deleteTHead() method of the HTMLTableElement object deletes the header from
the table, if one exists.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1697
Example
Listing 11.333 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then the invocation of its deleteTHead() method.
HTMLTableElement.frame
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.frame
Description
The frame property of the HTMLTableElement object specifies which external table
borders to render.
Example
Listing 11.334 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its frame property.
HTMLTableElement.insertRow()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.insertRow(index)
Description
The insertRow() method of the HTMLTableElement object inserts a new empty row in
the table. The new row is inserted immediately before and in the same section as the
current index row in the table. If index is equal to the number of rows, the new row is
appended. In addition, when the table is empty, the row is inserted into a TBODY that is
created and inserted into the table.
Example
Listing 11.335 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then the invocation of its insertRow() method.
HTMLTableElement.rows
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObject.rows
Description
The rows property of the HTMLTableElement object returns a collection of all the rows
in the table, including all in THEAD, TFOOT, and TBODY elements.
Example
Listing 11.336 illustrates the creation of an HTMLTableElement and then reading its
rows property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1699
HTMLTableElement.rules
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.rules
Description
The rules property of the HTMLTableElement object specifies which internal table bor-
ders to render.
Example
Listing 11.337 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its rules property.
HTMLTableElement.summary
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.summary
Description
The summary property of the HTMLTableElement object is a description about the pur-
pose or structure of a table.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1700
Example
Listing 11.338 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its summary property.
HTMLTableElement.tBodies
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.tBodies
Description
The tBodies property of the HTMLTableElement object returns a collection of the
defined table bodies.
Example
Listing 11.339 illustrates the creation of an HTMLTableElement and then reading its
tBodies property.
HTMLTableElement.tFoot
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.tFoot
Description
The tFoot property of the HTMLTableElement object returns the table’s TFOOT, or Null
if none exists.
Example
Listing 11.340 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then reading its tFoot property.
HTMLTableElement.tHead
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.tHead
Description
The tHead property of the HTMLTableElement object returns the table’s THEAD, or Null
if none exists.
Example
Listing 11.341 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then reading its tHead property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1702
HTMLTableElement.width
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableObj.width
Description
The width property of the HTMLTableElement object specifies the desired table width.
Example
Listing 11.342 illustrates the creation of an HTMLTableElement using the
HTMLBodyElement object and then setting its width property.
HTMLTableRowElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1703
Description
This object represents a row in an HTML table element. HTMLTableRowElement inher-
its all methods and properties from HTMLElement. Table 11.38 contains a list of prop-
erties and methods for this object.
Example
Listing 11.343 illustrates the creation of an HTMLTableRowElement using the
HTMLTableElement object’s insertRow() method.
HTMLTableRowElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.align
Description
The align property of the HTMLTableRowElement object is the horizontal alignment of
data within cells of this row.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1704
Example
Listing 11.344 illustrates the creation of an HTMLTableRowElement using the
HTMLTableElement object and then setting its align property.
HTMLTableRowElement.bgColor
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.bgColor
Description
The bgColor property of the HTMLTableRowElement object is the background color for
rows.
Example
Listing 11.345 illustrates the creation of an HTMLTableRowElement using the
HTMLTableElement object and then setting its bgColor property.
HTMLTableRowElement.cells
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.cells
Description
The cells property of the HTMLTableRowElement object is the collection of cells in this
row.
Example
Listing 11.346 illustrates the creation of an HTMLTableRowElement and then reading its
cells property.
HTMLTableRowElement.ch
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.ch
Description
The ch property of the HTMLTableRowElement object is the alignment character for
cells in a column.
Example
Listing 11.347 illustrates the creation of an HTMLTableRowElement using the
HTMLTableElement object and then setting its ch property.
HTMLTableRowElement.chOff
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.chOff
Description
The chOff property of the HTMLTableRowElement object is the offset of alignment char-
acter.
Example
Listing 11.348 illustrates the creation of an HTMLTableRowElement using the
HTMLTableElement object and then setting its chOff property.
HTMLTableRowElement.deleteCell()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.deleteCell(index)
Description
The deleteCell() method of the HTMLTableRowElement object deletes a cell from the
current row.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1707
Example
Listing 11.349 illustrates the creation of an HTMLTableRowElement and then invokes its
deleteCell() method.
HTMLTableRowElement.insertCell()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.insertCell(index)
Description
The insertCell() method of the HTMLTableRowElement object inserted an empty TD
cell into this row. If index is equal to the number of cells, the new cell is appended.
Example
Listing 11.350 illustrates the creation of an HTMLTableRowElement using the
HTMLTableElement object and then the invocation of its insertCell() method.
HTMLTableRowElement.rowIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.rowIndex
Description
The rowIndex property of the HTMLTableRowElement object is the index of this row,
relative to the entire table, starting from 0. This is in document tree order and not dis-
play order. The rowIndex does not take into account sections (THEAD, TFOOT, or TBODY)
within the table.
Example
Listing 11.351 illustrates the creation of an HTMLTableRowElement using the
HTMLTableElement object element and then reading its rowIndex property.
HTMLTableRowElement.sectionRowIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.sectionRowIndex
Description
The sectionRowIndex property of the HTMLTableRowElement object is the index of this
row, relative to the current section (THEAD, TFOOT, or TBODY), starting from 0.
Example
Listing 11.352 illustrates the creation of an HTMLTableRowElement and then reading its
sectionRowIndex property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1709
HTMLTableRowElement.vAlign
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableRowObj.vAlign
Description
The vAlign property of the HTMLTableRowElement object is the vertical alignment of
data within cells of this row.
Example
Listing 11.353 illustrates the creation of an HTMLTableRowElement using the
HTMLTableElement object and then setting its vAlign property.
HTMLTableSectionElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1710
Description
This object represents the HTML elements THEAD, TFOOT, and TBODY. The
HTMLTableSectionElement object inherits all methods and properties from
HTMLElement. Table 11.39 contains a list of properties and methods for this object.
Example
Listing 11.354 illustrates the creation of an HTMLTableSectionElement and then set-
ting its align property.
HTMLTableSectionElement.align
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableSectionObj.align
Description
The align property of the HTMLTableSectionElement object is the horizontal align-
ment of data in cells.
Example
Listing 11.355 illustrates the creation of an HTMLTableSectionElement object and then
setting its align property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1711
HTMLTableSectionElement.ch
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableSection.ch
Description
The ch property of the HTMLTableSectionElement object is the alignment character for
cells in a column.
Example
Listing 11.356 illustrates the creation of an HTMLTableSectionElement and then
setting its ch property.
HTMLTableSectionElement.chOff
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableSectionObj.chOff
Description
The chOff property of the HTMLTableSectionElement object is the offset of alignment
character.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1712
Example
Listing 11.357 illustrates the creation of an HTMLTableSectionElement object and then
setting its chOff property.
HTMLTableSectionElement.deleteRow()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableSectionObj.deleteRow(index)
Description
The deleteRow() method of the HTMLTableSectionElement deletes a row from this
section.
Example
Listing 11.358 illustrates the creation of an HTMLTableSectionElement object and then
invoking its deleteRow() method.
HTMLTableSectionElement.insertRow()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableSectionObj.insertRow(index)
Description
The insertRow() of the HTMLTableSectionElement object inserts a row into this sec-
tion. The new row is inserted immediately before the current index row in this section.
If index is equal to the number of rows in this section, the new row is appended.
Example
Listing 11.359 illustrates the creation of an HTMLTableSectionElement and then the
invocation of its insertRow() method.
HTMLTableSectionElement.rows
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableSectionObj.rows
Description
The rows property of the HTMLTableSectionElement object is the collection of rows in
this table section.
Example
Listing 11.360 illustrates the creation of an HTMLTableSectionElement and then read-
ing its rows property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1714
HTMLTableSectionElement.vAlign
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTableSectionObj.vAlign
Description
The vAlign property of the HTMLTableSectionElement object is the vertical alignment
of data in cells.
Example
Listing 11.361 illustrates the creation of an HTMLTableSectionElement and then set-
ting its vAlign property.
HTMLTextAreaElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1715
Example
Listing 11.362 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object.
HTMLTextAreaElement.accessKey
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.accessKey
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1716
Description
The accessKey property of the HTMLTextAreaElement object is a single character
access key to give access to the form control.
Example
Listing 11.363 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object element and then setting its accessKey property.
HTMLTextAreaElement.blur()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.blur()
Description
The blur() method of the HTMLTextAreaElement object removes keyboard focus from
this element.
Example
Listing 11.364 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object element and then the invocation of its blur() method.
HTMLTextAreaElement.cols
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextArea.cols
Description
The cols property of the HTMLTextAreaElement object is the width of control (in char-
acters).
Example
Listing 11.365 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then setting its cols property.
HTMLTextAreaElement.defaultValue
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.defaultValue
Description
The defaultValue of the HTMLTextAreaElement object represents the contents of the
element. The value of this attribute doesn’t change if the contents of the corresponding
form control, in an interactive user agent, changes. Changing this attribute, however,
resets the contents of the form control.
Example
Listing 11.366 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then setting its defaultValue property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1718
HTMLTextAreaElement.disabled
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.disabled
Description
The disabled property of the HTMLTextAreaElement object is used to disable the
textarea instance.
Example
Listing 11.367 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then setting its disabled property.
HTMLTextAreaElement.focus()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.focus()
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1719
Description
The focus() method of the HTMLTextAreaElement object gives keyboard focus to this
element.
Example
Listing 11.368 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then the invocation of its focus()method.
HTMLTextAreaElement.form
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.form
Description
The form property of the HTMLTextAreaElement object returns the FORM element con-
taining this control. Returns Null if this control isn’t within the context of a form.
Example
Listing 11.369 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then reading its form property.
HTMLTextAreaElement.name
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.name
Description
The name property of the HTMLTextAreaElement object is the form control or object
name when submitted with a form.
Example
Listing 11.370 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then setting its name property.
HTMLTextAreaElement.readOnly
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.readOnly
Description
The readOnly property of the HTMLTextAreaElement object indicates whether or not
this control is read-only.
Example
Listing 11.371 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object element and then setting its readOnly property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1721
HTMLTextAreaElement.rows
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.rows
Description
The rows property of the HTMLTextAreaElement object is the number of text rows in
the text area.
Example
Listing 11.372 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then setting its rows property.
HTMLTextAreaElement.select()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.select()
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1722
Description
The select() method of the HTMLTextAreaElement object selects the contents of the
TEXTAREA.
Example
Listing 11.373 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then the invocation of its select() method.
HTMLTextAreaElement.tabIndex
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.tabIndex
Description
The tabIndex property of the HTMLTextAreaElement object is the index that represents
the element’s position in the tabbing order.
Example
Listing 11.374 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then setting its tabIndex property.
HTMLTextAreaElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.type
Description
The type property of the HTMLTextAreaElement object is the type of this form control.
This is the string “textarea”.
Example
Listing 11.375 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then reading its type property.
HTMLTextAreaElement.value
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTextAreaObj.value
Description
The value property of the HTMLTextAreaElement object represents the current contents
of the corresponding form control, in an interactive user agent. Changing this attribute
changes the contents of the form control, but doesn’t change the contents of the ele-
ment. If the entirety of the data cannot fit into a single string, the implementation might
truncate the data.
Example
Listing 11.376 illustrates the creation of an HTMLTextAreaElement using the
HTMLFormElement object and then setting its value property.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1724
HTMLTitleElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents the document title. HTMLTitleElement inherits all properties and
methods from HTMLElement. The property for this object is as follows:
Item Description
text The specified title as a string
Example
Listing 11.377 illustrates the creation of an HTMLTitleElement using the
HTMLHeadElement object element.
// -->
</script>
</html>
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1725
HTMLTitleElement.text
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlTitleObj.text
Description
The title property of the HTMLTitleElement object represents the specified title of an
HTML document.
Example
Listing 11.378 illustrates the creation of an HTMlTitleElement using the
HTMLHeadElement object element and then setting its text property.
HTMLUListElement
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Core DOM HTML object.
Description
This object represents an HTML unordered list element. HTMLUListElement inherits all
properties and method of HTMLElement. Table 11.41 contains a list of properties for this
object.
23 0672321416 CH11 was 10 7/30/01 1:36 PM Page CD:1726
Example
Listing 11.379 illustrates the creation of an HTMLUListElement using the
HTMLBodyElement.
HTMLUListElement.compact
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlUListObj.compact
Description
The compact property of the HTMLUListElement object reduces spacing between list
items.
Example
Listing 11.380 illustrates the creation of an HTMLUListElement using the
HTMLBodyElement object and then setting its compact property.
HTMLUListElement.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
htmlUListObj.type
Description
The type property of the HTMLUListElement object is the bullet style of the element.
Example
Listing 11.381 illustrates the creation of an HTMLUListElement using the
HTMLBodyElement object and then setting its type property.
DOM Events
CHAPTER 12
DOM Events
The DOM Level 2 Event Model was designed with two main
goals. The first goal was to offer a generic model that would
allow the registration of event handlers, flow for events to fol-
low, and basic contextual information regarding the event. The
second goal was to provide backward compatibility with the
event models of DOM Level 0 and Level 1.
DocumentEvent
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Event object.
Description
The DocumentEvent object provides a mechanism by which
the user can create an Event of a type supported by the imple-
mentation. It is expected that the DocumentEvent interface will
be implemented on the same object which implements the
Document interface in an implementation that supports the
Event model. Contents of the EventException object are as
follows:
Type Item Description
Method createEvent() Creates a new event.
Example
Listing 12.1 shows the creation of a mouse event object using
the createEvent() of the DocumentEvent object. The event is
then initialized using the initEvent() method.
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1732
DocumentEvent.createEvent()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DocumentEvent.createEvent(eventType)
Description
The createEvent() method of the DocumentEvent object creates a new event of the
specified eventType.
Example
Listing 12.2 shows the creation of a mouse event object using the CreateEvent() of
the DocumentEvent object. The event is then initialized using the initEvent() method.
Event
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Event object.
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1733
Description
The Event interface is used to provide contextual information about an event to the
handler processing the event. An object that implements the Event interface is gener-
ally passed as the first parameter to an event handler. More specific context informa-
tion is passed to event handlers by deriving additional interfaces from Event, which
contain information directly relating to the type of event they accompany. The object
passed to the event listener also implements these derived interfaces.
An Event is created by using the createEvent() method of the DocumentEvent object.
Table 12.1 lists all constants, methods and properties of the Event object.
Example
Listing 12.3 illustrates the creation of an event using the createEvent() method of the
DocumentEvent object.
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1734
Event.type
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.type
Description
The type property of the Event object identifies the name of the event.
Example
Listing 12.4 illustrates the creation of an EventListener function and checks the type
property of an Event to see how it should be handled.
Event.bubbles
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1735
Syntax
eventObj.bubbles
Description
The bubbles property of the Event object is of type boolean and indicates whether this
event can bubble.
Example
Listing 12.5 illustrates the creation of an EventListener function and checks the
bubbles property of the evt parameter to determine whether the event bubbles.
Event.cancelable
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.cancelable
Description
Used to indicate whether an event can have its default action prevented. If the default
action can be prevented, the value is true; otherwise the value is false.
Example
Listing 12.6 illustrates the creation of an EventListener function and checks the
cancelable property of the evt parameter to determine whether the event’s default
action can be canceled.
Event.currentTarget
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.currentTarget
Description
The target property of an Event object indicates the EventTarget object to which this
event is currently being dispatched.
Example
Listing 12.7 illustrates the creation of an EventListener function and checks the
currentTarget property of the Event object to see how the event should be handled.
Event.eventPhase
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.eventPhase
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1737
Description
Indicates which phase of the event flow is being evaluated: Event.CAPTURING_PHASE,
Event.AT_TARGET, or Event.BUBBLING_PHASE.
Example
Listing 12.8 illustrates the creation of an EventListener function and checks the
eventPhase property of the evt parameter to determine at what phase the event is in.
Event.initEvent()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.initEvent(eventType, canBubble, cancelable)
Description
The initEvent() method of the Event object is used to initialize the value of an Event
created using the createEvent() of the DocumentEvent object. This method can only
be called before the Event has been dispatched via the dispatchEvent() method,
although it can be called multiple times during that phase if necessary. If called multi-
ple times, the final invocation takes precedence. If called from a subclass of the Event
interface, only the values specified in the initEvent() method are modified: All other
attributes are left unchanged. The eventType parameter is a string that specifies the
event type, canBubble specifies whether this event can bubble, and cancelable speci-
fies whether the event’s default action can be prevented.
Example
Listing 12.9 shows the creation of a mouse event object using the CreateEvent() of
the DocumentEvent object. The event is then initialized using the initEvent() method.
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1738
Event.preventDefault()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.preventDefault()
Description
If an event is cancelable, the preventDefault() method of the Event object is used to
signify that the event is to be canceled, meaning any default action normally taken by
the implementation as a result of the event will not occur. If, during any stage of event
flow, the preventDefault() method is called, the event is canceled. Any default action
associated with the event will not occur. Calling this method for a non-cancelable event
has no effect. After preventDefault() has been called, it will remain in effect through-
out the remainder of the event’s propagation. This method can be used during any stage
of event flow.
Example
Listing 12.10 illustrates the prevention of the default behavior if an event is cancelable.
Event.stopPropagation()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.stopPropagation()
Description
The stopPropagation() method of the Event object is used prevent further propaga-
tion of an event during event flow. If any EventListener calls this method, the event
will cease propagating through the tree. The event will complete dispatch to all listen-
ers on the current EventTarget before event flow stops. This method can be used dur-
ing any stage of event flow.
Example
Listing 12.11 illustrates the stoppage of the event flow of an event currently in the
AT_TARGET phase.
Event.target
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.target;
Description
The target property of the Event object indicates the EventTarget object to which
this event was originally dispatched.
Example
Listing 12.12 illustrates the creation of an EventListener function and checks the
target property of the Event object to see how the event should be handled.
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1740
Event.timeStamp
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventObj.timeStamp
Description
The timeStamp property of the Event object is used to specify the time (in milliseconds
relative to the epoch) at which the event was created. Because some systems might not
provide this information, the value of timeStamp might not be available for all events.
When not available, a value of 0 will be returned. Examples of epoch time are the time
of the system start or 0:0:0 UTC 1st January 1970. The timeStamp property is an object
of type Date.
Example
Listing 12.13 illustrates the creation of an event handler that behaves differently
depending on the time when the event originated.
EventException
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Event object.
Description
The EventException object is thrown when an exception condition is met while eval-
uating certain methods of other DOM Event objects. Table 12.2 lists the constants and
properties for the EventException object.
Example
Listing 12.14 illustrates the catching of an EventException object and reading its code
property.
}catch(evt) {
if(evt.code == EventException.UNSPECIFIED_EVENT_TYPE_ERR)
handleUnexpectedEvent(evt);
}
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1742
EventException.code
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventExceptionObj.code
Description
The code property of the EventException object contains the numeric code represent-
ing the actual exception.
Example
Listing 12.15 illustrates the catching of an EventException object and reading its code
property.
try {
var htmlDocument =
➥HTMLDOMImplementation.createHTMLDocument(“My HTML Page”);
var textArea = htmlDocument.createElement(“TextArea”);
textArea.addEventListener(“MouseEvent”, MouseEventHandler ,false);
}catch(evt) {
if(evt.code == EventException.UNSPECIFIED_EVENT_TYPE_ERR)
handleUnexpectedEvent(evt);
}
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1743
// -->
</script>
</html>
EventListener
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Event object.
Description
The EventListener is simply a function reference that takes an object of type Event
as an argument. When the event listener is registered, the body of the function will be
executed when an specified type of event occurs.
Example
Listing 12.16 shows the declaration of an EventListener and then illustrates the reg-
istration of the listener with a TextArea object.
var htmlDocument =
➥HTMLDOMImplementation.createHTMLDocument(“My HTML Page”);
var textArea = htmlDocument.createElement(“TextArea”);
textArea.addEventListener(“MouseEvent”, MouseEventHandler ,false);
textArea.dispatchEvent(mouseEvent);
// -->
</script>
</html>
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1744
EventTarget
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Event object.
Description
Specified by an Event object’s target attribute, the EventTarget represents the object
that an event is directed to by the DOM implementation. When the event reaches the
target, all appropriate EventListeners are triggered.
All Node objects from a DOM implementation that supports the DOM Level 2 Event
Model inherit from EventTarget. Table 12.1 shows all methods available for the
EventTarget object. Table 12.3 lists all of the methods of the EventTarget object.
Example
Listing 12.17 demonstrates the assignment of an event target and fires off an event.
textArea.dispatchEvent(mouseEvent);
// -->
</script>
EventTarget.addEventListener()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
targetObj.addEventListener(type, listener, useCapture);
Description
The addEventListener() method of the EventTarget object adds an event listener to
this target. Type is the event type to be listened for, the listener parameter is the actual
listener function call, and useCapture is a Boolean field that determines whether the
event can be intercepted by an event listener found in an ancestor of the target.
Example
Listing 12.18 demonstrates the assignment of an event listener and fires off an event.
EventTarget.dispatchEvent()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventTargetObj.dispatchEvent(evt);
Description
The dispatchEvent() method of the EventTarget object directs the event evt to this
EventTarget object.
Example
Listing 12.19 demonstrates using the dispatchEvent() method to direct a mouse event
to an HTML TextArea object.
textArea.dispatchEvent(mouseEvent);
// -->
</script>
</html>
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1747
EventTarget.removeEventListener()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
eventListenerObj.removeListener(type, listener, useCapture)
Description
The removeEventListener() method of the EventTarget object removes the
described and referenced listener from the list of event listeners maintained by this
event target. type is the event type to being listened for, the listener parameter is the
actual listener function call, and useCapture is a Boolean field that determines whether
the event can be intercepted by an event listener found in an ancestor of the target.
Example
Listing 12.20 demonstrates removing an event listener from the first TextArea object
that appears in an HTML document.
MouseEvent
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Event object.
Description
The MouseEvent object provides specific contextual information associated with
mouse events. The MouseEvent object inherits all properties and methods from the
UIMethod object. Table 12.4 lists all of the properties and methods of the MouseEvent
object.
Example
Listing 12.21 shows the creation of a mouse event object using the createEvent()
method of the DocumentEvent object. The event is then initialized using the
initEvent() method.
MouseEvent.altKey
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.altKey
Description
Used to indicate whether the Alt key was depressed during the firing of the event. On
some platforms, this key might map to an alternative key name.
Example
Listing 12.22 illustrates an event listener method as well as inspecting the altKey prop-
erty if the event is a “click” mouse event.
MouseEvent.button
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.Button
Description
During mouse events caused by the depression or release of a mouse button, button is
used to indicate which mouse button changed state. The values for button range from
0 to indicate the left button of the mouse, 1 to indicate the middle button if present, and
2 to indicate the right button. In mice configured for left-handed use in which the but-
ton actions are reversed, the values are instead read from right to left.
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1750
Example
Listing 12.23 illustrates an event listener method as well as inspecting which mouse
button was pressed if the event is a “click” mouse event.
MouseEvent.clientX
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.clientX
Description
The clientX property of the MouseEvent object represents the horizontal coordinate at
which the event occurred relative to the DOM implementation’s client area.
Example
Listing 12.24 illustrates an event listener method as well as inspecting the clientX
property if the event is a “click” mouse event.
MouseEvent.clientY
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.clientY
Description
The clientY property of the MouseEvent object represents the vertical coordinate at
which the event occurred relative to the DOM implementation’s client area.
Example
Listing 12.25 illustrates an event listener method as well as inspecting the clientY
property if the event is a “click” mouse event.
MouseEvent.ctrlKey
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.ctrlKey
Description
Used to indicate whether the CTRL key was depressed during the firing of the event.
Example
Listing 12.26 illustrates an event listener method as well as inspecting the ctrlKey
property if the event is a “click” mouse event.
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1752
MouseEvent.initMouseEvent()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.initMouseEvent(type, canBubble, cancelable, view, detail,
screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey,
button, relatedTarget)
Description
The initMouseEvent() method of the MouseEvent object is used to initialize the value
of a MouseEvent created through the DocumentEvent object. This method can only be
called before the MouseEvent has been dispatched via the dispatchEvent() method,
although it can be called multiple times during that phase if necessary. If called multi-
ple times, the final invocation takes precedence.
The following types of mouse events are supported by DOM Level 2: click, mouseup,
mousedown, mouseover, mousemove, and mouseout.
Example
Listing 12.27 shows the creation of a mouse event object using the createEvent() of
the DocumentEvent object. The event is then initialized using the initEvent() method
to initialize it.
MouseEvent.metaKey
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.metaKey
Description
The metaKey property of the MouseEvent object is used to indicate whether the META
key was depressed during the firing of the event. On some platforms, this key might
map to an alternative key name.
Example
Listing 12.28 illustrates an event listener method as well as inspecting the metaKey
property if the event is a “click” mouse event.
MouseEvent.relatedTarget
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEvent.relatedTarget
Description
The relatedTarget property of the MouseEvent object is used to identify a secondary
EventTarget related to a UI event. Currently, this attribute is used with the mouseover
event to indicate the EventTarget, which the pointing device exited, and with the
mouseout event to indicate the EventTarget, which the pointing device entered.
Example
Listing 12.29 illustrates reading the relatedTarget property of the MouseEvent object.
24 0672321416 CH12 was 11 7/30/01 1:47 PM Page CD:1754
MouseEvent.screenX
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.screenX
Description
The screenX property of the MouseEvent object represents the horizontal coordinate at
which the event occurred relative to the origin of the screen coordinate system.
Example
Listing 12.30 illustrates an event listener method as well as inspecting the screenX
property if the event is a “click” mouse event.
MouseEvent.screenY
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.screenY
24 0672321416 CH12 was 11 7/30/01 1:48 PM Page CD:1755
Description
The screenY property of the MouseEvent object represents the vertical coordinate at
which the event occurred relative to the origin of the screen coordinate system.
Example
Listing 12.31 illustrates an event listener method as well as inspecting the screenY
property if the event is a “click” mouse event.
MouseEvent.shiftKey
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mouseEventObj.shiftKey
Description
The shiftKey property of the MouseEvent object is used to indicate whether the Shift
key was depressed during the firing of the event.
Example
Listing 12.32 illustrates an event listener method as well as inspecting the shiftKey
property if the event is a “click” mouse event.
MutationEvent
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Event object.
Description
The MutationEvent object is designed to allow notification of any changes to the struc-
ture of a document, including Attr and Text modifications. It might be noted that none
of the mutation events listed are designated as cancelable. This stems from the fact that
it is very difficult to make use of existing DOM objects that cause document modifi-
cations if any change to the document might or might not take place because of the can-
cellation of the related event. Although this is still a desired capability, it was decided
that it would be better left until the addition of transactions into the DOM. Many sin-
gle modifications of the tree can cause multiple mutation events to be fired. Rather than
attempt to specify the ordering of mutation events because of every possible modifica-
tion of the tree, the ordering of these events is left to the implementation.
A DOM application can use the hasFeature() method of the DOMImplementation
object with parameter values MutationEvents and 2.0 (respectively) to determine
whether the mutation event module is supported by the implementation. Table 12.5 lists
all of the constants, properties, and methods of the MutationEvent object.
Example
Listing 12.33 shows the creation of a mutation event object using the createEvent()
of the DocumentEvent object. The event is then initialized using the initEvent()
method to initialize it.
MutationEvent.relatedNode
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mutationEventObj.relatedNode
Description
The relatedNode property of the MutationEvent object is used to identify a secondary
node related to a mutation event. For example, if a mutation event is dispatched to a
node indicating that its parent has changed, the relatedNode is the changed parent. If
an event is instead dispatched to a subtree indicating a node was changed within it, the
relatedNode is the changed node. In the case of the DOMAttrModified event it indi-
cates the Attr node which was modified, added, or removed.
Example
Listing 12.34 shows the creation of a mutation event object using the createEvent()
of the DocumentEvent object. The event is then initialized using the initEvent()
method to initialize it.
MutationEvent.attrChange
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mutationEvent.attrChange
Description
The attrChange property of the MutationEvent object indicates the type of change
that triggered the DOMAttrModified event. The values can be MODIFICATION, ADDITION,
or REMOVAL.
Example
Listing 12.35 checks the attrChange property to determine how an attribute was mod-
ified and handles the event accordingly.
MutationEvent.attrName
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mutationEvent.attrName
Description
The attrName property of the MutationEvent object indicates the name of the changed
Attr node in a DOMAttrModified event.
Example
Listing 12.36 checks the attrName property to determine if the modified attribute is a
TextArea. If so, the event is handled appropriately.
24 0672321416 CH12 was 11 7/30/01 1:48 PM Page CD:1759
MutationEvent.initMutationEvent()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mutationEventObj.initMutationEvent(type, canBubble, cancelable,
relatedNode, prevValue, newValue, attrName, attrChange)
Description
The initMutationEvent() method is used to initialize the value of a MutationEvent
created using the DocumentEvent object. This method can only be called before the
MutationEvent has been dispatched via the dispatchEvent() method, though it can
be called multiple times during that phase if necessary. If called multiple times, the
final invocation takes precedence.
The possible values for type are DOMSubTreeModified, DOMNodeInserted, and
DOMNodeRemoved.
Example
Listing 12.37 shows the creation of a mutation event object using the createEvent()
of the DocumentEvent object. The event is then initialized using the initEvent()
method to initialize it.
MutationEvent.newValue
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mutationEventObj.newValue
Description
The newValue property of the MutationEvent object indicates the new value of the
Attr node in DOMAttrModified events and of the CharacterData node in
DOMCharDataModified events.
Example
Listing 12.38 checks the prevValue and newValue properties to determine whether any
actual changes have occurred to the Attr in question.
MutationEvent.prevValue
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
mutationEventObj.prevValue
Description
The prevValue property indicates the previous value of the Attr node in
DOMAttrModified events, and of the CharacterData node in DOMCharDataModified
events.
Example
Listing 12.39 checks the prevValue and newValue properties to determine whether any
actual changes have occurred to the Attr in question.
24 0672321416 CH12 was 11 7/30/01 1:48 PM Page CD:1761
UIEvent
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
DOM Event object.
Description
The UIEvent object provides specific contextual information associated with User
Interface events. The UIEvent object inherits all properties and methods from the
Event object. Table 12.6 lists the properties and methods of the UIEvent object.
Example
Listing 12.40 shows the creation of a user interface event object using the
createEvent() method of the DocumentEvent object. The event is then initialized
using the initUIEvent() method.
Listing 12.40 Creating and Initializing a User Interface Event Using the
initUIEvent() Method of the UIEvent Object
<html>
<script language=”JScript”>
<!--
var uiEvent = DocumentEvent.createEvent(“UIEvent”);
uiEvent.initUIEvent(“DOMFocusOut”, true, false, );
// -->
</script>
</html>
24 0672321416 CH12 was 11 7/30/01 1:48 PM Page CD:1762
UIEvent.detail
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
uiEventObj.detail
Description
The detail property of the UIEvent object specifies some detail information about the
Event, depending on the type of event.
Example
Listing 12.41 shows the creation of a user interface event object using the
createEvent() method of the DocumentEvent object. The event is then initialized
using the initEvent() method. After initialization, the detail property is written to.
UIEvent.initUIEvent()
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
uiEventObj.initUIEvent(type, canBubble, cancelable, view, detail)
Description
The initUIEvent() method of the UIEvent object is used to initialize the value of an
UIEvent created through the DocumentEvent object. This method can only be called
before the UIEvent has been dispatched via the dispatchEvent() method, although it
can be called multiple times during that phase if necessary. If called multiple times, the
final invocation takes precedence.
The type parameter is a string that can be DOMFocusIn, DOMFocusOut, or
DOMActivate. The canBubble parameter indicates whether this event can bubble, the
cancelable parameter indicates whether this event can be canceled, view is the
AbstractView object in which this UIEvent originated, and detail is a number that
24 0672321416 CH12 was 11 7/30/01 1:48 PM Page CD:1763
Example
Listing 12.42 shows the creation and initialization of a UIEvent using the
initUIEvent() method.
UIEvent.view
JavaScript 1.5+, JScript 5.0+
Nav6+, IE5+
Syntax
uiEventObj.view
Description
The view property of the UIEvent object identifies the AbstractView from which the
event was generated.
Example
Listing 12.43 show the writing of the view property of the UIEvent object.
DOM CSS
CHAPTER 13
DOM CSS
Counter
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS object.
Description
Table 13.1 Arguments Associated With Counter
Object
Type Item Description
Property identifier This is a read-only property of
type String. Represents the
identifier of the counter.
listStyle This read-only property of
type String. Represents the
style of the list.
separator This read-only property of
type String. Represents the
separator of the nested
counter.
Example
Listing 13.1 illustrates reading the properties of the Counter
object.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1768
Counter.identifier
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
CounterObj.identifier
Description
The read-only property identifier of the Counter object is used for to identify the
counter.
Example
Listing 13.2 illustrates reading the identifier property of the Counter object.
Counter.listStyle
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
counterObj.listStyle
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1769
Description
The read-only property listStyle of the Counter object is of type String. The
listStyle property is used for the style of the list.
Example
Listing 13.3 illustrates reading the listStyle property of the Counter object.
Counter.separator
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Counter.separator
Description
The read-only property separator of the Counter object is of type String. The
separator property is used for the separator of the nested counters.
Example
Listing 13.4 illustrates reading the separator property of the Counter object.
CSSCharsetRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The CSSCharsetRule object represents a @charset rule in a CSSStyleSheet.
CSSCharsetRule extends CSSRule. The property associated with the CSSCharsetRule
object is as follows:
Item Description
encoding This is a read-only property of type String. Represents a list of
media types for this rule.
Example
Listing 13.5 demonstrates reading the encoding property of the CSSCharsetRule
object.
CSSCharsetRule.encoding
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssCharsetRuleObj.encoding
Description
The read-only property encoding of the CSSCharsetRule object is of type String.
Encoding contains the encoding information used in this rule. This attribute can raise
a DOMException with the values of NO_MODIFICATION_ALLOWED_ERR and SYNTAX_ERR.
Example
Listing 13.6 demonstrates reading the encoding property of the CSSCharsetRule
object.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1771
CSSFontFaceRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The CSSFontFaceRule object represents a set of font descriptions in a CSSStyleSheet.
CSSFontFaceRule inherits all properties and methods from CSSRule. The property
associated with the CSSFontFaceRule object is as follows:
Item Description
style This is a read-only property of type CSSStyleDeclaration.
Represents declaration block of the rule.
Example
Listing 13.7 demonstrates manipulating the style property of the CSSFontFaceRule
object.
CSSFontFaceRule.style
JavaScript 1.5+, JScript 5+
Nav6+, IE5+JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssFontFaceRuleObj.style
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1772
Description
This read-only attribute is of type CSSStyleDeclaration. This attribute represents the
declaration block of the rule.
Example
Listing 13.8 demonstrates manipulating the style property of the CSSFontFaceRule
object.
CSSImportRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The CSSImportRule object represents the @import rule of a CSSStyleSheet.
CSSImportRule inherits all methods and properties of CSSRules. Table 13.2 lists all
properties of the CSSImportRule object.
Example
Listing 13.9 demonstrates reading the href property of the CSSImportRule object.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1773
CSSImportRule.href
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssImportRuleObj.href
Description
The read-only property href of the CSSImportRule object is of type string. The href
property is the textual representation of the location of the style sheet to be imported.
The URI specifier won’t be included in this attribute.
Example
Listing 13.10 demonstrates reading the href property of the CSSImportRule object.
CSSImportRule.media
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssImportRuleObj.media
Description
The read-only property media of the CSSImportRule object is of type MediaList. The
media property is a list of media types that can be used by the style sheet.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1774
Example
Listing 13.11 demonstrates reading the media property of the CSSImportRule object.
CSSImportRule.styleSheet
JavaScript 1.5+, JScript 5+
Nav6+, IE5+JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssImportRuleObj.styleSheet
Description
The read-only property styleSheet of the CSSImportRule object is of type
CSSStyleSheet. The styleSheet property represents the loaded style sheet of this rule.
If a style sheet hasn’t been loaded by this rule, the value will be Null.
Example
Listing 13.12 demonstrates reading the styleSheet property of the CSSImportRule
object.
CSSMediaRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1775
Description
The CSSMediaRule object represents the target media types of a set of rules.
CSSMediaRule extends CSSRule. Table 13.3 lists all methods and properties of the
CSSMediaRule object.
Example
Listing 13.13 gets a CSSMediaRule and sets its media type.
CSSMediaRule.cssRules
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssMediaRuleObj.cssRules
Description
The cssRule property of the CSSMediaRule object is a read-only attribute of type
CSSRuleList. This is a list of CSS rules contained within the media block.
Example
Listing 13.14 demonstrates iterating through the cssRules property and processing
each item.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1776
CSSMediaRule.deleteRule()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssMediaRuleObj.deleteRule(index)
Description
The deleteRule() method of the CSSMediaRule takes the argument Number index.
This method deletes the rule from the media block. This method can raise a
DOMException with the values of NO_MODIFICATION_ALLOWED_ERR and SYNTAX_ERR.
Example
Listing 13.15 demonstrates removing a CSS media rule from the media block.
CSSMediaRule.insertRule()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssmediaRuleObj.insertRule(rule, index)
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1777
Description
The insertRule() method of the CSSMediaRule object takes the arguments String
rule and Number index and returns the index of the newly inserted rule. This method
can raise a DOMException with the values of HIERARCHY_REQUEST_ERR,
INDEX_SIZE_ERR, NO_MODIFICATION_ALLOWED_ERR, and SYNTAX_ERR.
Example
Listing 13.16 illustrates inserting a rule into the media block.
Listing 13.16 Inserting a Rule into the Media Block Using the
insertRule() Method
<html>
<script language=”JScript”>
<!--
cssMediaRuleObj.insertRule(“media:screen”, 1);
// -->
</script>
</html>
CSSMediaRule.media
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssMediaRuleObj.media
Description
The media property of the CSSMediaRule object is a read-only attribute of type
MediaList. This is a list of media types for this rule.
Example
Listing 13.17 getting a CSSMediaRule and setting its media type.
CSSPageRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The CSSPageRule object represents a @page rule within a CSSStyleSheet. The
CSSPageRule extends CSSRule. Table 13.4 lists all properties of the CSSPageRule
object.
Example
Listing 13.18 demonstrates setting the selectorText property of a CSSPageRule
object.
CSSPageRule.selectorText
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
CSSPageRule.selectorText
Description
The selectorText property of the CSSPageRule object is a read-only attribute of type
String. The selectorText property is a textual representation of the page selector.
This attribute can raise a DOMException with the values of NO_MODIFICATION_
ALLOWED_ERR and SYNTAX_ERR.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1779
Example
Listing 13.19 demonstrates setting the selectorText property of a CSSPageRule
object.
CSSPageRule.style
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPageRuleObj.style
Description
The style property of the CSSPageRule object is a read-only attribute of type
CSSStyleDeclaration. The style property represents the declaration block of this
rule.
Example
Listing 13.20 demonstrates manipulating the style property of a CSSPageRule object.
CSSPrimitiveValue
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1780
Description
The CSSPrimitiveValue object represents a CSSValue. This object can be used to
determine or set a value for a specific style property. Table 13.5 lists all constants, prop-
erties, and methods of the CSSPrimitiveValue object.
Example
Listing 13.21 illustrates using the getRGBColor() method of the CSSPrimitiveValue
object.
CSSPrimitiveValue.getCounterValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPrimitiveValueObj.getCounterValue()
Description
The getCounterValue() method of the CSSPrimitiveValue takes no arguments and
returns a Counter object representing the Counter value. This method can raise a
DOMException with the value of INVALID_ACCESS_ERR.
Example
Listing 13.22 Getting a counter value for the CSSPrimitiveValue object.
CSSPrimitiveValue.getFloatValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPrimitiveValueObj.getFloatValue(unitType)
Description
The getFloatValue() method of the CSSPrimitiveValue takes the argument
unitType and returns a float value. This method can raise a DOMException with the
value of INVALID_ACCESS_ERR.
Example
Listing 13.23 demonstrates the assigning of an event target and fires off an event.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1783
CSSPrimitiveValue.getRectValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPrimitiveValueObj.getRectValue()
Description
The getRectValue() method of the CSSPrimitiveValue takes no arguments and
returns a Rect object representing a Rect value. This method can raise a DOMException
with the value of INVALID_ACCESS_ERR.
Example
Listing 13.24 Illustrates getting a Rect value for the CSSPrimitiveValue object.
CSSPrimitiveValue.getRGBColorValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPrimitiveValueObj.getRGBColorValue()
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1784
Description
The getRGBColorValue() method of the CSSPrimitiveValue takes no arguments and
returns a RGBColor object representing the RGB Color value. This method can raise a
DOMException with the value of INVALID_ACCESS_ERR.
Example
Listing 13.25 illustrates using the getRGBColorValue() method of the
CSSPrimitiveValue object.
CSSPrimitiveValue.getStringValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPrimitiveValueObj.getStringValue()
Description
The getStringValue() method of the CSSPrimitiveValue object takes no arguments
and returns a String value in the current unit. This method can raise a DOMException
with the value of INVALID_ACCESS_ERR.
Example
Listing 13.26 Getting a string value for the CSSPrimitiveValue object.
CSSPrimitiveValue.primitiveType
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPrimitiveValueObj.primitiveType
Description
The primitiveType property of the CSSPrimitiveValue object is a read-only attribute
of type Number. The primitiveType property is a Number representing the type of value
as defined by the constants.
Example
Listing 13.27 demonstrates reading the primitiveType property of the
CSSPrimitiveValue object.
CSSPrimitiveValue.setFloatValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPrimitiveValueObj.setFloatValue(unitType, floatType)
Description
The setFloatValue() method of the CSSPrimitiveValue takes the arguments
unitType and floatType and has no return value. This method can raise a
DOMException with the values of NO_MODIFICATION_ALLOWED_ERR and
INVALID_ACCESS_ERR.
Example
Listing 13.28 demonstrates setting a float value for CSSPrimitveValue.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1786
CSSPrimitiveValue.setStringValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssPrimitiveValueObj.setStringValue(stringType, stringValue)
Description
The setStringValue() method of the CSSPrimitiveValue takes the arguments
stringType and stringValue and has no return value. This method can raise a
DOMException with the values of NO_MODIFICATION_ALLOWED_ERR and
INVALID_ACCESS_ERR.
Example
Listing 13.29 setting a string value for the CSSPrimitiveValue object.
CSSRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1787
Description
CSSRule is an abstract base object for any CSS statement including the rules set and at
rules. Table 13.6 lists all the properties of the CSSRule object.
Example
Listing 13.30 illustrates getting a CSSRules object and iterating through the list while
checking each rule’s type.
CSSRule.cssText
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssRuleObj.cssText
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1788
Description
The cssText property of the CSSRule object returns a string. This is a textual repre-
sentation of the CSS rule. This String holds the current state of the CSS rule. This
attribute can raise a DOMException with the values of HIERARCHY_REQUEST_ERR,
NO_MODIFICATION_ALLOWED_ERR, INVALID_MODIFICATION_ERR, and SYNTAX_ERR.
Example
Listing 13.31 illustates the setting of the cssText property for a CSSRule object.
Listing 13.31 Setting CSS Text Using the cssText Property of the
CSSRule Object
<html>
<script language=”JScript”>
<!--
cssRule.cssText = “color:’green’; font-weight:bold”;
// -->
</script>
</html>
CSSRule.parentRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssRuleObj.parentRule
Description
The read-only property parentRule of the CSSRule object is of type CSSRule. If this
CSSRule is contained within another CSSRule, this is the containing rule. Otherwise this
is Null.
Example
Listing 13.32 demonstrates reading the parentRule property.
CSSRule.parentStyleSheet
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssRuleObj.parentStyleSheet
Description
The read-only property parentStyleSheet of the CSSRule object is of type
CSSStyleSheet. Represents the style sheet that contains this rule.
Example
Listing 13.33 demonstrates reading the parentStyleSheet property.
CSSRule.type
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssRuleObj.type
Description
The read-only property type of the CSSRule object returns a number indicating the type
of rule.
Example
Listing 13.34 getting a CSSRules object and iterating through the list while checking
each rule’s type.
Listing 13.34 Checking Rule Type Reading the type Property of CSSRule
<html>
<script language=”JScript”>
<!--
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1790
CSSRuleList
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
CSSRuleList is an object that acts as an abstraction of an ordered collection of CSS
Rules. Table 13.7 lists all properties and methods of the CSSRuleList object.
Example
Listing 13.35 getting a CSSRuleList object and iterating through the list.
CSSRuleList.item()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssRuleListObj.item(index)
Description
The item() method of the CSSRuleList takes the argument index. This method is
used to retrieve the CSS rule by the ordinal index.
Example
Listing 13.36 getting a CSSRuleList object and iterating through the list.
CSSRuleList.length
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssRuleListObj.length
Description
The length property of the CSSRuleList object returns the number of CSS rules con-
tained within the CSSRuleList.
Example
Listing 13.37 getting a CSSRuleList object and iterating through the list.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1792
CSSStyleDeclaration
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The CSSStyleDeclaration object represents a CSS declaration block.
CSSStyleDeclaration can be used to set or determine what style properties are set
within the block. Table 13.8 lists all properties and methods of the
CSSStyleDeclaration object.
Example
Listing 13.38 demonstrates setting the CSSText property of the CSSStyleDeclation
object.
CSSStyleDeclaration.cssText
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleDeclObj.cssText
Description
The cssText property of the CSSStyleDeclaration object is a textual representation
of the declaration block. Setting this attribute will reset all properties set in this decla-
ration block. This attribute can raise a DOMException with the values of
NO_MODIFICATION_ALLOWED_ERR and SYNTAX_ERR.
Example
Listing 13.39 demonstrates setting the cssText property of CSSStyleDeclaration
object.
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1794
CSSStyleDeclaration.getPropertyCSSValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStuleDeclObj.getPropertyCSSValue(propertyName)
Description
The getPropertyCSSValue() method of the CSSStyleDeclaration takes the argument
string propertyName and returns a CSSValue representing the value of the property of
the property that has been set. Returns Null if the property hasn’t been set.
Example
Listing 13.40 illustrates getting a property value using the getPropertyCSSValue()
method of CSSStyleDeclaration.
CSSStyleDeclaration.getPropertyPriority()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleDecl.getPropertyPriority(propertyName)
25 0672321416 CH13 was 12 7/30/01 1:49 PM Page CD:1795
Description
The getPropertyPriority() method of the CSSStyleDeclaration takes the argument
propertyName and returns a String representing the priority of the CSS property.
Returns an empty string if none exists.
Example
Listing 13.41 illustrates getting a property value using the getPropertyPriority()
method of CSSStyleDeclaration.
CSSStyleDeclaration.getPropertyValue()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleDeclObj.getPropertyValue(propertyName)
Description
The getPropertyValue() method of the CSSStyleDeclaration takes the argument
propertyName and returns a String representing the value of the property in the dec-
laration block. Returns an empty string if the property hasn’t been set.
Example
Listing 13.42 illustrates getting a property value using the getPropertyValue()
method of CSSStyleDeclaration.
CSSStyleDeclaration.item()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleDeclarationObj.item(index)
Description
The item() method of the CSSStyleDeclaration takes the argument index and
returns a String representing the name of the property at the ordinal position.
Example
Listing 13.43 illustrates getting a CSSValue and setting its value type.
CSSStyleDeclaration.length
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleDeclObj.length
Description
The length property of the CSSStyleDeclaration object is a read-only attribute of
type Number. Length is the number of properties that have been set in this declaration
block.
Example
Listing 13.44 illustrates reading the length property of CSSStyleDeclaration.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1797
CSSStyleDeclaration.parentRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleDeclObj.parentRule
Description
The parentRule read-only property of the CSSStyleDeclaration object. The
parentRule property represents the CSSRule that contains this declaration block or is
Null if this block isn’t contained in a CSSRule.
Example
Listing 13.45 illustrates reading the parentRule property of CSSStyleDeclaration.
CSSStyleDeclaration.removeProperty()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleDeclObj.removeProperty(propertyName)
Description
The removeProperty() method of the CSSStyleDeclaration takes the argument
propertyName and returns a String representing the value of the property that has
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1798
been set. Returns an empty string if the property hasn’t been set. This method can raise
a DOMException with the value of NO_MODIFICATION_ALLOWED_ERR.
Example
Listing 13.46 illustrates getting a property value using the removeProperty() method
of CSSStyleDeclaration.
CSSStyleDeclaration.setProperty()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleDeclObj.setProperty(propertyName, value, priority)
Description
The setProperty() method of the CSSStyleDeclaration takes the arguments string
propertyName, string value, string priority, and has no return value. This method
can raise a DOMException with the value of NO_MODIFICATION_ALLOWED_ERR.
Example
Listing 13.47 illustrates setting a property value using the setProperty() method of
CSSStyleDeclaration.
CSSStyleRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
CSSStyleRule is an object representing a single rule set in a CSSStyleSheet.
CSSStyleRule extends CSSRule. Table 13.9 lists all properties of the CSSStyleRule
object.
Example
Listing 13.48 gets a CSSStyleRule object and sets its selectorText property.
CSSStyleRule.selectorText
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleRuleObj.selectorText
Description
The selectorText of the CSSStyleRule object is a read-only attribute of type string.
This is a textual representation of the selector of this rule set. This attribute can raise a
DOMException with the values of NO_MODIFICATION_ALLOWED_ERR and SYNTAX_ERR.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1800
Example
Listing 13.49 getting a CSSStyleRule object and setting its selectorText property.
CSSStyleRule.style
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleRuleObj.style
Description
The style property of the CSSStyleRule object is a read-only property of type
CSSStyleDeclaration. This contains the declarative block of the rule set.
Example
Listing 13.50 demonstrates the assignment of a value to the height property of the
style property of the CSSStyleRule object.
CSSStyleSheet
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1801
Description
The CSSStyleSheet object is used to represent a CSS style sheet. This object allows
access to the collection of rules within a CSS StyleSheet. Table 13.10 lists all proper-
ties and methods of the CSSStyleSheet object.
Example
Listing 13.51 demonstrates the creation of a CSSStyleSheetObject.
CSSStyleSheet.cssRules
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleSheetObj.cssRules
Description
The cssRules property of the CSSStyleSheet object is a read-only property that is of
type CSSRuleList object. cssRules is a list of all rules contained within the style sheet
and includes both rule sets and at-rules.
Example
Listing 13.52 demonstrates iterating through the list of cssRules and displaying the
type of each.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1802
CSSStyleSheet.deleteRule()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleSheetObj.deleteRule(index)
Description
The deleteRule() method of the CSSStyleSheet takes the argument index. This
method is used to remove a rule from the style sheet at position index. This
method can raise a DOMException with the values of INDEX_SIZE_ERR and
NO_MODIFICATION_ALLOWED_ERR.
Example
Listing 13.53 demonstrates removing a CSSRule from the stylesheet.
CSSStyleSheet.insertRule()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleSheetObj.insertRule(rule, index)
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1803
Description
The insertRule() method of the CSSStyleSheet takes the arguments rule and index
and returns the index of the newly inserted rule. This method can raise a DOMException
object with the values of HIERARCHY_REQUEST_ERR, INDEX_SIZE_ERR,
NO_MODIFICATION_ALLOWED_ERR, and SYNTAX_ERR.
Example
Listing 13.54 illustrates inserting a new CSSRule into the style sheet.
CSSStyleSheet.ownerRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssStyleSheetObj.ownerRule
Description
This is a read-only attribute that is of type CSSRule object. ownerRule can contain both
rule sets and at-rules.
Example
Listing 13.55 demonstrates reading the ownerRule property.
CSSUnknownRule
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The CSSUnknownRule object represents an at-rule that isn’t supported. It inherits all
methods and properties from CSSRule.
Example
Listing 13.56 getting a CSSRules object and iterating through the list while checking to
see whether the rule type is a CSSUnknownRule.
CSSValue
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The CSSValue object represents a simple or complex value within the context of a CSS
property. Table 13.11 lists all constants and properties of the CSSValue object.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1805
Example
Listing 13.57 illustrates getting a CSSValue and setting its value type.
CSSValue.cssText
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssValueObj.cssText
Description
The cssText property of the CSSValue object is of type string. The cssText property
is a textual representation of the current value. This attribute can raise a DOMException
with the values of NO_MODIFICATION_ALLOWED_ERR, INVALID_MODIFICATION_ERROR,
and SYNTAX_ERR.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1806
Example
Listing 13.58 illustrates getting a CSSValue and setting its value type.
CSSValue.cssValueType
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssValueObj.cssValueType
Description
The read-only property cssValueType of the CSSValue object is of type Number. The
cssValueType property is a code defining the type of value.
Example
Listing 13.59 illustrates getting a CSSValue and setting its value type.
CSSValueList
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1807
Description
The CSSValueList object is an abstraction of an ordered collection of CSSValues.
Table 13.12 lists the property and method of the CSSValue object.
Example
Listing 13.60 illustrates iterating through a CSSValueList object.
CSSValueList.item()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssValueListObj.item(index)
Description
The item() method of the CSSValueList takes the argument Number index and returns
the CSSValue at the index position in the list.
Example
Listing 13.61 illustrates iterating through a CSSValueList object.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1808
CSSValueList.length
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
cssValueListObj.length
Description
This read-only attribute is of type Number. Length is a number representing the number
of CSSValue objects in the list.
Example
Listing 13.62 illustrates iterating through a CSSValueList object.
DocumentCSS
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The DocumentCSS object represents a document with a CSS view. The method associ-
ated with the DocumentCSS object is as follows:
Item Description
getOverrideStyle() This method returns a CSSStyleSheet representing
the override style declaration.
Example
Listing 13.63 demonstrates getting the overridden style of a particular element.
DocumentCSS.getOverrideStyle()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
documentCSSObj.getOverrideStyle(elt, pseudoElt)
Description
The getOverrideStyle() method of the DocumentCSS takes the arguments Element
elt and String pseudoElt and returns the override style declaration.
Example
Listing 13.64 demonstrates getting the overridden style of a particular element.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1810
DOMImplementationCSS
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The DOMImplementationCSS object represents the ability for the DOM user to create a
CSSStyleSheet outside the context of the document. The method associated with the
DOMImplementationCSS object is as follows:
Item Description
createCSSStyleSheet This method returns a CSSStyleSheet object rep-
resenting the new CSSStyleSheet.
Example
Listing 13.65 demonstrates creating a new style sheet.
DOMImplementationCSS.createCSSStyleSheet()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOMImplementationCSS.createCSSStyleSheet(title, media)
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1811
Description
The CreateCSSStyleSheet() method of the DOMImplementationCSS takes the argu-
ments String title and String media and returns a new CSSStyleSheet. This method
can raise a DOMException with the value of SYNTAX_ERR.
Example
Listing 13.66 demonstrates creating a new style sheet.
ElementCSSInlineStyle
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The ElementCSSInlineStyle object represents the contents of the style attribute for
HTML elements. The property associated with the ElementCSSInlineStyle object is
as follows:
Item Description
style This is a read-only property of type CSSStyleDeclaration.
Example
Listing 13.67 demonstrates reading the style property from the
ElementCSSInlineStyle object.
ElementCSSInlineStyle.style
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
elementCSSInlineStyleObj.style
Description
The read-only property style of the ElementCSSInlinestyle object is of type
CSSStyleDeclaration. style is a textual representation of the style for HTML
elements.
Example
Listing 13.68 demonstrates reading the style property from the
ElementCSSInlineStyle object.
Rect
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The Rect object represents any Rect value. Rect reflects the values in the style prop-
erties. Modifications in the style properties are reflected in this object. Table 13.13
lists all properties of the Rect object.
Item Description
right This read-only property is of type CSSPrimitiveValue. Represents the
right of the Rect.
top This is a read-only property of type CSSPrimitiveValue. Represents the
top of the Rect.
Example
Listing 13.69 illustrates reading the properties of the Rect object.
Rect.bottom
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
rectObj.bottom
Description
The read-only property bottom of the Rect object is of type CSSPrimitiveValue. bot-
tom represents the bottom of the Rect.
Example
Listing 13.70 illustrates reading the bottom property of the Rect object.
Rect.left
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Rect.left
Description
The read-only property left of the Rect object is of type CSSPrimitiveValue. Left
represents the left of the Rect.
Example
Listing 13.71 illustrates reading the left property of the Rect object.
Rect.right
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Rect.right
Description
The read-only property right of the Rect object is of type CSSPrimitiveValue. Right
represents the right of the rectangle.
Example
Listing 13.72 illustrates reading the right property of the Rect object.
// -->
</script>
</html>
Rect.top
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
Rect.top
Description
The read-only property top of the Rect object is of type CSSPrimitiveValue. The top
property represents the top of the Rect.
Example
Listing 13.73 illustrates reading the top property of the Rect object.
RGBColor
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The RGBColor object is a representation of any RGB color value. RGBColor reflects the
values in the style properties. Modifications in the style properties are reflected in this
object. Table 13.14 lists all properties of the RGBColor object.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1816
Example
Listing 13.74 illustrates the manipulation of the RGBColor object.
// -->
</script>
</html>
RGBColor.blue
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
rgbColorObj.blue
Description
The read-only property blue of the RGBColor object is of type CSSPrimitiveValue.
blue is used to represent the blue value of the RGB color.
Example
Listing 13.75 illustrates the manipulation of the RGBColor object.
RGBColor.green
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
rgbColor.green
Description
The read-only property green of the RGBColor object is of type CSSPrimitiveValue.
green is used to represent the green value of the RGB color.
Example
Listing 13.76 illustrates the manipulation of the RGBColor object.
RGBColor.red
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
rgbColor.red
Description
The read-only property red of the RGBColor object is of type CSSPrimitiveValue. Red
is used to represent the red value of the RGB color.
Example
Listing 13.77 illustrates the manipulation of the RGBColor object.
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1818
// -->
</script>
</html>
ViewCSS
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
DOM CSS Object.
Description
The ViewCSS object represents a CSS view. The method associated with the ViewCSS
object is as follows:
Item Description
getComputedStyle This method returns a CSSStyleDeclaration representing
the computed style.
Example
Listing 13.78 demonstrates getting the computed style of a particular element.
ViewCSS.getComputedStyle()
JavaScript 1.5+, JScript 5+
Nav6+, IE5+
Syntax
viewCSSObj.getComputedStyle(elt, pseudoElt)
25 0672321416 CH13 was 12 7/30/01 1:50 PM Page CD:1819
Description
The getComputedStyle() method of the ViewCSS object takes the arguments Element
elt and String pseudoElt and returns the computed style.
Example
Listing 13.79 demonstrates getting the computed style of a particular element.
ON THE CD-ROM
26 0672321416 CH14a 7/30/01 1:52 PM Page CD:1822
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1823
JScript RunTime
CHAPTER 14
JScript RunTime
This chapter contains all the items and elements making up
Microsoft’s Scripting Engine additions. This contains JScript
elements that are specific to Microsoft’s interpreters. These
elements can be used with IIS ASP pages, Windows Script
Host, and within the Internet Explorer browser. Table 14.1
shows the JScript support in the various applications that are
shipped with Microsoft’s Scripting Engine.
NOTE
Microsoft products provide the ability to upgrade the
scripting engines, which are separate from the applica-
tion, in its products. This means that it is possible for
Internet Explorer 3 to have JScript 5.0 with full backward
compatibility. Table 14.1 only lists the engine version that
was shipped with the product.
All the extensions discussed in this chapter are objects supplied in Microsoft’s
Scripting Runtime Library, which is named scrrun.dll. They are not intrinsic mem-
bers of the JScript language itself, which is found in the jscript.dll library. However,
there are some exceptions. These are the conditional compilation flags, GetObject
and ActiveXObject, and the various ScriptEngine functions that are covered in
Chapter 7, “Core Language.”
The exceptions noted previously are probably the most notable differences between
JScript and JavaScript. JScript is an automation-compatible language—it can create
and manipulate COM (Component Object Model) objects. Both the Dictionary and
FileSystemObject objects are examples of this, as are Excel, Word, and other
Microsoft Office applications. The binaries for these applications, in the world of
COM, are called COM servers.
It is worth noting that the Microsoft Scripting Runtime Library did not come with
Internet Explorer until version 5. It was available with IIS and the Windows Script
Host. As mentioned in the previous note, you can download the latest version from
Microsoft’s Scripting Technologies page at http://msdn.microsoft.com/scripting.
Now that you have taken a quick look at Microsoft’s JScript and COM, you can get on
to the reference. As with the other chapters in this section of the book, each entry
includes a version, syntax, description, example, as well as many other details of the
JScript language.
Dictionary
JScript3.0+
Syntax
dictionaryObj = new ActiveXObject(“Scripting.Dictionary”);
Description
The Dictionary object is an associative array of items that can be of any type. Each
item is associated with a unique key that provides access to each item in the array. The
key is usually an integer or a string, but can be anything except an array. A Dictionary
object is created and returned when the ActiveXObject() method has the server and
type name set to “Scripting.Dictionary”.
A number of properties and methods are provided by the Dictionary object to provide
access to the items in the dictionary. These properties and methods are listed in Table
14.2.
Example
Listing 14.1 creates a dictionary object using the ActiveXObject() constructor and
assigns the new dictionary object to the variable “fruits”.
Dictionary.Add()
JScript3.0+
Syntax
dictionaryobj.Add(key, item)
Description
The Add() method of the Dictionary object adds new items to the dictionary using
key, item pairs. The item can be of any type, but the key cannot be an array. Nothing
is returned from this method.
Example
Listing 14.2 creates a fruit dictionary and then uses the Add() method to add fruit items
to the dictionary.
Listing 14.2 Create and Add Items to a Fruit Dictionary Using Add()
<script type=”text/jscript” language=”JScript”>
<!--
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1826
Dictionary.Count
JScript3.0+
Syntax
dictionaryobj.Count
Description
The Count property of the Dictionary object contains the number of items in the
dictionary. This property is read-only, so it cannot be used to change the size of the
dictionary.
Example
Listing 14.3 creates a dictionary and displays the number of items that it contains.
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
Dictionary.Exists()
JScript3.0+
Syntax
dictionaryobj.Exists(key)
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1827
Description
The Exists() method of the Dictionary object determines whether an item exists in
the dictionary based on the key that is passed in to the method. If key exists, true is
returned; otherwise false is returned from the method.
Example
Listing 14.4 creates a dictionary and determines if any fruits that begin with “s” are in
the dictionary
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
if(fruits.Exists(“S”))
document.write(“The fruit “,fruits.Item(‘S’),” exists in dictionary.”);
else
document.write(“No fruits that begin with <b>s</b> exist in dictionary.”);
// -->
</script>
Dictionary.Item()
JScript3.0+
Syntax
dictionaryobj.Item(key)
dictionaryobj.Item(key) = newItem
Description
The Item() property of the Dictionary object provides the capability to retrieve, cre-
ate, and modify items in the dictionary.
To retrieve an item from the dictionary, simply specify the key of the item to be
returned in the argument list. The item associated with the key will be returned. If the
key does not exist in the dictionary, a new key, item pair will be created in the dic-
tionary and the item will be left empty. Nothing is returned from the method when this
scenario occurs.
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1828
To create a new key, item pair in the dictionary, specify a new unique key as the
method’s argument. Directly after the Item() method, place an equal sign followed by
the newItem to be associated with the key. The newly created item will be returned
from the method.
Finally, an item can be changed by specifying the key associated with the item in the
argument list. Directly after the Item() method, place an equal sign followed by the
newItem that will replace the existing item. The new item will be returned from the
method.
Example
Listing 14.5 uses Item() to create, modify, and retrieve an item from the dictionary.
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
// -->
</script>
Dictionary.Items()
JScript3.0+
Syntax
dictionaryobj.Items()
Description
The Items() method of the Dictionary object returns all the items in the dictionary in
an Visual Basic array.
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1829
NOTE
A Visual Basic array (VBArray object) can be converted to a JScript array by using
the VBArray object’s toArray() method.
Example
Listing 14.6 uses the Items() method to retrieve all the items that in the dictionary as
a Visual Basic array. The toArray() method is then used to convert the Visual Basic
array to a JavaScript array. Each item in the new theArray array is displayed in the
browser.
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
//Create an array.
theArray = (new VBArray(fruits.Items())).toArray();
// -->
</script>
Dictionary.Key()
JScript3.0+
Syntax
dictionaryobj.Key(key) + = newKey
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1830
Description
The Key() property of the Dictionary object provides the ability to change an exist-
ing key in the dictionary. To change a key, simply specify the key of the item you want
changed followed by an equal sign and the newKey. If the key does not exist in the dic-
tionary, a new key, item pair will be created in the dictionary using newKey and leav-
ing the item empty. In either case, the new key is returned by the method.
Example
Listing 14.7 uses Key() to change an existing key in the dictionary.
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
// -->
</script>
Dictionary.Keys()
JScript3.0+
Syntax
dictionaryobj.Keys()
Description
The Keys() method of the Dictionary object returns all the keys in the dictionary in
an array.
Example
Listing 14.8 uses the Keys() method to retrieve all the keys that are in the dictionary.
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
//Create an array.
theArray = (new VBArray(fruits.Keys())).toArray();
// -->
</script>
Dictionary.Remove()
JScript3.0+
Syntax
dictionaryobj.Remove(key)
Description
The Remove() method of the Dictionary object removes the key, item pair from the
dictionary that matches the key passed into the method. If no match is found, an error
is returned. Nothing is returned from this method.
Example
Listing 14.9 uses the Remove() method to remove berry from the dictionary.
Listing 14.9 Remove the berry Item and Associated Key from the
Dictionary Using Remove()
<script type=”text/jscript” language=”JScript”>
<!--
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
// -->
</script>
Dictionary.RemoveAll()
JScript3.0+
Syntax
dictionaryobj.RemoveAll()
Description
The RemoveAll() method of the Dictionary object removes all key, item pairs from
the dictionary. Nothing is returned from this method.
Example
Listing 14.10 uses RemoveAll() to remove items from the dictionary.
Listing 14.10 Remove All Items from the Dictionary Using RemoveAll()
<script type=”text/jscript” language=”JScript”>
<!--
//Create dictionary.
var fruits = new ActiveXObject(“Scripting.Dictionary”);
// -->
</script>
Drive
JScript3.0+
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1833
Syntax
The core JScript object is created by calling the GetDrive() method of the
FileSystemObject object.
Description
File System Objects (FSO) provide access to properties, methods, and events, using
simple dot notation, to allow you to work with folders and files. A Drive is a file sys-
tem object that provides access to the properties of disk drives and shared networks. A
Drive object is created using the GetDrive() method of the FileSystemObject object.
The properties associated with the Drive object are listed in Table 14.3. For more infor-
mation on file system objects, see the FileSystemObject section in this chapter.
Example
Listing 14.11 creates a Drive object using the GetDrive() method associated with the
FileSystemObject object.
Drive.AvailableSpace
JScript3.0+
Syntax
driveobject.AvailableSpace
Description
The AvailableSpace property of the Drive object contains the amount of space avail-
able to the user on the specified drive or shared network.
Example
Listing 14.12 displays the available space on drive C.
// -->
</script>
Drive.DriveLetter
JScript3.0+
Syntax
driveobject.DriveLetter
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1835
Description
The DriveLetter property of the Drive object contains the drive letter of the local
drive or a shared network.
Example
Listing 14.13 retrieves the drive letter for the specified drive.
Listing 14.13 Display the Drive Letter Using the DriveLetter Property
of the Drive Object
<script type=”text/jscript” language=”JScript”>
<!--
// -->
</script>
Drive.DriveType
JScript3.0+
Syntax
driveobject.DriveType
Description
The DriveType property of the Drive object contains a numeric value indicating the
type of the specified drive. The values associated with the DriveType are listed in Table
14.4.
Example
Listing 14.14 retrieves the drive type for the specified drive.
Listing 14.14 Display the Drive Type Using the DriveType Property of
the Drive Object
<script type=”text/jscript” language=”JScript”>
<!--
// -->
</script
Drive.FileSystem
JScript3.0+
Syntax
driveobject.FileSystem
Description
The FileSystem property of the Drive object contains the type of file system used by
the specified drive
Example
Listing 14.15 retrieves the file system of the specified drive.
Listing 14.15 Display the File System Using the FileSystem Property of
the Drive Object
<script type=”text/jscript” language=”JScript”>
<!--
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1837
// -->
</script>
Drive.FreeSpace
JScript3.0+
Syntax
driveobject.FreeSpace
Description
The FreeSpace property of the Drive object contains the amount of free space, in
bytes, available to the user on the specified drive or shared network.
Example
Listing 14.16 retrieves the free space associated with the C drive
Listing 14.16 Display the Free Space Using the FreeSpace Property of
the Drive Object
<script type=”text/jscript” language=”JScript”>
<!--
Drive.IsReady
JScript3.0+
Syntax
driveobject.IsReady
Description
The IsReady property of the Drive object contains the status of the specified drive. If
the drive is ready, true is returned; otherwise false is returned
Example
Listing 14.17 determines if drive A is ready.
Drive.Path
JScript3.0+
Syntax
driveobject.Path
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1839
Description
The Path property of the Drive object contains the path of the specified file, folder, or
drive.
Example
Listing 14.18 displays drive C’s path.
Listing 14.18 Display the Path of Drive C Using the Path Property of the
Drive Object
<script type=”text/jscript” language=”JScript”>
<!--
// -->
</script>
Drive.RootFolder
JScript3.0+
Syntax
driveobject.RootFolder
Description
The RootFolder property of the Drive object contains a Folder object that represents
the root folder of the specified drive.
Example
Listing 14.19 provides a function that returns the root folder of drive C.
Listing 14.19 Return the Root Folder Using the RootFolder Property of
the Drive Object
function getCRootFolder()
{
//Create a string to hold the drive path.
var drivePath = “C:”;
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1840
Drive.SerialNumber
JScript3.0+
Syntax
driveobject.SerialNumber
Description
The SerialNumber property of the Drive object contains the decimal serial number
that uniquely identifies the specified disk volume.
Example
Listing 14.20 displays the unique serial number of drive C.
Listing 14.20 Displaying the Unique Serial Number of Drive C Using the
SerialNumber Property of the Drive Object
<script type=”text/jscript” language=”JScript”>
<!--
// -->
</script>
Drive.ShareName
JScript3.0+
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1841
Syntax
driveobject.ShareName
Description
The ShareName property of the Drive object contains the network share name for the
specified drive.
Example
Listing 14.21 provides a function that returns the share name of a drive.
Listing 14.21 Return the Share Name Using the ShareName Property of
the Drive Object
function getShareName(drivePath)
{
Drive.TotalSize
JScript3.0+
Syntax
driveobject.TotalSize
Description
The TotalSize property of the Drive object returns the total size of the specified drive
in bytes.
Example
Listing 14.22 shows the total size of the drive.
Listing 14.22 Return the Total Size of Drive Using the TotalSize
Property of the Drive Object
<script type=”text/jscript” language=”JScript”>
<!--
// -->
</script>
Drive.VolumeName
JScript3.0+
Syntax
driveobject. VolumeName
driveobject.VolumeName = newVolumeName
Description
The VolumeName property of the Drive object contains the volume name of the speci-
fied drive. If an equal sign follows this property, the volume name is set to
newVolumeName.
Example
Listing 14.23 provides a function that returns the volume name of a drive.
Listing 14.23 Return the Volume Name Using the VolumeName Property
of the Drive Object
function getVolumeName(drivePath)
{
//Create a file system object.
var fileSysObj = new ActiveXObject(“Scripting.FileSystemObject”);
Drives
JScript3.0+
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1843
Syntax
fileSysObj.Drives
Description
The Drives collection holds a read-only collection of all the available drives. A col-
lection is similar to an array except that an item pointer is used to navigate through the
items in the collection rather than an array index. You can only move the current item
pointer to the first or next element of a collection. Because the Drive object is a col-
lection, the drives can only be accessed by using an Enumerator object. The properties
associated with the Drives object are listed in Table 14.5. For more information on
accessing collections, see the Enumerator object.
Example
Listing 14.24 accesses the number of drives in the Drives collection using the
FileSystemObject and the Drives object count property.
Drives.Count
JScript3.0+
Syntax:
Drives.Count
Description:
The Count property of the Drives collection contains the number of items in the col-
lection.
Example
Listing 14.25 displays the number of items contained in the Drives collection.
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1844
// -->
</script>
Drives.Item()
JScript3.0+
Syntax
new enumeratorobj = Enumerator(Drives)
enumeratorobj.Item(key)
Description
The Item() property returns a drive, specified by key, from the enumerated Drives
collection.
Example
Listing 14.26 begins by creating an Enumerator object to access the Drives collection.
The Item() property is used by the enumerator object to access the letter and type of
each drive.
// -->
</script>
</html>
File
JScript3.0+
Syntax
fileObj = new ActiveXObject(“Scripting.FileSystemObject”);
Description
The File object provides access to all the properties of a file. The File object has spe-
cific properties and methods associated with it, as shown in Table 14.6.
Example
Listing 14.27 shows how to create a new File object.
var myObject, f;
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1846
f = myObject.GetFile(“f:\\test.txt”);
document.write(“The name of the file is: “ + f.Name);
// -->
</script>
File.Attributes
JScript3.0+
Syntax
file.Attributes[newattributes]
Description
The Attributes property is used to determine or set the attributes of a file. This prop-
erty is an array that takes the optional parameter newattributes to set any new attrib-
utes. Attributes can be read/write or read-only. The list of valid attributes is shown in
Table 14.7.
Example
Listing 14.28 retrieves all the file attributes of a fictitious file called test.txt. When
the user clicks the Get Attributes button, the Attributes property is used to retrieve
the properties and display them in an alert box.
<!--
function get()
{
// declare variables.
var myObject, f;
</html>
File.Copy()
JScript3.0+
Syntax
file.Copy(destination, overwrite)
Description
The Copy() method is used to copy a specified file from one location to another. This
method takes two parameters. destination is the location to which to copy the file.
The overwrite argument is an optional Boolean value indicating whether to overwrite
an existing file of the same name should one exist.
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1848
Example
Listing 14.29 uses the Copy() method to copy the fictitious test.txt file to
“testcopy.txt”.
function copy()
{
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
f = myObject.GetFile(“c:\\test.txt”);
<form name=”myForm”>
<input type=”Button” value=”Copy” onClick=’copy()’>
</form>
</html>
File.DateCreated
JScript3.0+
Syntax
file.DateCreated
Description
The DateCreated property is used to get the date when the file was created.
Example
Listing 14.30 shows how to use to DateCreated property to get the creation date of the
test.txt file.
<form name=”myForm”>
<input type=”Button” value=”Get Date” onClick=’get()’>
</form>
</html>
File.DateLastAccessed
JScript3.0+
Syntax
file.DateLastAccessed
Description
The DateLastAccessed property is used to find out the last date when the file was
accessed.
Example
Listing 14.31 shows how the DateLastAccessed property is used to retrieve the date
when the test.txt file was last accessed.
// Inform the user of the date when the file was last accessed.
alert (“The date this file was last accessed is: “ + date);
}
//-->
</script>
<form name=”myForm”>
<input type=”Button” value=”Get Date” onClick=’get()’>
</form>
</html>
File.DateLastModified
JScript3.0++
Syntax
file.DateLastModified
Description
The DateLastModified property returns the date when the file was last modified.
Example
Listing 14.32 shows how the DateLastModified property is used to retrieve the date
when the test.txt file was last modified.
// Inform the user of the date when the file was last modified.
alert (“The date this file was last modified is: “ + date);
}
//-->
</script>
<form name=”myForm”>
<input type=”Button” value=”Get Date” onClick=’get()’>
</form>
</html>
File.Delete
JScript3.0+
Syntax
file.Delete()
Description
The Delete()method is used to delete a specified file.
Example
Listing 14.33 shows how to delete a file using the Delete() method.
var f = myObject.GetFile(“c:\\mytest.txt”);
f.Delete();
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1852
<form name=”myForm”>
<input type=”Button” value=”Delete File” onClick=’remove()’>
</form></html>
File.Drive
JScript3.0++
Syntax
file.Drive
Description
The Drive property returns the drive letter of the drive on which the specified file or
folder resides.
Example
Listing 14.34 shows how the Drive property is used to get the letter of the drive that
contains the specified file.
// Function gets the drive letter on which the file resides and
// then informs the user of the drive.
function get()
{
var myObject, f, d;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
f = myObject.GetFile(“c:\\test.txt”);
d = f.drive;
alert(“The drive that test.txt resides is: “ + d);
}
//-->
</script>
<form name=”myForm”>
<input type=”Button” value=”Get Drive” onClick=’get()’>
</form>
</html>
File.Move()
JScript3.0+
Syntax
file.Move(destination)
Description
The Move method is used to move a file from one location to another. This method takes
a single parameter, destination, which represents the location to which the file is to
be moved.
Example
Listing 14.35 uses the Move() method to move the test.txt file from the “C:\\”
directory to the “C:\\mydir\\” directory.
Press the button to move the file test.txt into the mydir directory.<br>
<form name=”myForm”>
<input type=”Button” value=”Move File” onClick=’move()’>
</form>
</html>
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1854
File.Name
JScript3.0++
Syntax
file.Name
Description
The Name property is used to either set or retrieve the name of a file object.
Example
Listing 14.36 uses the Name property to retrieve the filename (test.txt) and display it
in an alert box.
</html>
File.OpenAsTextStream()
JScript3.0+
Syntax
file.OpenAsTextStream(iomode, format)
Description
The OpenAsTextStream method is used to open a specified text stream that can be used
to read or write to a file. This method takes two optional parameters. The first parame-
ter, iomode, specifies the mode for the file. Valid modes are ForReading, ForWriting,
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1855
and ForAppending as shown in Table 14.8. The second parameter, format, specifies the
format of the file. The default value is ASCII: However you can have one of the three
settings shown in Table 14.9.
Example
Listing 14.37 uses the OpenAsTextStream method to open a stream to the file test.txt
in ASCII mode and then write a string to it.
function open()
{
var myObject, f, text;
<form name=”myForm”>
<input type=”Button” value=”open a filestream” onClick=’open()’>
</form>
</html>
File.ParentFolder
JScript3.0++
Syntax
file.ParentFolder
Description
The ParentFolder property is used to determine the parent folder from which the file
was obtained.
Example
Listing 14.38 shows how the ParentFolder property is used.
</html>
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1857
File.Path
JScript3.0++
Syntax
file.Path
Description
The Path property is used to get the path for a specified file.
Example
Listing 14.39 shows an example of the Path property.
<form name=”myForm”>
<input type=”Button” value=”Get Path” onClick=’getPath()’>
</form>
</html>
File.ShortName
JScript3.0++
Syntax
file.ShortName
Description
The ShortName property returns the short name used by programs that require the ear-
lier 8.3 naming convention.
26 0672321416 CH14a 7/30/01 1:53 PM Page CD:1858
Example
Listing 14.40 shows how to access the short name of the file.
<form name=”myForm”>
<input type=”Button” value=”Get Shortname” onClick=’get()’>
</form>
</html>
File.ShortPath
JScript3.0++
Syntax
file.ShortPath
Description
The ShortPath property returns the short path used by programs that require the ear-
lier 8.3 naming convention.
Example
Listing 14.41 shows how to get the short path for the specified file.
<form name=”myForm”>
<input type=”Button” value=”Get Shortpath” onClick=’get()’>
</form>
</html>
File.Size
JScript3.0++
Syntax
file.Size
Description
The Size property returns the size of the specified file.
Example
In Listing 14.42, the Size property is used to get the file size.
</html>
File.Type
JScript3.0++
Syntax
file.Type
Description
The Type property is used to get information pertaining to the type of file.
Example
Listing 14.43 shows an example of how the Type property is used to return the type of
the myTest.txt file.
<form name=”myForm”>
<input type=”Button” value=”Get File Type” onClick=’get()’>
</form>
</html>
27 0672321416 CH14b 7/30/01 1:56 PM Page CD:1861
Files
JScript3.0+
Syntax
Core JScript Collection of File objects.
Description
The Files object represents a collection of files in a folder. The Files object has spe-
cific properties and methods associated with it, which are shown in Table 14.10.
Example
Listing 14.44 shows how to create a new Files object.
<script language=”JScript”>
<!--
// -->
</script>
27 0672321416 CH14b 7/30/01 1:56 PM Page CD:1862
</body>
to </html>
Files.Count
JScript2.0+
Syntax
files.Count
Description
The Count property returns the number of items in the Files collection.
Example
Listing 14.45 shows how to use the Count property to get the number of items in the
Files collection.
<script language=”JScript”>
<!--
// -->
</script>
<body>
<form name=”myForm”>
</body>
</html>
Files.Item
JScript2.0+
Syntax
files.Item
Description
The Item property sets or returns an item based on a specified key in a collection of
files.
Example
Listing 14.46 shows how to use the Item property.
<script language=”JScript”>
<!--
<body>
<form name=”myForm”>
Enter the name of a folder which contains files.
<input type=”text” size=”35” name=”file”>
<br><br>
<input type=”Button” value=”Get File Item”
➥onClick=’getItem(document.form1.file.value)’>
</form>
</body>
</html>
FileSystemObject
JScript3.0+
Syntax
Core JScript object created by calling the ActiveXObject() method passing
Scripting.FileSystemObject.
Description
The FileSystemObject object provides access to the computer’s file system. The
FileSystemObject object has specific properties and methods associated with it,
which are shown in Table 14.11.
Property/Method Description
DriveExists() Determines whether a drive exists
Drives Returns a Drives collection, containing all the available
drive objects
FileExists() Determines whether a file exists
FolderExists() Determines whether a folder exists
GetAbsolutePathName() Returns the absolute pathname for a file
GetBaseName() Gets the base name of the last component
GetDrive() Gets the drive letter for a file
GetDriveName() Gets the drive name on which a file resides
ExtensionName() Returns the extension for a file
GetFile() Gets the file object
GetFileName() Gets the name of a file
GetFolder() Gets the folder name that contains a file
GetParentFolderName() Gets the parent folder’s name
GetSpecialFolder() Gets the folder names for special folders
GetTempName() Creates a randomly generated temporary file
MoveFile() Moves a file from one location to another
MoveFolder() Moves a folder and its contents from one location to
another
OpenTextFile() Opens a text file stream to a file
Example
Listing 14.47 shows how to create a new FileSystemObject object.
<script language=”JScript”>
<!--
// -->
</script>
</html>
FileSystemObject.BuildPath()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1866
Syntax
filesystemobject.BuildPath(path, name)
Description
The BuildPath() method is used to append a name to an existing path. A separator is
inserted between the existing path and the appended name if necessary.
Example
Listing 14.48 shows how to use the BuildPath() method.
<script language=”JScript”>
<!--
function GetNewPath(path)
{
var myObject, newpath;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
newpath = myObject.BuildPath(path, “\\newstuff”);
alert(“The result is: “ + newpath);
}
// -->
</script>
<body>
<form name=”myForm”>
<input type=”Button” value=”Build Path” onClick=’GetNewPath(“c:\\tmp”)’>
</form>
</body>
</html>
FileSystemObject.CopyFile
JScript3.0+
Syntax
filesystemobject.CopyFile(source, destination, overwrite)
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1867
Description
The CopyFile() method is used to copy one or more files to a specified directory. This
method takes three parameters. The first parameter, source, is a string specifying the
source path and filename from which to copy. The second parameter, destination, is
a string specifying the destination path and filename to which to copy. The final para-
meter, overwrite, is an optional parameter. It represents a Boolean value indicating
whether to overwrite an existing file.
Example
Listing 14.49 shows how to copy a file from one location to another.
<script language=”JScript”>
<!--
function copy()
{
var myObject, newpath;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// Copies file test.txt from the root C drive to the tmp folder.
myObject.CopyFile (“c:\\test.txt”, “c:\\tmp\\myTest.txt”);
}
// -->
</script>
<body>
Copy “c:\test.txt” to the existing path: “c:\tmp\myTest.txt”
<form name=”myForm”>
<input type=”Button” value=”Copy File” onClick=’copy()’>
</form>
</body>
</html>
FileSystemObject.CopyFolder()
JScript3.0+
Syntax
filesystemobject.CopyFolder(source, destination, overwrite)
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1868
Description
The CopyFolder() method copies a folder from a source to a destination. This method
takes three parameters. The first parameter, source, is a string specifying the source
path and filename from which to copy. Wildcards can be used to copy more than one
folder. The second parameter, destination, is a string specifying the destination path
and filename to which to copy. The final parameter, overwrite, is an optional parame-
ter. It represents a Boolean value indicating whether to overwrite an existing file.
Example
Listing 14.50 shows how to use the CopyFolder() method. A new FileSystemObject
is created, providing access to the computer’s file system. It is then used to copy all the
contents of the folder tmp to newtmp. The * specifies that all the contents of tmp are to
be copied.
<script language=”JScript”>
<!--
// -->
</script>
<body>
Copy Folder “c:\tmp” to the folder “c:\newtmp”
<form name=”myForm”>
<input type=”Button” value=”Copy Folder” onClick=’copy()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1869
FileSystemObject.CreateFolder()
JScript3.0+
Syntax
filesystemobject.CreateFolder(name)
Description
The CreateFolder() method is used to create a new folder. This method takes the name
parameter, which is a string specifying the folder name to create.
Example
Listing 14.51 shows how to use the CreateFolder() method.
<script language=”JScript”>
<!--
// -->
</script>
<body>
Create Folder: “c:\newtmp”
<form name=”myForm”>
<input type=”Button” value=”Click to Create New Folder” onClick=’create()’>
</form>
</body>
</html>
FileSystemObject.CreateTextFile()
JScript2.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1870
Syntax
filesystemobject.CreateTextFile(filename, overwrite, unicode)
Description
The CreateTextFile()method is used to create a new text file. This method takes two
parameters. The first parameter, filename, is a string specifying the name of the file to
create, whereas the second parameter, overwrite, is a Boolean value indicating
whether to overwrite an existing file. A third parameter, unicode, is an optional para-
meter that indicates whether the file should be created as Unicode or ASCII. It is a
Boolean value with a default value of false. To create a file as Unicode, set this value
to true.
Example
Listing 14.52 shows how to use the CreateTextFile() method. An instance of the
FileSystemObject is created, which in turn uses the CreateTextFile() method to
create the file testing.txt.
<script language=”JScript”>
<!--
// -->
</script>
<body>
Create Text file “testing.txt”
<form name=”myForm”>
<input type=”Button” value=”Click to Create New File” onClick=’createFile()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1871
FileSystemObject.DeleteFile()
JScript3.0+
Syntax
filesystemobject.DeleteFile(filename, force)
Description
The DeleteFile() method is used to delete an existing file. An instance of the
FileSystemObject is created, which uses the DeleteFile() method to remove the file
testing.txt. This method takes two parameters. The first parameter, filename, is a
string specifying the name of the file to delete, whereas force is a Boolean value indi-
cating whether a file that has read-only permissions can be deleted.
Example
Listing 14.53 shows how to delete a file.
<script language=”JScript”>
<!--
// -->
</script>
<body>
Delete Text file “testing.txt”
<form name=”myForm”>
<input type=”Button” value=”Click to Delete File” onClick=’deleteFile()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1872
FileSystemObject.DeleteFolder()
JScript3.0+
Syntax
filesystemobject.DeleteFolder(foldername, force)
Description
The DeleteFolder() method is used to remove an existing folder and all its contents.
This method takes two parameters. The first parameter, foldername, is a string speci-
fying the name of the folder to delete, whereas force is a Boolean value indicating
whether a file that has read-only permissions can be deleted.
Example
Listing 14.54 shows how the DeleteFolder() method is used. An instance of the
FileSystemObject is created, which uses the DeleteFolder() method to remove the
folder newtmp.
<script language=”JScript”>
<!--
// -->
</script>
<body>
Delete Folder: “newtmp”
<form name=”myForm”>
<input type=”Button” value=”Click to Delete Folder” onClick=’deleteFolder()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1873
FileSystemObject.DriveExists()
JScript3.0+
Syntax
filesystemobject.DriveExists (letter)
Description
The DriveExists() method is used to determine whether a drive exists. This method
takes letter as a parameter, which specifies a drive letter to look for.
Example
Listing 14.55 shows how to check for the existence of a D drive.
<script language=”JScript”>
<!--
// -->
</script>
<body>
Check for drive “D”
<form name=”myForm”>
<input type=”Button” value=”Check drive” onClick=’checkDrive()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1874
FileSystemObject.Drives
JScript3.0+
Syntax
filesystemobject.Drives
Description
The Drives collection holds all the Drive objects. It is used to get an object consisting
of all the drives.
Example
Listing 14.56 shows how to check for drives.
<script language=”JScript”>
<!--
function getdrive()
{
var myObject, drive, e;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
drive = myObject.Drives;
// -->
</script>
<body>
<form name=”myForm”>
<input type=”Button” value=”Get Drive Name” onClick=’getdrive()’>
</form>
</body>
</html>
FileSystemObject.FileExists()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1875
Syntax
filesystemobject.FileExists(filename)
Description
The FileExists() method is used to determine whether a file exists on the current sys-
tem. This method takes filename as its only parameter, which represents the name of
the file to check.
Example
Listing 14.57 shows how to use the FileExists() method to check to see whether the
file test.txt exists.
<script language=”JScript”>
<!--
function checkfile()
{
var myObject;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Check for file “test.txt”
<form name=”myForm”>
<input type=”Button” value=”Check file” onClick=’checkfile()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1876
FileSystemObject.FolderExists()
JScript3.0+
Syntax:
filesystemobject.FolderExists(foldername)
Description
The FolderExists() method is used to determine whether a specified folder exists on
the current system. This method takes foldername as its only parameter, which repre-
sents the name of folder to check.
Example
Listing 14.58 shows an example of how to determine whether the tmp folder exists on
a specific drive.
<script language=”JScript”>
<!--
function checkfolder()
{
var myObject;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Check for folder “tmp” on the C drive
<form name=”myForm”>
<input type=”Button” value=”Check Folder” onClick=’checkfolder()’>
</form>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1877
</body>
</html>
FileSystemObject.GetAbsolutePathName()
JScript3.0+
Syntax
filesystemobject.GetAbsolutePathName()
Description
The GetAbsolutePathName() method returns a complete and unambiguous path from
a provided path specification.
Example
Listing 14.59 shows how to use the GetAbsolutePathName() method.
<script language=”JScript”>
<!--
// -->
</script>
<body>
Get the Absolute Path for C:\
<form name=”myForm”>
<input type=”Button” value=”Get Absolute Path” onClick=’getpath()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1878
FileSystemObject.GetBaseName()
JScript3.0+
Syntax
filesystemobject.GetBaseName(path)
Description
The GetBaseName() method returns a string containing the base name of a file or
folder, without any extension, in a path.
Example
Listing 14.60 shows how the GetBaseName() method is used.
<script language=”JScript”>
<!--
// -->
</script>
<body>
<form name=”myForm”>
<input type=”Button” value=”Get Base” onClick=’get()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1879
FileSystemObject.GetDrive()
JScript3.0+
Syntax
filesystemobject.GetDrive(drive)
Description
The GetDrive() method is used to determine the drive specified in the drive parame-
ter. This method takes drive as its only parameter, which represents the letter of drive
for which to get information.
Example
Listing 14.61 shows how the GetDrive() method is used.
<script language=”JScript”>
<!--
function getdrive()
{
var myObject, drive;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
drive = myObject.GetDrive(“c:\\”)
alert(“Drive Name of drive C is: “ + drive.VolumeName);
}
// -->
</script>
<body>
Get the name for Drive C.
<form name=”myForm”>
<input type=”Button” value=”Get Drive Name” onClick=’getdrive()’>
</form>
</body>
</html>
FileSystemObject.GetDriveName()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1880
Syntax
filesystemobject.GetDriveName(letter)
Description
The GetDriveName() method is used to get the name of a specified drive. This method
takes drive as its only parameter, which represents the letter of drive for which to get
the name.
Example
Listing 14.62 shows how the GetDriveName() method is used. An instance of the
FileSystemObject is created and then used to get the name of the C drive.
<script language=”JScript”>
<!--
function getdrive()
{
var myObject, drive;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Get the name for Drive C.
<form name=”myForm”>
<input type=”Button” value=”Get Drive Name” onClick=’getdrive()’>
</form>
</body>
</html>
FileSystemObject.GetExtensionName()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1881
Syntax
filesystemobject.GetExtensionName(path)
Description
The GetExtensionName() method is used to get the file extension name for a specified
file. This method takes path as its only parameter, which represents the full path to the
file.
Example
Listing 14.63 shows how the GetExtensionName() method is used. An instance of the
FileSystemObject is created and then used to get the extension name of the specified
file type.
<script language=”JScript”>
<!--
// Gets the extension name for the file and informs the user
// of the results.
function getExt()
{
var myObject, ext;
// Creates an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Get the extension for the file “testing.txt”.
<form name=”myForm”>
<input type=”Button” value=”Get Extension” onClick=’getExt()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1882
FileSystemObject.GetFile()
JScript3.0+
Syntax
filesystemobject.GetFile()
Description
The GetFile() method is used to get a specified file object.
Example
Listing 14.64 shows how you can use the GetFile() method to get the size of a file.
<script language=”JScript”>
<!--
function getsize()
{
var myObject, afile, size;
// Creates an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
afile = myObject.GetFile(“c:\\test.txt”)
// -->
</script>
<body>
Get the size for the file “test.txt”
<form name=”myForm”>
<input type=”Button” value=”Get Size” onClick=’getsize()’>
</form>
</body>
</html>
FileSystemObject.GetFileName()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1883
Syntax
filesystemobject.GetFileName(filename)
Description
The GetFileName() method is used to get a specified filename. This method takes
filename as its only parameter, which represents the absolute or relative path to the
file.
Example
Listing 14.65 shows how the GetFileName() property is used.
<script language=”JScript”>
<!--
function getname()
{
var myObject, name;
// Creates an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Get the name value for the file “test.txt”
<form name=”myForm”>
<input type=”Button” value=”Get File Name” onClick=’getname()’>
</form>
</body>
</html>
FileSystemObject.GetFolder()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1884
Syntax
filesystemobject.GetFolder()
Description
The GetFolder() method is used to get the specified folder object.
Example
Listing 14.66 shows how to retrieve a folder object. An instance of the
FileSystemObject is created and then used to get a folder name. Then the
DateLastAccessed property is applied to the folder object to get the actual date that the
folder was last accessed. The result is then returned to the user.
<script language=”JScript”>
<!--
// Function gets the folder object and then checks the date.
// Property that identifies when the folder was last accessed.
function getfolder()
{
var myObject, afolder, date;
// Creates an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Get the date that the folder “tmp” was last accessed.
<form name=”myForm”>
<input type=”Button” value=”Get Folder Date” onClick=’getfolder()’>
</form>
</body>
</html>
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1885
FileSystemObject.GetParentFolderName()
JScript3.0+
Syntax
filesystemobject.GetParentFolderName(foldername)
Description
The GetParentFolderName() method is used to get the name of the parent folder for a
specified file or folder. This method takes foldername as its only parameter, which rep-
resents the path for the name of the subfolder.
Example
Listing 14.67 shows how to get the name for the parent folder.
<script language=”JScript”>
<!--
function getparent()
{
var myObject, name;
// Creates an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
name = myObject.GetParentFolderName(“c:\\tmp\\subfolder”);
alert(“The parent folder name is:” + name);
}
// -->
</script>
<body>
Get the parent folder name for “subfolder” folder.
<form name=”myForm”>
<input type=”Button” value=”Get Parent Folder” onClick=’getparent()’>
</form>
</body>
</html>
FileSystemObject.GetSpecialFolder()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1886
Syntax
filesystemobject.GetSpecialFolder(num)
Description
The GetSpecialFolder() method is used to get the special folder object specified.
This method takes num as its only parameter, which represents one of the following val-
ues:
• 0—Windows folder
• 1—System folder
• 2—Temporary folder
Example
Listing 14.68 shows how the GetSpecialFolder() method is used to get the
Temporary folder.
<script language=”JScript”>
<!--
function get()
{
var myObject, name;
// Creates an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
name = myObject.GetSpecialFolder(2);
alert(“The folder is a temporary folder” + name);
}
// -->
</script>
<body>
Check to see if the folder “Temp” is a temporary folder.
<form name=”myForm”>
<input type=”Button” value=”Get Special Folder” onClick=’get()’>
</form>
</body>
</html>
FileSystemObject.GetTempName()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1887
Syntax
filesystemobject.GetTempName()
Description
The GetTempName() method is used to get a randomly generated temporary file or
folder.
Example
Listing 14.69 shows how the GetTempName() method is used. An instance of the
FileSystemObject is created and then used to get the name of a randomly generated
temporary file.
<script language=”JScript”>
<!--
function get()
{
var myObject, name;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Get a temp file.
<form name=”myForm”>
<input type=”Button” value=”Get Temp Name” onClick=’get()’>
</form>
</body>
</html>
FileSystemObject.MoveFile()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1888
Syntax
filesystemobject.MoveFile(source, destination)
Description
The MoveFile() method is used to move a file from a source to a destination. This
method takes two parameters. The first parameter, source, is the location of the file to
be moved, whereas the second parameter, destination, is the new location of the
moved file.
Example
Listing 14.70 shows how the MoveFile() method is used. An instance of the
FileSystemObject is created and then used to move test.txt from the root directory
on the C drive to the tmp folder.
<script language=”JScript”>
<!--
function move()
{
var myObject;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Move the file “test.txt” from c:\ to c:\tmp
<form name=”myForm”>
<input type=”Button” value=”Move file” onClick=’move()’>
</form>
</body>
</html>
FileSystemObject.MoveFolder()
JScript3.0+
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1889
Syntax
filesystemobject.MoveFolder()
Description
The MoveFolder() method is used to move one or more folders from one location to
another.
Example
Listing 14.71 shows how the MoveFolder() method is used. An instance of the
FileSystemObject is created and then used to move the subtmp folder to the root
directory on the C drive.
<script language=”JScript”>
<!--
function move()
{
var myObject;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// Folder is moved.
myObject.MoveFolder(“c:\\tmp\\subtmp”, “c:\\”);
}
// -->
</script>
<body>
Move the folder “subtmp” from c:\tmp\subtmp to c:\
<form name=”myForm”>
<input type=”Button” value=”Move folder” onClick=’move()’>
</form>
</body>
</html>
FileSystemObject.OpenTextFile()
JScript2.0+
Syntax
filesystemobject.OpenTextFile(filename, iomode, create, format)
27 0672321416 CH14b 7/30/01 1:57 PM Page CD:1890
Description
The OpenTextFile() method is used to open a text stream object to a specified file,
which can be used to read and write from that file. This method takes four parameters.
The first parameter, filename, is the name of the file to be created. The second para-
meter, iomode, is an optional parameter indicating the mode of the file. The third para-
meter, create, is an optional Boolean value parameter indicating whether the file can
be created if it doesn’t exist. And the final parameter, format, is an optional parameter
indicating the format of the opened file. The default is ASCII.
Example
Listing 14.72 shows how the OpenTextFile() method is used. An instance of the
FileSystemObject is created and then used to open a text stream to the file dummy.txt.
The file is opened in append mode.
<script language=”JScript”>
<!--
function open()
{
var myObject, afile;
// Create an instance of the FileSystemObject.
myObject = new ActiveXObject(“Scripting.FileSystemObject”);
// -->
</script>
<body>
Open a text stream for the file dummy.txt
<form name=”myForm”>
<input type=”Button” value=”Open File” onClick=’open()’>
</form>
</body>
</html>
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1891
Folder
JScript3.0+
Syntax
Core JScript object created by calling the GetFolder() method of the
FileSystemObject object.
Description
The Folder object, when created, provides access to all the properties of a folder. This
object is created by using the GetFolder() method of the FileSystemObject object.
The folder passed is the name the folder for which you want to create a JScript object.
Table 14.12 contains a list of methods and properties of the Folder object.
Example
Listing 14.73 creates an instance of the FileSystemObject object, and then creates an
instance of the Folder object. The drive letter of the folder instance is written to the
user’s page if this script is run in a browser window.
</script>
Folder.Attributes
JScript3.0+
Syntax
folder.Attributes
folder.Attributes = attrib
Description
The Attributes property of an instance of the Folder object is used to set or retrieve
the attributes of a folder. If the property is called, as in the first syntactical definition,
you can retrieve the current attributes of the folder. If you set the property equal to
attrib, you are able to set new attributes. Table 14.13 has the values of the attributes.
Example
In Listing 14.74 when the button is clicked, an alert box pops up displaying the
attribute setting of the folder specified in the script. See the entry for File.Attributes
for a more detailed example.
function get(){
</script>
</head>
<body>
<form name=”myForm”>
<input type=”Button” value=”Get Attributes” onClick=’get()’>
</form>
</body>
</html>
Folder.Copy()
JScript3.0+
Syntax
folder.Copy(destination)
folder.Copy(destination, boolean)
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1894
Description
The Copy() method is used to copy a specified folder from one location to another. The
destination specified is the location to which to copy the folder. If boolean is set to
true and a folder exists in the destination location, the copy will overwrite the folder.
Example
Listing 14.75 creates an instance of the Folder object, and then makes a copy using the
Copy() method. If the new folder already exists, it will be overwritten.
Folder.DateCreated
JScript3.0+
Syntax
folder.DateCreated
Description
The DateCreated property of an instance of the Folder object is used to get the date
when the folder was created.
Example
Listing 14.76 can be run in an Internet Explorer browser, and it contains a single but-
ton. When the button is clicked, an alert box pops up displaying the creation date of the
folder specified.
function get(){
</script>
<head>
<body>
<form name=”myForm”>
<input type=”Button” value=”Get Date” onClick=’get()’>
</form>
</body>
</html>
Folder.DateLastAccessed
JScript3.0+
Syntax
folder.DateLastAccessed
Description
The DateLastAccessed property of an instance of the Folder object is used to get the
date the folder was last accessed.
Example
Listing 14.77 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the date the folder was last
accessed.
function get(){
</script>
</head>
<body>
Get the date the c:\temp folder was last accessed.
<form name=”myForm”>
<input type=”Button” value=”Get Last Access” onClick=’get()’>
</form>
</body>
</html>
Folder.DateLastModified
JScript3.0+
Syntax
folder.DateLastModified
Description
The DateLastModified property of an instance of the Folder object is used to get the
date the folder was last modified.
Example
Listing 14.78 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the date the folder was last
modified.
function get(){
</script>
</head>
<body>
Get the date the c:\temp folder was last modified.
<form name=”myForm”>
<input type=”Button” value=”Get Last Modified” onClick=’get()’>
</form>
</body>
</html>
Folder.Delete()
JScript3.0+
Syntax
folder.Delete(boolean)
folder.Delete()
Description
The Delete() method of an instance of the Folder object is used to delete a specified
folder. The optional boolean parameter the method takes will cause the method to
delete all read-only files and folders in the folder if set to true.
Example
Listing 14.79 deletes the specified folder.
Folder.Drive
JScript3.0+
Syntax
folder.Drive
Description
The Drive property of an instance of the Folder object returns the drive letter of the
folder.
Example
Listing 14.80 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the drive on which the
folder is located.
function get(){
</script>
</head>
<body>
<form name=”myForm”>
<input type=”Button” value=”Get Drive” onClick=’get()’>
</form>
</body>
</html>
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1899
Folder.Files
JScript3.0+
Syntax
folder.Files
Description
The Files property of an instance of the Folder object returns a collection consisting
of all the File objects contained in the folder. This includes hidden and system files.
Example
Listing 14.81 creates and instance of the Folder object, and then creates an instance of
the Enumerator object to access the collection of files contained in the Files property.
If this example is loaded in a browser, each of the files contained in the folder will be
written to the page.
</script>
Folder.IsRootFolder
JScript3.0+
Syntax
folder.IsRootFIsRootFolder
Description
The older property of an instance of the Folder object, evaluates to true if the folder
is the root folder, and false otherwise.
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1900
Example
Listing 14.82 creates an instance of the Folder object, and then checks to see if it is
the root folder. If this example is loaded in a browser, a string will be written to the
user’s page stating whether the folder is the root folder.
</script>
Folder.Move()
JScript3.0+
Syntax
folder.Move(destination)
Description
The Move() method is used to move a specified folder from one location to another.
The destination specified is the location to which to move the folder.
Example
Listing 14.83 creates an instance of the Folder object, and then moves it by using the
Move() method.
Folder.Name
JScript3.0+
Syntax
folder.Name
Description
The Name property of an instance of the Folder object is used to either set or get the
name of the folder.
Example
Listing 14.84 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the name of the folder.
function get(){
</script>
</head>
<body>
Get the name of the c:\temp folder.
<form name=”myForm”>
<input type=”Button” value=”Get Name” onClick=’get()’>
</form>
</body>
</html>
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1902
Folder.ParentFolder
JScript3.0+
Syntax
folder.ParentFolder
Description
The ParentFolder property of an instance of the Folder object is used to return a new
Folder object for the parent folder.
Example
Listing 14.85 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the name of the parent
folder.
function get(){
</script>
</head>
<body>
Get the name of the c:\temp parent folder.
<form name=”myForm”>
<input type=”Button” value=”Get Parent Folder” onClick=’get()’>
</form>
</body>
</html>
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1903
Folder.Path
JScript3.0+
Syntax
folder.Path
Description
The Path property of an instance of the Folder object returns the full path to the folder.
Example
Listing 14.86 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the path of the folder.
function get(){
</script>
</head>
<body>
Get the path of the c:\temp folder.
<form name=”myForm”>
<input type=”Button” value=”Get Path” onClick=’get()’>
</form>
</body>
</html>
Folder.ShortName
JScript3.0+
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1904
Syntax
folder.ShortName
Description
The ShortName property of an instance of the Folder object returns the “8.3” name (an
eight-character name, followed by a dot, ., and completed with a three-character exten-
sion) of the folder.
Example
Listing 14.87 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the short name of the
folder.
function get(){
</script>
</head>
<body>
<form name=”myForm”>
<input type=”Button” value=”Get Short Name” onClick=’get()’>
</form>
</body>
</html>
Folder.ShortPath
JScript3.0+
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1905
Syntax
folder.ShortPath
Description
The ShortPath property of an instance of the Folder object returns the “8.3” path (an
eight-character name, followed by a dot, ., and completed with a three-character exten-
sion) to the folder.
Example
Listing 14.88 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the short path to the folder.
function get(){
</script>
</head>
<body>
Get the short path of the “c:\\Program Files” folder.
<form name=”myForm”>
<input type=”Button” value=”Get Short Path” onClick=’get()’>
</form>
</body>
</html>
Folder.Size
JScript3.0+
Syntax
folder.Size
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1906
Description
The Size property of an instance of the Folder object returns the byte size of the
folder.
Example
Listing 14.89 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the byte size of the folder.
function get(){
</script>
</head>
<body>
Get the size of the “c:\\Program Files” folder.
<form name=”myForm”>
<input type=”Button” value=”Get Size” onClick=’get()’>
</form>
</body>
</html>
Folder.SubFolders
JScript3.0+
Syntax
folder.SubFolders
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1907
Description
The SubFolders property of an instance of the Folder object returns a collection con-
sisting of all the Folder objects contained in the folder. This includes hidden and sys-
tem folders.
Example
Listing 14.90 creates an instance of the Folder object, and then creates an instance of
the Enumerator object to access the collection of folders contained in the Folders
property. If this example is loaded in a browser, the names of each of the folders con-
tained in the folder will be written to the page.
</script>
Folder.Type
JScript3.0+
Syntax
folder.Type
Description
The Type property of an instance of the Folder object returns the type of the folder. For
a folder, the return value is File Folder.
Example
Listing 14.91 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the type of the folder.
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1908
function get(){
</script>
</head>
<body>
Get the type of the “c:\\Program Files” folder.
<form name=”myForm”>
<input type=”Button” value=”Get Type” onClick=’get()’>
</form>
</body>
</html>
Folders
JScript3.0+
Syntax
Core JScript Collection of Folder objects.
Description
The Folders collection holds a read-only collection of all the available folders. A col-
lection is similar to an array except that an item pointer is used to navigate through the
items in the collection rather than an array index. As you would with arrays, you can
only move the current item pointer to the first or next element of a collection. Because
the Folder object is a collection, the folders can only be accessed by using an
Enumerator object. The properties associated with the Folders collection are listed in
Table 14.14. For more information on accessing collections, see the Enumerator sec-
tion in this chapter.
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1909
Example
Listing 14.92 accesses the Folders collection by using FileSystemObject.
Folders.Add()
JScript3.0+
Syntax
folderscollection.Add(foldername)
Description
The Add() method of the Folders collection is used to add folders to the collection.
This can be used to create new folders on the file system.
Example
Listing 14.93 creates a test folder inside the \temp folder on the file system. This
script can be executed by using the Windows Script Host (wscript.exe or
cscript.exe). Be sure that you are on a drive that contains a folder named temp, and
make sure that there is no folder named test already present. Not doing so will result
in an error.
Folders.Count
JScript3.0+
Syntax
folderscollection.Count
Description
The Count property of the Folders collection returns the number of folders in the col-
lection. Folders are added to this collection by using the Folders.Add() method.
Example
Listing 14.94 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the number of folders in
the Folders collection.
function get(){
// Create two instances of the Folder object for the “temp” folder.
var myFolder = myFileSysObj.GetFolder(“c:\\Temp”);
</script>
</head>
<body>
Get the count of the c:\temp Folders collection.
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1911
<form name=”myForm”>
<input type=”Button” value=”Get Count” onClick=’get()’>
</form>
</body>
</html>
Folders.Item
JScript3.0+
Syntax
folderscollection.Item(foldername)
Description
The Item property of an instance of the Folders collection returns foldername folder.
Example
Listing 14.95 is run in an Internet Explorer browser, and it contains a single button.
When the button is clicked, an alert box pops up displaying the second folder added to
the Folders collection.
function get(){
// Create two instances of the Folder object for the “temp” folder.
var myFolder = myFileSysObj.GetFolder(“c:\\Temp”);
}
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1912
<form name=”myForm”>
<input type=”Button” value=”Get Item” onClick=’get()’>
</form>
</body>
</html>
TextStream
JScript2.0+
Syntax
Core JScript object created by calling the CreateTextFile() method of the
FileSystemObject object.
Description
The TextStream object is created by calling the CreateTextFile() method of an
instance of the FileSystemObject. An instance of the TextStream object is created by
calling the CreateTextFile() method of the FileSystemObject object.
Table 14.15 contains a list of methods and properties of the TextStream object.
Example
Listing 14.96 creates an example of the TextStream object, and then writes a string to
the file. After the string has been written, the stream is closed. This file can be executed
with the Windows Script Host (wscript.exe or cscript.exe).
TextStream.AtEndOfLine
JScript2.0+
Syntax
textstream.AtEndOfLine
Description
The AtEndOfLine property of the TextStream object returns true when the end of a
line in a text line is found.
Example
Listing 14.97 opens two files. The first file is for reading a string from, whereas the
second file is written to—one character at a time—as the script iterates through. The
result is that the first line of the file opened for reading is written to the second file.
This file can be executed with the Windows Script Host (wscript.exe or
cscript.exe).
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1914
Listing 14.97 Using the AtEndOfLine Property to Find the End of the First
Line in a File
// Create a FileSystemObject object.
var myFileSysObj = new ActiveXObject(“Scripting.FileSystemObject”);
TextStream.AtEndOfStream
JScript2.0+
Syntax
textstream.AtEndOfStream
Description
The AtEndOfStream property of the TextStream object returns true when the end of a
file in a text file is found.
Example
Listing 14.98 opens two files. The first file is for reading a string from, whereas the sec-
ond file is written to—one character at a time—as the script iterates through. The result
is that the file opened for reading is written to the second file. This file can be executed
with the Windows Script Host (wscript.exe or cscript.exe).
Listing 14.98 Using the AtEndOfStream Property to Find the End of the
File
// Create a FileSystemObject object.
var myFileSysObj = new ActiveXObject(“Scripting.FileSystemObject”);
TextStream.Close()
JScript2.0+
Syntax
textstream.Close()
Description
The Close() method of the TextStream object closes the previously opened file.
Example
Listing 14.99 shows you how to open and close a text file. This file can be executed
with the Windows Script Host (wscript.exe or cscript.exe).
TextStream.Column
JScript2.0+
Syntax
textstream.Column
Description
The Column property of the TextSream object returns the column number of the current
pointer position.
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1916
Example
Listing 14.100 opens a file for reading and a file for writing. The script iterates through
each character of the first file, and then writes it and the column number to the second
file. This file can be executed with the Windows Script Host (wscript.exe or
cscript.exe).
TextStream.Line
JScript2.0+
Syntax
textstream.Line
Description
The Line property of the TextStream object returns the line number of the current
pointer position.
Example
Listing 14.101 opens a file for reading and a file for writing. The script iterates through
each character of the first file, and then writes it and the line number to the second file.
This file can be executed with the Windows Script Host (wscript.exe or
cscript.exe).
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1917
TextStream.Read()
JScript2.0+
Syntax
textstream.Read(num)
Description
The Read() method of an instance of the TextStream object reads the num characters
passed to the method starting at the current pointer position.
Example
Listing 14.102 opens two files. The first file is for reading a string from, whereas the
second file is written to—one character at a time—as the script iterates through. The
result is that the file opened for reading is written to the second file. This file can be
executed with the Windows Script Host (wscript.exe or cscript.exe).
TextStream.ReadAll()
JScript2.0+
Syntax
textstream.ReadAll()
Description
The ReadAll() method of an instance of the TextStream object reads the entire text
file. Be careful when using this method with large files because it will use up a good
amount of system memory.
Example
Listing 14.103 opens two files. The first file is for reading a string from, whereas the
second file is written to. The result is that the file opened for reading is written to the
second file. This file can be executed with the Windows Script Host (wscript.exe or
cscript.exe).
TextStream.ReadLine()
JScript2.0+
Syntax
textstream.ReadLine()
Description
The ReadLine() method of an instance of the TextStream object reads a line from a
text file up to a newline character. Be careful when using this method with large files
because it will use up a good amount of system memory.
Example
Listing 14.104 opens two files. The first file is for reading a string from, whereas the
second file is written to. Each line is read and written one at a time. The result is that
the file opened for reading is written to the second file. This file can be executed with
the Windows Script Host (wscript.exe or cscript.exe).
TextStream.Skip()
JScript2.0+
Syntax
textstream.Skip(num)
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1920
Description
The Skip() method of an instance of the TextStream object skips num characters.
Example
Listing 14.105 opens two files. The first file is for reading a string from, whereas the
second file is written to. The Skip() method is used to skip the first five characters
before the file is read. This file can be executed with the Windows Script Host
(wscript.exe or cscript.exe).
TextStream.SkipLine()
JScript2.0+
Syntax
textstream.SkipLine()
Description
The SkipLine() method of an instance of the TextStream object skips the next line.
Example
Listing 14.106 opens two files. The first file is for reading a string from, whereas the
second file is written to. The SkipLine() method is used to skip the first line before
28 0672321416 CH14c 7/30/01 1:58 PM Page CD:1921
the file is read. This file can be executed with the Windows Script Host (wscript.exe
or cscript.exe).
// The SkipLine method is used to skip the first line of the input file.
myInputTextStream.SkipLine();
TextStream.Write()
JScript2.0+
Syntax
textstream.Write(string)
Description
The Write() method of an instance of the TextStream object is used to write a string
to the text file.
Example
Listing 14.107 opens a text file and writes a string to it. This file can be executed with
the Windows Script Host (wscript.exe or cscript.exe).
TextStream.WriteBlankLines()
JScript2.0+
Syntax
textstream.WriteBlankLines(num)
Description
The WriteBlankLines() method of an instance of the TextStream object is used to
write num newline characters to the text file.
Example
Listing 14.108 opens a text file and writes a string to it. The WriteBlankLines()
method is then used to place a newline before a second string is written. This file can
be executed with the Windows Script Host (wscript.exe or cscript.exe).
TextStream.WriteLine()
JScript2.0+
Syntax
textstream.WriteLine()
Description
The WriteLine() method of an instance of the TextStream object is used to write a
string followed by a newline to the text file.
Example
Listing 14.109 opens a text file and writes a string followed by a newline to it. This file
can be executed with the Windows Script Host (wscript.exe or cscript.exe).
ON THE CD-ROM
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1926
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1927
NOTE
As of the writing of this book, Windows Script Host 5.6
was in beta release, so the new 5.6 material covered in
this chapter is subject to some changes in the final release
of 5.6. The newest Windows Script Host engine and vari-
ous associated documents can be downloaded from
Microsoft’s scripting page (www.msdn.microsoft.com/
scripting).
Scripting.Signer
WSH 5.6+
Syntax
Scripting.Signer
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1928
Description
The Scripting.Signer object allows script authors to sign their scripts with a digital
signature. Similarly, the object allows a recipient of the script to verify the signature’s
authenticity and trustworthiness. The Scripting.Signer object requires a valid cer-
tificate, used to decode or encode the digital signature, in order to be of any use.
Example
Listing 15.1 uses the Scripting.Signer object to try to sign a script. If no certificate
or file is specified, the user is alerted.
//If no certificate or file exists then display the usage of the signer.
if (!(WScript.Arguments.Named.Exists(“cert”) &&
WScript.Arguments.Named.Exists(“file”)))
{
WScript.Echo(“No certificate or file”);
WScript.Quit();
}
File = WScript.Arguments.Named(“file”);
Cert = WScript.Arguments.Named(“cert”);
Store = WScript.Arguments.Named(“store”);
</script>
</job>
NOTE
The <job> and </job> tags are used to define the beginning and end of a job
within a Windows Script file. If the <job> tag contains the argument “id=” fol-
lowed by a user-defined name, the id can be used to execute a particular job
within a Windows Script file, if multiple jobs exist in the file. To execute a particular
job, simply add the argument “Job” followed by the job ID to the cscript.exe
command.
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1929
WScript
WSH 1.0+
Syntax
WScript
Description
The WScript object provides access to properties of the Windows Script Host
(WScript.exe or cscript.exe) that is currently running. The object also provides meth-
ods to create and read objects. Table 15.1 lists all the properties and methods associ-
ated with the WScript object.
In addition to the methods and properties shown in the table, WScript is also a parent
to some objects. Specifically, the CreateObject() method can be used to create any
one of the following objects as a child of the WScript object: WshController,
WshNetwork, WshShell.
Example
In Listing 15.2, the Echo() method of the WScript object is used to display contents of
the WScript’s Name property.
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1930
WScript.Echo(“WSH Name=”,WScript.Name);
</script>
</job>
WScript.Arguments
WSH 1.0+
Syntax
WshObject.Arguments
Description
The Arguments property of a WScript object contains a pointer to the WshArguments
object, which is a collection that contains the command-line parameters associated
with the WScript object.
Example
Listing 15.3 uses the Arguments property to retrieve a collection of arguments that
were passed into the script. For example, assume that the script in Listing 15.1 was
saved in a Windows script file called myscript.wsf and was executed in a MS-DOS
window using the following line:
cscript.exe myscript.wsf car truck boat plane
In this case, the arguments that are passed into the script are car, truck, boat, and
plane. These arguments are retrieved from within the script using the Arguments
property and displayed as shown in Figure 15.1.
if(WScript.Arguments.Count())
{
WScript.Echo(“Arguments:”);
WScript.Echo(i + “= “ + WSObjectArgs(i));
}
}
else
{
WScript.Echo(“No arguments”);
}
</script>
</job>
Figure 15.1
Accessing command-line parameters with the Arguments property.
WScript.ConnectObject()
WSH 2.0+
Syntax
WshObject.ConnectObject(theObject, prefixString)
Description
The ConnectObject() method connects the specified object’s (theObject) event
sources to functions located in the script. When the object fires an event with this new
connection in place, the Windows Script Host will call a specified function. The
prefixString argument is used to form the name of the function. The name of the sub-
routine is formed by combining the prefixString with the name of the event. For
example if prefixString is “MyObject” and the event is “OnBegin”, the function name
would be “MyObjectOnBegin”.
Example
Listing 15.4 demonstrates how to use the ConnectObject() method using a fictitious
object called BogusObject. An instance of the BogusObject is created and then used in
the call to the ConnectObject() method. Should a “BogusEvent” event occur while
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1932
MyBogusObject.myMethod();
</script>
</job>
WScript.CreateObject()
WSH 2.0+
Syntax
WshObject.CreateObject(programID, [prefixString])
Description
The CreateObject() method creates an object specified by the program ID
(programID) of the object to create. An optional argument can be provided to make the
Windows Script Host connect the new object’s outgoing interface to the script file. If
the new object fires an event with this connection in place, the Windows Script Host
will call a subroutine located in the script. The name of the subroutine is formed by
combining the second argument (prefixString) with the name of the event. For exam-
ple if prefixString is “MyObject” and the event is “OnBegin”, the subroutine name
would be “MyObjectOnBegin”.
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1933
Example
Listing 15.5 uses the CreateObject() method to create a WshNetwork object called
MyWshNetwork. The new MyWshNetwork object is then used to display the name of the
computer.
MyWshNetwork = WScript.CreateObject(“WScript.Network”);
WScript.echo(MyWshNetwork.computerName);
</script>
</job>
WScript.DisconnectObject()
WSH 2.0+
Syntax
WshObject.DisconnectObject(theObject)
Description
The DisconnectObject() method disconnects the specified object’s (theObject)
event sources from the Windows Script Host.
Example
Listing 15.4, shown in an earlier entry, demonstrates how to use the
DisconnectObject() method using a fictitious object called MyBogusObject.
WScript.Echo()
WSH 1.0+
Syntax
WshObject.Echo(string1, string2, ..., stringN )
Description
The Echo() method displays the specified strings separated by spaces. If the script is
being run from WScript.exe, the string will be displayed in a dialog box. If the script
is run with the Console Script Host (CScript.exe), the string will be displayed in the
console from which the script is run. Under CScript.exe, a newline character is placed
at the end of the output after every call to the Echo() method. If no string is provided
when calling the method, a blank line will be displayed.
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1934
Example
Listing 15.6 uses the Echo() method to display some various strings. If the script is run
from WScript.exe, the two calls to the Echo() method will appear in two separate dia-
log boxes. If the script is run from CScript.exe, the output from each call to the Echo()
method will result in two lines of text.
color = “red”;
</script>
</job>
WScript.FullName
WSH 2.0+
Syntax
WshObject.FullName
Description
The FullName property contains the full path to the host executable file.
Example
The FullName property is used in Listing 15.7 to display the full path to the Windows
Script Host executable file. For example, if WScript.exe were located in the
C:\WINDOWS directory, the FullName property would contain C:\WINDOWS\
WSCRIPT.EXE.
</script>
</job>
WScript.GetObject()
WSH 2.0+
26 0672321416 CH15a 7/30/01 1:54 PM Page CD:1935
Syntax
WshObject.GetObject( fileName, [programID], [prefixString] )
Description
The GetObject() method retrieves an existing object from memory or creates a new
one from a file. To create an object from a file, simply provide the full path to the file
(fileName). To retrieve an object from memory, simply specify the program ID
(programID). If the object to be retrieved is registered as a single-instance object, only
one instance of the object is created.
An optional argument can be provided to make the Windows Script Host connect the
new object’s outgoing interface to the script file. If the new object fires an event with
this connection in place, the Windows Script Host will call a subroutine located in the
script. The name of the subroutine is formed by combining the second argument
(prefixString) with the name of the event. For example if prefixString is
“MyObject” and the event is “OnBegin”, the subroutine name would be
“MyObjectOnBegin”.
NOTE
The GetObject() method can be used with all COM classes, independent of the
language used to create the object.
The GetObject() method cannot be used to obtain a reference to a Microsoft
Visual Basic class created with Visual Basic 4.0 or earlier.
Example
The following fictitious code snippet uses the GetObject() method to create a
channel object from the MYSONG.MID file that is associated with the MYSOUNDPGM
application. This would cause the MYSOUNDPGM application to start and open the object
CHANNEL from within the MYSONG file.
channel = GetObject(“C:\SONGS\MYSONG.MID”,”MYSOUNDPGM.CHANNEL”);
WScript.Interactive
WSH 5.6+
Syntax
WshObject.Interactive
Description
The Interactive property contains the mode of the script in the form of a Boolean
value. The property can also be used to set the mode. The mode can be either batch or
interactive, which is represented by 0 and 1, respectively.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1936
In interactive mode (1), the script can interact with users through dialog boxes. In batch
mode (0) input or output cannot take place, so there is no interaction between the script
and users.
NOTE
The mode of a script can also be set using the Cscript.exe command line switches
//I (for Interactive), and //B (for Batch).
Example
In Listing 15.8, the script mode is retrieved and displayed using the Interactive
property.
Listing 15.8 Retrieving the Script Mode with the Interactive Property
<job>
<script language=”JScript”>
WScript.Echo(“Script Mode=”,WScript.Interactive);
</script>
</job>
WScript.Name
WSH 2.0+
Syntax
WshObject.Name
Description
The Name property contains the name of the Windows Script Host (WSH).
Example
In Listing 15.9 the Windows Script Host name is retrieved and displayed using the Name
property.
Listing 15.9 Retrieving the WSH Name with the Name Property
<job>
<script language=”JScript”>
WScript.Echo(“WSH Name=”,WScript.Name);
</script>
</job>
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1937
WScript.Path
WSH 2.0+
Syntax
WshObject.Path
Description
The Path property contains the name of the directory in which the WScript.exe or
CScript.exe resides.
Example
In Listing 15.10, the directory in which the Windows Script Host executable is located
is retrieved and displayed using the Path property.
Listing 15.10 Retrieving the WSH Directory with the Path Property
<job>
<script language=”JScript”>
WScript.Echo(“WSH Path=”,WScript.Path);
</script>
</job>
WScript.Quit()
WSH 2.0+
Syntax
WshObject.Quit (exitCode)
Description
The Quit() method causes the execution of the script to stop immediately. If you need
the script to return an integer exit code, simply provide an optional exitCode parame-
ter to the method call.
Example
In Listing 15.11, the Quit() method is called just before the second Echo() method is
reached. This causes execution of the script to stop, which prevents the second Echo()
method to be executed.
</script>
</job>
WScript.ScriptFullName
WSH 2.0+
Syntax
WshObject.ScriptFullName
Description
The ScriptFullName property contains the full path to the script that is currently being
executed.
Example
In Listing 15.12, the ScriptFullName property is used to display the full path to the
script that is being executed.
WScript.Echo(WScript.ScriptFullName);
</script>
</job>
WScript.ScriptName
WSH 2.0+
Syntax
WshObject.ScriptName
Description
The ScriptName property contains the name of the script file that is currently being
executed. No path information is contained in this property.
Example
In Listing 15.13, the ScriptName property is used to display the name of the script file
that is being executed.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1939
WScript.Echo(WScript.ScriptName);
</script>
</job>
WScript.Sleep()
WSH 2.0+
Syntax
WshObject.Sleep(milliseconds)
Description
The Sleep() method causes the script to pause execution for the number of millisec-
onds specified by the milliseconds parameter.
Example
In Listing 15.14, the Sleep() method pauses execution of the script for 10 seconds
(10,000 milliseconds). Using the Sleep() method causes a 10 second pause between
when the string above the Sleep() method is displayed and when the string below the
Sleep() method is displayed.
</script>
</job>
WScript.StdErr
WSH 2.0+
Syntax
WshObject.StdErr
Description
The StdErr property provides access to the write-only error output stream of the cur-
rent script.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1940
CAUTION
The StdErr property can only be accessed using the Console Script Host
(CScript.exe). Accessing the property with the Windows Script Host (WScript.exe)
will cause an error.
Example
In Listing 15.15, the error stream is assigned to the variable standardError using the
StdErr property. A string is then sent to the standard error output using the write()
method. In order for this script to work, it must be executed using the Console Script
Host (CScript.exe). Unless you have redirected the standard error output, the string will
appear in the console.
standardError = WScript.StdErr;
standardError.write(“This string was sent to the standard error output”);
</script>
</job>
WScript.StdIn
WSH 2.0+
Syntax
WshObject.StdIn
Description
The StdIn property provides access to the read-only input stream of the current script.
CAUTION
The StdIn property can only be accessed using the Console Script Host
(CScript.exe). Accessing the property with the Windows Script Host (WScript.exe)
will cause an error.
Example
In Listing 15.16, the standard input stream is assigned to the variable standardInput
using the StdIn property. The user is then prompted to enter some text. The text is then
read in using the Read() method, and the first 10 characters entered by the user are
stored in the str variable and then displayed in the console.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1941
standardIn = WScript.StdIn;
</script>
</job>
WScript.StdOut
WSH 2.0+
Syntax
WshObject.StdOut
Description
The StdOut property provides access to the write-only standard output stream of the
current script.
CAUTION
The StdOut property can only be accessed using the Console Script Host
(CScript.exe). Accessing the property with the Windows Script Host (WScript.exe)
will cause an error.
Example
In Listing 15.17, the standard output stream is assigned to the variable standardOutput
using the StdOut property. A string is then sent to standard output using the write()
method. In order for this script to work, it must executed using the Console Script Host
(CScript.exe). Unless you have redirected standard output, the string will appear in the
console.
standardOutput = WScript.StdOut;
standardOutput.write(“This string was sent to the standard output”);
</script>
</job>
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1942
WScript.Version
WSH 1.0+
Syntax
WshObject.Version
Description
The Version property contains the version of the Windows Script Host that is being
used.
Example
In Listing 15.18, the version of the Windows Script Host is displayed using the
Version property.
Listing 15.18 Displaying the WSH Version Using the Version Property
<job>
<script language=”JScript”>
WScript.Echo(“WSH Version:”,WScript.Version);
</script>
</job>
WScript.WshArguments
WSH 5.6+
Syntax
WshObject.WshArguments
Description
The WshArguments property of a WScript object contains a pointer to the
WshArguments object, which contains the command-line parameters associated with
the WScript object.
Example
Listing 15.19 uses the Arguments property to retrieve a collection of arguments that
were passed into the script. For example, assume that the script from Listing 15.1 was
saved in a Windows script file called myscript.wsf and was executed in a MS-DOS
window using the following line:
cscript.exe myscript.wsf car truck boat plane
In this case the arguments that are passed into the script are car, truck, boat, and
plane. These arguments are retrieved from within the script using the Arguments prop-
erty and displayed as shown earlier in Figure 15.1.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1943
if(WScript.WshArguments.Count())
{
WScript.Echo(“Arguments:”);
WScript.WshController
WSH 5.6+
Syntax
None
Description
The WshController object is a child object of WScript. Because it is not directly
accessible through the WScript.WshController syntax, see this chapter’s entry for
WshController for more information.
WScript.WshNetwork
WSH 5.6+
Syntax
None
Description
The WshNetwork object is a child object of WScript. Because it is not directly accessi-
ble through the WScript.WshNetwork syntax, see this chapter’s entry for WshNetwork
for more information.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1944
WScript.WshShell
WSH 5.6+
Syntax
None
Description
The WshShell object is a child object of WScript. Because it is not directly accessible
through the WScript.WshShell syntax, see this chapter’s entry for WshShell for more
information.
WshArguments
WSH 2.0+
Syntax
ArgObj = WScript.Arguments
WScript.Arguments(number)
Description
The WshArguments object provides access to the command-line parameters associated
with the WScript object. The WshArguments object is accessed from the WScript
object’s Arguments property and is in fact a child of the WScript object. Table 15.2 lists
all the properties and methods associated with the WshArguments object.
The contents of the WshArguments object can also be accessed directly by placing a
number in parenthesis directly after the WshArgument object’s name.
In addition to the methods and properties shown in the table, WshArguments is also a
parent to some other objects. Specifically, the Named and Unnamed properties provide
access to the WshNamed and WshUnnamed objects.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1945
Example
The code in Listing 15.20 creates a WshArgument object, called WshArgsObj, from the
WScript.Arguments property. If the WshArgsObj object contains any parameters, they
are accessed directly from the object using parenthesis. So, if you executed this code
using the command cscript.exe listing15-20.wsf Chris Craig, the arguments
Chris and Craig would be displayed.
if(WshArgsObj.Count())
{
WScript.Echo(“Arguments:”);
WshArguments.Count
WSH 2.0+
Syntax
WshArgObj.Count
Description
The Count property contains the number of parameters that were passed into the
Windows Script Host. This number includes both the named and unnamed parameters.
NOTE
The Count property is only available in VBScript. Use the Length property to access
the number of parameters in JScript.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1946
Example
No example is provided because this property is not available in JScript.
WshArguments.Count()
WSH 2.0+
Syntax
WshArgObj.Count()
Description
The Count() method returns the number of parameters that were passed into the
Windows Script Host. This number includes both the named and unnamed parameters.
Example
The code in Listing 15.21 creates a WshArgument object, called WshArgsObj, from the
WScript.Arguments property. The Count() method is then used to display the number
of parameters passed into the Windows Script Host. For example, if the code were run
in MS-DOS using the line “cscript.exe listing21.wsf red blue”, the Count()
method would return the number 2.
</script>
</job>
WshArguments.Item()
WSH 2.0+
Syntax
WshArgObj.Item(number)
Description
The Item() method is used to access a single item in the WshArguments collection. The
item (WScript parameter) to be retrieved is specified with the number argument.
Example
The code in Listing 15.22 creates a WshArgument object, called WshArgsObj. If the
WshArgsObj object contains any parameters, they are accessed using the Item() method.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1947
if(WshArgsObj.Count())
{
WScript.Echo(“Arguments:”);
WshArguments.length
WSH 2.0+
Syntax
WshArgObj.length
Description
The Length property contains the number of parameters that were passed into the
Windows Script Host. This number includes both the named and unnamed parameters.
Example
The code in Listing 15.23 creates a WshArgument object, called WshArgsObj. The
Length property is then used to determine if the object contains any parameters. If the
WshArgObj object does contain parameters, the Length property is used again to set up
a loop in which all the parameters are displayed.
WshArguments.Named
WSH 5.6+
Syntax
WshArgsObj.Named
Description
The Named property contains the WshNamed collection object. The WshNamed object con-
tains parameters of the WshArguments object with the unnamed parameters removed. A
named parameter is one that is made up of a key/value pair in which the key and value
are separated with a colon (:) and the key is preceded by a forward slash (/).
Example
The code in Listing 15.24 creates a WshArgument object, called WshArgsObj. The Named
property is then used to access the WshNamed object, which is used to display the value
of the color parameter if such a parameter should exist. For example let us assume that
the script was run using the following line:
cscript.exe listing24.wsf /color:green
Listing 15.24 Using the Named Property to Display the Color Parameter
<job>
<script language=”JScript”>
if(WshNamedArgsObj.length)
{
WScript.Echo(“color=”, WshNamedArgsObj.Item(“color”));
}
else
{
WScript.Echo(“No named arguments”);
}
</script>
WshArguments.ShowUsage()
WSH 5.6+
Syntax
WshArgsObj.ShowUsage()
Description
The ShowUsage() method displays a help screen for the script. This help screen dis-
plays information about the script’s command-line options. This information is defined
in the runtime portion of the script as defined within the <runtime> and </runtime>
tags.
Example
Listing 15.25 contains a script that displays the color the user entered on the command
line when executing the script. If no arguments are specified on the command line, the
ShowUsage() method is called to display the usage information contained in the
<runtime> tags. Figure 15.2 shows the usage information that is displayed.
<description>
This script displays the color you pass in
</description>
<named
name = “color”
helpstring = “Your favorite color”
type = “string”
required = “true”
/>
<example>Example: listing25.wsf /color:purple</example>
</runtime>
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1950
if(WshArgsObj.Named.length == 0)
{
//Display how to use script
WshArgsObj.ShowUsage();
}
else
{
WScript.Echo(“Your favorite color is”, WshArgsObj.Named(“color”));
}
</script>
</job>
Figure 15.2
Displaying the usage information for the script.
WshArguments.Unnamed
WSH 5.6+
Syntax
WshArgsObj.Unnamed
Description
The Unnamed property contains the WshUnnamed collection object. The WshUnnamed
object contains parameters of the WshArguments object with the named parameters
removed. A named parameter is one that is made up of a key/value pair in which
the key and value are separated by a colon (:) and the key is preceded by a forward
slash (/).
Example
The code in Listing 15.26 creates a WshArgument object, called WshArgsObj.
The Unnamed property is then used to access the WshUnnamed object, which is used to
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1951
display the unnamed parameters if such parameters should exist. For example, let us
assume that the script was run using the following line:
cscript.exe listing26.wsf /color:green blue red
When the code is executed using the command the unnamed parameters blue and red
are displayed.
if(WshUnnamedArgsObj.length)
{
WScript.Echo(“Unnamed Arguments:”);
WshArguments.WshNamed
WSH 5.6+
Syntax
None
Description
WshNamed object is a child object of WshArguments. Because it is not directly accessi-
ble through the WshArguments.WshNamed syntax, see this chapter’s entry for WshNamed
for more information.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1952
WshArguments.WshUnnamed
WSH 5.6+
Syntax
None
Description
WshUnnamed object is a child object of WshArguments. Because it is not directly acces-
sible through the WshArguments.WshUnnamed syntax, see this chapter’s entry for
WshUnnamed for more information.
WshController
WSH 5.6+
Syntax
WshControllerObj = WScript.CreateObject(“WScript.Controller”)
Description
The WshController object is a child of the WScript object. The WshController object
allows remote scripts, WshRemote objects, to be created using its CreateScript()
method. To create the WshController object, you must use the WScript’s
CreateScript() method.
NOTE
The WshController object is not available on Windows 9x operating systems.
Example
Listing 15.27 uses the CreateObject() method to create a WshController object that
is a child of the WScript object. The new WshController object is then used to create
a remote script that is executed.
</script>
</job>
WshController.CreateScript()
WSH 5.6+
Syntax
WshControllerObj.CreateScript(commandLine, machine)
Description
The CreateScript() method creates a WshRemote object that allows scripts on one
computer system to be executed remotely on another machine. The full pathname of
the remote script, as well as any command-line options, are passed in to the
commandLine argument. The script file can be on a completely different computer sys-
tem.
If the script is to be executed on a remote machine, the name of the remote computer
should be passed into the machine argument using the Universal Naming Convention
(UNC). The machine argument is optional, so if it is left blank, the script is run on the
controller’s computer system.
CAUTION
The CreateScript() method sets up a script to run and establishes a connection
with a remote computer system, but the script is not actually started until a call is
made to the Execute() method of the WshRemote object.
NOTE
The CreateScript() method is not available on Windows 9x operating systems.
Example
Listing 15.28 creates a WshController object, called WshCtrlObj using the
CreateObject() method. A remote script located at “C:\scripts\myScript.wsf” is
created using the CreateScript() method. The remote script, called myRemoteScript,
is executed using the Execute() method.
</script>
</job>
WshController.WshRemote
WSH 5.6+
Syntax
None
Description
WshRemote object is a child object of WshController. Because it is not directly acces-
sible through the WshController.WshRemote syntax, see this chapter’s entry for
WshRemote for more information.
WshEnvironment
WSH 2.0+
Syntax
WshEnvObj(string)
Description
The WshEnvironment object provides access to the entire set of environment variables.
This object is accessed through the Environment property of the WshShell object.
Depending on the settings of the Environment property, the WshEnvironment object
will contain “User”, “System”, “Volatile”, or “Process” related environment vari-
ables. For more information on creating the WshEnvironment object, see the
“WshShell.Environment” section in this chapter.
Table 15.3 lists all the properties and methods associated with the WshEnvironment
object. In addition to the methods shown in this array, an environment variable can be
directly accessed from the WshEnvironment object by simply placing an environment
variable’s name in parenthesis directly after the name of the WshEnvironment object.
Table 15.4 lists some of the environment variables that are available in the Win-
dows operating system with a short description. The table also shows each variable’s
availability based on the Environment property setting (P=Process, S=System,
U=User). The “Volatile” setting supports none of the variables in the table.
Example
A WshEnvironment object is created and used to access all the “Process” environment
variables in Listing 15.29. The new WshEnvObj is used to display the value of the
“WINDIR” environment variable. When this script is executed, the path to your system
directory will be displayed.
</script>
</job>
WshEnvironment.Count()
WSH 2.0+
Syntax
WshEnvObj.Count()
Description
The Count() method returns the number of environment variables that are in the
WshEnvironment object. Depending on the settings of the Environment property on
creation, the WshEnvironment object will contain different numbers of environment
variables. For more information on the Environment property, see the
“WshShell.Environment” entry in this chapter.
Example
Listing 15.30 uses the Count() method to display the number of “Process” related
environment variables that are in the WshEnvironment object.
</script>
</job>
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1957
WshEnvironment.Item()
WSH 2.0+
Syntax
WshEnvObj.Item(string)
Description
The Item() method is used to access the value of a single environment variable from
WshEnvironment object. The name of the environment variable to retrieve is specified
by the string argument.
Example
A WshEnvironment object is created and used to access all the “Process” environment
variables in Listing 15.31. The new WshEnvObj and its Item() method are used to dis-
play the value of the “WINDIR” environment variable. When this script is executed, the
path to your system directory will be displayed.
Listing 15.31 Displaying the System Directory Path with the Item()
Method
<job>
<script language=”JScript”>
</script>
</job>
WshEnvironment.length
WSH 2.0+
Syntax
WshEnvObj.length
Description
The length property contains the number of environment variables that are in the
WshEnvironment object. Depending on the settings of the Environment property on
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1958
Example
Listing 15.32 uses the length property to display the number of “Process” related
environment variables that are in the WshEnvironment object.
</script>
</job>
WshEnvironment.Remove()
WSH 2.0+
Syntax
WshEnvObj.Remove(envVar)
Description
The Remove() method allows you to delete environment variables by simply specify-
ing the name of the environment variable in the method. Environment variables that are
removed with this method are only removed for the current session.
NOTE
An Environment variable must exist in the WshEnvironment object in order to be
deleted. The environment variables that are in the WshEnvironment object depend
on the settings of the Environment property when the WshEnvironment object is
created.
26 0672321416 CH15a 7/30/01 1:55 PM Page CD:1959
Example
Listing 15.33 begins by checking to see if the WINDIR environment variable exists. If it
does, the value stored in the variable is displayed. The variable is then deleted using the
Remove() method. Finally, a success message is displayed if the environment variable
is successfully deleted.
if(WshEnvObj.Item(“WINDIR”))
{
//Display the number of environment variables in object
WScript.Echo(“WINDIR=”, WshEnvObj.Item(“WINDIR”));
</script>
</job>
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1960
WshNamed
WSH 5.6+
Syntax
WshNamed
Description
The WshNamed object provides access to the collection or arguments in which the
WshArguments.Named property returns. Table 15.5 lists all the properties and methods
associated with the WshNamed object.
Example
Listing 15.34 uses the Arguments property to retrieve a collection of arguments that
were passed into the script and assigns that to a new object named WshNamed. Then a
loop is run to print out all the arguments to the screen. Suppose that the script was
named myScript.wsf and was run with the following command in DOS:
cscript myScript.wsf “Where is Tilly” “The Dog is outside”
After executing the script, the two arguments “Where is Tilly” and “The Dog is out-
side” would be displayed to the user.
</script>
</job>
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1961
WshNamed.Count()
WSH 5.6+
Syntax
WshNamed.Count()
Description
The Count() method of the WshNamed object returns an integer value representing the
number of switches.
Example
Listing 15.35 uses the Arguments property to retrieve a collection of arguments that
were passed into the script and assigns that to a new object named WshNamed. Then the
number of arguments is printed to the screen. Suppose that the script was named
myScript.wsf and was run with the following command in DOS:
</script>
</job>
WshNamed.Exists()
WSH 5.6+
Syntax
WshNamed.Exists(value)
Description
The Exists() method is used to determine whether a specific value exists in the
WshNamed object. A boolean value of true or false is returned.
Example
Listing 15.36 uses the Arguments property to retrieve a collection of arguments that
were passed into the script and assigns that to a new object named WshNamed. Then it
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1962
checks for the specific value “c” in the argument list. Suppose that the script was
named myScript.wsf and was run with the following command in DOS:
cscript myScript.wsf /c “Where is the Doc”
</script>
</job>
WshNamed.Item
WSH 5.6+
Syntax
WshNamed.Item(key)
Description
The Item property is used to gain access to each item in the WshNamed object.
Example
Listing 15.37 uses the Arguments property to retrieve a collection of arguments that
were passed into the script and assigns that to a new object named WshNamed. Then a
loop is run to print out all the arguments to the screen. Suppose that the script was
named myScript.wsf and was run with the following command in DOS:
cscript myScript.wsf “Where is Big Money JLai?” “He is out riding his bike”
After execution, each argument, “Where is Big Money JLai?” and “He is out
riding his bike”, would be displayed to the screen.
</script>
</job>
WshNamed.length
WSH 5.6+
Syntax
WshObject.length
Description
The length property returns the number of command-line parameters for the script.
This is a read-only property and is essentially the number of items in the arguments
collection.
Example
Listing 15.38 uses the Arguments property to retrieve a collection of arguments that
were passed into the script and assigns that to a new object named WshNamed. Then the
length property is used to display the length to the screen. Suppose that the script was
named myScript.wsf and was run with the following command in DOS:
cscript myScript.wsf “Angela” “Pete”
The length representing the number of arguments would be displayed to the screen.
</script>
</job>
WshNetwork
WSH 2.0+
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1964
Syntax
WshNetwork
Description
The WshNetwork object provides access to the Microsoft Windows Network. This
encompasses all network items such as drives and printers. Table 15.6 lists all the prop-
erties and methods associated with the WshNetwork object.
Example
In Listing 15.39, the Echo() method of the WScript object is used to display contents
of the WshNetwork’s UserName property.
</script>
</job>
WshNetwork.AddPrinterConnection()
WSH 2.0+
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1965
Syntax
WshNetwork.AddPrinterConnection(localName, remoteName, updateProfile, userName,
➥ password)
Description
The AddPrinterConnection() method is used to map a remote printer to a specified
machine. The localName of the printer should be supplied as the first parameter. The
remoteName of the printer should be specified as the second parameter. The
updateProfile is a boolean value that specifies whether the mapping should be stored
in the user profile (default if false). For printers that require login authentication to be
added, the userName and password should be supplied. The updateProfile, userName,
and password are optional parameters.
Example
Listing 15.40 shows an example of how to map a printer to the local machine.
</script>
</job>
WshNetwork.AddWindowsPrinterConnection()
WSH 2.0+
Syntax
WshObject.AddWindowsPrinterConnection(printerPath, driveName, printerPort)
Description
The AddWindowsPrinterConnection() method is used to add printer connections to
the windows environment. The printerPath parameter specifies the path to the printer
and must be specified. The driverName specifies the name of the driver to use and is
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1966
ignored on the Windows NT/2000 environment. The printerPort specifies the port on
which the printer connection should be made and is optional. The default value is LPT1
and is ignored on Windows NT/2000.
Example
Listing 15.41 shows an example of how to add the Epson Stylus 850 printer to the cur-
rent Windows environment.
</script>
</job>
WshNetwork.ComputerName
WSH 2.0+
Syntax
WshNetwork.ComputerName
Description
The ComputerName property returns a string representation of the computer name.
Example
Listing 15.42 shows an example of how to use the ComputerName property to get the
current computer’s name.
</script>
</job>
WshNetwork.EnumNetworkDrives()
WSH 2.0+
Syntax
WshNetwork.EnumNetworkDrives()
Description
The EnumNetworkDrives() method is used to obtain the current network drive map-
pings.
Example
In Listing 15.43 the network drives are retrieved and displayed to the user within a for
loop.
// Loop through the drives and print out each drive number
for (i=0; i<myDrives.Count(); i++){
WScript.Echo(“Drive Number “ + i + “ is “ + myDrives.Item(i+1) );
}
</script>
</job>
WshNetwork.EnumPrinterConnection()
WSH 2.0+
Syntax
WshNetwork.EnumPrinterConnection()
Description
The EnumPrinterConnection() method is used to obtain the current network printer
mappings.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1968
Example
In Listing 15.44 the list of network printers is displayed.
</script>
</job>
WshNetwork.MapNetworkDrive()
WSH 2.0+
Syntax
WshNetwork.MapNetworkDrive(driveLetter, driveName, updateProfile,
➥userName, password)
Description
The MapNetworkDrive() method is used to map a drive from the network to your local
machine. The driveLetter and the driveName must be supplied. The driveLetter
pertains to the letter on which the drive will be on the local machine. The driveName
represents the name of the network drive to map. The updateProfile is a boolean
value that specifies whether the mapping should be stored in the user profile (default is
false). For mappings that require login authentication, the userName and password
should be supplied.
Example
Listing 15.45 shows how the “everyone” drive can be mapped to the local machine as
the “T” drive.
</script>
</job>
WshNetwork.RemoveNetworkDrive()
WSH 2.0+
Syntax
WshNetwork.RemoveNetworkDrive(driveName, bForce, bUpdateProfile)
Description
The RemoveNetworkDrive() method is used to remove a current network drive from
the local machine. The driveName must be specified as a string representing the local
name or the remote name of the drive to be removed. The bForce is a boolean value
(default is false) that, if supplied and set to true, will force a removal of the drive
whether it is in use or not. The bUpdateProfile is a boolean value (default is false),
which if specified, will remove the mapping from the user profile. bForce and
bUpdateProfile are optional parameters.
Example
In Listing 15.46, a network drive is mapped and then removed using the
RemoveNetworkDrive method.
</script>
</job>
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1970
WshNetwork.RemovePrinterConnection()
WSH 2.0+
Syntax
WshNetwork.RemovePrinterConnection(printer, bForce, bUpdateProfile)
Description
The RemovePrinterConnection() method is used to remove a specified printer con-
nection from the local machine. The name of the printer to be removed is specified in
the printer parameter. The bForce is a boolean value (default is false) that, if sup-
plied and set to true, will force a removal of the drive whether it is in use or not. The
bUpdateProfile is a boolean value (default is false), which if specified, will remove
the mapping from the user profile. bForce and bUpdateProfile are optional parame-
ters.
Example
In Listing 15.47, the printer connected to LPT1 is removed from the local machine.
</script>
</job>
WshNetwork.SetDefaultPrinter()
WSH 2.0+
Syntax
WshNetwork.setDefaultPrinter(printerName)
Description
The setDefaultPrinter() method is used to set the default printer to a specified
remote printer, printerName.
Example
In Listing 15.48, the default printer is set to the “blueroom” printer.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1971
</script>
</job>
WshNetwork.UserDomain
WSH 2.0+
Syntax
WshObject.UserDomain
Description
The UserDomain property is used to obtain a string representation of the user domain
name.
Example
Listing 15.49 shows how to display the user domain name to the user.
Listing 15.49 Using the UserDomain Property to Display the User Domain
Name
<job>
<script language=”JScript”>
</script>
</job>
WshNetwork.UserName
WSH 2.0+
Syntax
WshObject.UserName
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1972
Description
The UserName property is used to get a string representation of the username.
Example
Listing 15.50 shows how to use the UserName property to display the username.
</script>
</job>
WshRemote
WSH 5.6+
Syntax
WshRemote
Description
The WshRemote object provides access to a remote script process. It is created by using
the CreateScript() method. Table 15.7 lists all the properties and methods associated
with the WshRemote object.
Example
In Listing 15.51, a WshController object is used to create a WshRemote object. Then
the remote script hello.wsf is executed using the Execute method.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1973
NOTE
The WshController object is not available on Windows 9x operating systems.
</script>
</job>
WshRemote.End
WSH 5.6+
Syntax
WshRemote.End
Description
The End event is used to signal to the remote script to end execution.
Example
In Listing 15.52 the remote script, hello.wsf, is executed. Upon ending, a message is
displayed indicating that execution has finished.
WshRemote.Error (Event)
WSH 5.6+
Syntax
WshObject.Error
Description
The Error event is used to signal the scripting engine to end execution of a remote
script when the remote script stops because of an error.
Example
In Listing 15.53 the remote script, hello.wsf, is executed. Upon an error, a message is
displayed indicating that execution has terminated due to an error.
Listing 15.53 Using the Error Event to Check for Remote Script Errors
<job>
<script language=”JScript”>
</script>
</job>
WshRemote.Error (Property)
WSH 5.6+
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1975
Syntax
WshRemote.Error
Description
The Error property is used to obtain information in relation to an error, which causes
a remote script to terminate prematurely. The Error property returns a
WshRemoteError object.
Example
In Listing 15.54, the error description is displayed from the showErr function if an
error occurred in the remote script.
Listing 15.54 Using the Error Property to Display the Error Description
<job>
<script language=”JScript”>
</script>
</job>
WshRemote.Execute()
WSH 5.6+
Syntax
WshRemote.Execute()
Description
The Execute() method is used to start execution of a remote script. This is not the
same as the WScript.Exec() method.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1976
Example
Listing 15.55 shows how to use the Execute method to start the remote script
hello.wsf.
</script>
</job>
WshRemote.WshRemoteError
WSH 5.6+
Syntax
WshRemote.WshRemoteError
Description
The WshRemoteError object is a child object of WshRemote. Because it is not directly
accessible through the WshRemote.WshRemoteError syntax, see this chapter’s entry for
WshRemoteError for more information.
WshRemote.Start
WSH 5.6+
Syntax
WshRemote.Start
Description
The Start event signals the scripting engine to begin execution of the remote script. It
is fired when the Execute method is called.
Example
Listing 15.56 shows how the Start event is used to indicate when the script has started
execution.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1977
</script>
</job>
WshRemote.Status
WSH 5.6+
Syntax
WshRemote.Status
Description
The Status property is used to obtain information on the status of a script run with the
Exec method. The status property is only used when a script is run asynchronously. It
will return one of two values. If WshRunning (equivalent to 0) is returned, the script is
still running. If WshFinished (equivalent to 1) is returned, the script has finished run-
ning.
Example
Listing 15.57 uses the Status property to see whether the script is finished running.
Listing 15.57 Using the Status Property to Check the Script Status
<job>
<script language=”JScript”>
if (remoteScript.Status == 1){
WScript.Echo (“The Script is finished”);
}
</script>
</job>
WshRemote.Terminate()
WSH 5.6+
Syntax
WshRemote.Terminate()
Description
The Terminate() method is used to stop execution of a remote script. No value is
returned from the method.
Example
Listing 15.58 uses the Terminate method to stop the execution of the hello.wsf script.
</script>
</job>
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1979
WshRemoteError
WSH 5.6+
Syntax
WshRemoteError
Description
The WshRemoteError object is used to obtain error information when a remote script is
terminated due to an error. It is returned by the Error property of the WshRemote object.
Table 15.8 lists all the properties associated with the WshRemoteError object.
Example
The code in Listing 15.59 creates a WshRemoteError object called myError.
function showErr(){
// Create WshRemoteError object.
var myError = remoteScript.Error;
}
</script>
</job>
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1980
WshRemoteError.Character
WSH 5.6+
Syntax
WshRemoteError.Character
Description
The Character property returns a signed long integer that specifies the character in the
line of source code in which the error occurred.
Example
Listing 15.60 shows how to use the Character property to display the exact character
in the source code where the error occurred.
</script>
</job>
WshRemoteError.Description
WSH 5.6+
Syntax
WshRemoteError.Description
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1981
Description
The Description property returns a string containing a brief description of the error
that occurred.
Example
Listing 15.61 uses the Description property to display the error description.
</script>
</job>
WshRemoteError.Line
WSH 5.6+
Syntax
WshRemoteError.Line
Description
The Line property returns an unsigned long integer indicating the line in which the
error occurred.
Example
Listing 15.62 uses the Line property of the WshRemoteError object to display the line
in the source code in which the error occurred.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1982
Listing 15.62 Using the Line Property to Display the Error Line Number
<job>
<script language=”JScript”>
</script>
</job>
WshRemoteError.Number
WSH 5.6+
Syntax
WshRemoteError.Number
Description
The Number property returns an unsigned long integer representing the error number of
the script error.
Example
Listing 15.63 uses the Number property of the WshRemoteError object to display the
number of the error that occurred.
Listing 15.63 Using the Number Property to Display the Remote Error
Number
<job>
<script language=”JScript”>
</script>
</job>
WshRemoteError.Source
WSH 5.6+
Syntax
WshRemoteError.Source
Description
The Source property returns a string representing the COM object responsible for caus-
ing the script error.
Example
The code in Listing 15.64 uses the Source property of the WshRemoteError object to
get the COM object that caused the error in the remote script.
Listing 15.64 Using the Source Property to Display the Remote Error
COM Source Object
<job>
<script language=”JScript”>
</script>
</job>
WshRemoteError.SourceText
WSH 5.6+
Syntax
WshRemoteError.SourceText
Description
The SourceText property returns a string containing the line of source code in which
the error occurred.
Example
Listing 15.65 uses the SourceText property of the WshRemoteError object to display
the source code text of the line in which the error occurred.
Listing 15.65 Using the SourceText Property to Display the Remote Error
Source Code Line
<job>
<script language=”JScript”>
</script>
</job>
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1985
WshScriptExec
WSH 5.6+
Syntax
WshScriptExec
Description
The WshScriptExec object provides status and access to the stdIn, stdOut, and
stdErr streams for the object returned from the WshShell.Exec() method. Table 15.9
lists all the properties and methods associated with the WshScriptExec object.
Example
Listing 15.66 shows how to create a new WshScriptExec object.
</script>
</job>
WshScriptExec.Status
WSH 5.6+
Syntax
WshScriptExec.Status
Description
The Status property provides access to status information on scripts run from the Exec
method. The Status property is only used when a script is run asynchronously. It will
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1986
return one of two values. If WshRunning (equivalent to 0) is returned, the script is still
running. If WshFinished (equivalent to 1) is returned, the script has finished running.
Example
The code in Listing 15.67 uses the Status property to see whether the script is finished
running or not. Depending on the status code returned, a message is displayed to the
user.
if (WshScriptExec.Status == 1){
WScript.Echo (“The Script is finished”);
}
</script>
</job>
WshScriptExec.StdErr
WSH 5.6+
Syntax
WshScriptExec.StdErr
Description
The StdErr property provides access to the stderr output stream for the Exec object.
The Exec object does not need to be running a script.
CAUTION
The StdErr property can only be accessed using the Console Script Host
(CScript.exe). Accessing the property with the Windows Script Host (WScript.exe)
will cause an error.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1987
Example
Listing 15.68 uses the error stream that is assigned to the variable standardError
using the StdErr property. A string is then sent to a standard error using the write()
method. In order for this script to work, it must be executed using the Console Script
Host (CScript.exe). Unless you have redirected standard error output, the string will
appear in the console.
</script>
</job>
WshScriptExec.StdIn
WSH 5.6+
Syntax
WshScriptExec.StdIn
Description
The StdIn property provides access to the read-only stdin input stream of the Exec
object.
CAUTION
The StdIn property can only be accessed using the Console Script Host
(CScript.exe). Accessing the property with the Windows Script Host (WScript.exe)
will cause an error.
Example
In Listing 15.69 the standard input stream is assigned to the variable standardInput
using the StdIn property. The user is then prompted to enter some text. The text is then
read in using the Read() method, and the first 10 characters entered by the user are
stored in the str variable and then displayed in the console.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1988
</script>
</job>
WshScriptExec.StdOut
WSH 5.6+
Syntax
WshScriptExec.Stdout
Description
The StdOut property provides a write-only stdout output stream of the Exec object.
CAUTION
The StdOut property can only be accessed using the Console Script Host
(CScript.exe). Accessing the property with the Windows Script Host (WScript.exe)
will cause an error.
Example
In Listing 15.70 the standard output stream is assigned to the variable standardOutput
using the StdOut property. A string is then sent to standard output using the write()
method. In order for this script to work, it must be executed using the Console Script
Host (CScript.exe). Unless you have redirected standard output, the string will appear
in the console.
29 0672321416 CH15b 7/30/01 1:59 PM Page CD:1989
</script>
</job>
WshScriptExec.Terminate()
WSH 5.6+
Syntax
WshScriptExec.Terminate()
Description
The Terminate() method is used to terminate the process started by the Exec method.
Example
Listing 15.71 shows how the hello.wsf script is stopped by the Terminate method.
//Terminate script
aScript.Terminate();
</script>
</job>
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:1990
WshShell
WSH 2.0+
Syntax
WshShell
Description
The WshShell object is used to create new processes, shortcuts, and access environ-
ment variables. Table 15.10 lists all the properties and methods associated with the
WshShell object.
Example
Listing 15.72 shows how to create a new instance of the WshShell object.
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:1991
</script>
</job>
WshShell.AppActivate()
WSH 2.0+
Syntax
WshShell.AppActivate(app)
Description
The AppActivate() method of the WshShell object activates a specified application
window. The application name (can be a window title or application task ID) is speci-
fied as the parameter app. The method returns a boolean value that indicates whether
the procedure call was successful or not.
Example
Listing 15.73 uses the WshShell AppActivate() method to activate a notepad applica-
tion window. (This example assumes that the notepad application is currently running.)
// Activate Notepad.
WshShellObj.AppActivate(“Notepad”);
</script>
</job>
WshShell.CreateShortcut()
WSH 2.0+
Syntax
WshShell.CreateShortcut(str)
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:1992
Description
The CreateShortcut() method of the WshShell object is used to create a new short-
cut or open an existing shortcut. A single parameter, str, is passed specifying the short-
cut pathname.
Example
Listing 15.74 uses the CreateShortcut() method to create a Web site shortcut on the
desktop to the www.bestbookbuys.com site.
</script>
</job>
WshShell.CurrentDirectory
WSH 5.6+
Syntax
WshShell.CurrentDirectory
Description
The CurrentDirectory property returns a string containing the full pathname of the
current directory for the active process. This is not the directory that contains the WSH
script, but the directory in which the process is begun.
Example
Listing 15.75 displays the current directory in which the example code is started from.
</script>
</job>
WshShell.Environment
WSH 2.0+
Syntax
WshShell.Environment(str)
Description
The Environment property contains a WshEnvironment object, which is a collection of
environment variables. An optional parameter, str, can be specified for the location of
the environment variable. If str is not specified, the Environment property can return
different types depending on the operating system. For Windows 95/98/Me, only
“PROCESS” is permitted as the str. For Windows NT/2000, “System” can be specified.
Example
Listing 15.76 uses the Environment property to get the CLASSPATH environment vari-
able and display it.
</script>
</job>
WshShell.Exec()
WSH 5.6+
Syntax
WshShell.Exec(cmd)
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:1994
Description
The Exec() method of the WshShell object is used to run an application in a child com-
mand shell. The method takes a single parameter, cmd, specifying the command to start
the application. This should be the same string as if you had typed it from the command
line. A WshScriptExec object is returned, which provided access to the StdIn, StdOut,
and StdErr streams.
Example
Listing 15.77 shows how the Exec() method is used to execute the hello.wsf script in
a child command shell.
</script>
</job>
WshShell.ExpandEnvironmentStrings()
WSH 2.0+
Syntax
WshShell.ExpandEnvironmentStrings(var)
Description
The ExpandEnvironmentStrings() method is used to get an environment variable’s
expanded value. It takes a single parameter, var, which must be enclosed between %
characters.
Example
Listing 15.78 shows an example of using the ExpandEnvironmentStrings() method to
get the expanded version of the PATH environment variable.
</script>
</job>
WshShell.LogEvent()
WSH 2.0+
Syntax
WshShell.LogEvent(eventType, logStr, [strTarget])
Description
The LogEvent() method is used to add an entry to a log file. The eventType and
logStr must be specified. The logStr is a string value specifying the log entry text.
Valid event types are listed in Table 15.11. There is also an optional parameter called
strTarget, which is a string value indicating the name of the computer system where
the event is stored. This optional parameter applies to Windows NT/2000 operating
systems only.
Example
Listing 15.79 shows how the WshShell object uses the LogEvent() method to log a
successful event. When executed, the example logs a success event to the WSH.log file
on Windows 9.x systems. If using Windows NT/2000, then messages are logged to the
Windows NT event log file.
WshShell.Popup()
WSH 2.0+
Syntax
WshShell.Popup(text, [wait], [title], [type])
Description
The Popup() method is used to display a piece of text in a pop-up message box. The
text parameter must be specified for the text to display. The wait parameter is an
optional parameter indicating the length of time (in seconds) for the pop-up to display.
The title parameter is an optional string parameter specifying the title of the pop-up.
The type parameter is an optional numeric parameter specifying the type of buttons
and icons in the pop-up. Refer to Table 15.12 for available button types and Table 15.13
for available icon types. Values can be combined.
Example
In Listing 15.80, a pop-up box is created with a sample message that displays for 15
seconds, has a title, and shows a specific combination of button and icon types.
// Create Popup.
WshShellObj.Popup(“Sample message”, 15, “My Popup box”, 3+32);
</script>
</job>
WshShell.RegDelete()
WSH 2.0+
Syntax
WshShell.RegDelete(key)
Description
The RegDelete() method is used to delete a key or one of its values from the Windows
registry. The key must be specified as the parameter. To indicate a key name, use a final
backslash after the key. Do not use backslash to indicate a value. Abbreviated versions
of root keys can be used. Table 15.14 lists these abbreviations.
CAUTION
Performing modifications to the Windows Registry can cause harm to the opera-
tion system if performed incorrectly. Use caution when working with the Windows
Registry. It is suggested that a backup of the registry be made before deleting or
writing to the registry.
Example
Listing 15.81 shows an example of how the RegDelete() method is used to delete a
registry entry for Netscape.
</script>
</job>
WshShell.RegRead()
WSH 2.0+
Syntax
WshShell.RegRead(key)
Description
The RegRead() method is used to read a key value or a value name from the registry.
The key parameter is used to determine which key to read. To specify a key name, end
the key with a final backslash. If backslash not specified, value name will be used.
Example
Listing 15.82 uses the RegRead() method to get the key value of the specified registry
entry.
WScript.Echo(value);
</script>
</job>
WshShell.RegWrite()
WSH 2.0+
Syntax
WshShell.RegWrite(key, value, [type])
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:1999
Description
The RegWrite() method is used to create a new key, add another value name to an
existing key, or modify the value of an existing value name. A parameter string, key, is
used to specify the key name, value name, or value you want to add, create, or modify.
The value parameter specifies the name of the new key to create, the name of the value
to add, or the new value to assign to an existing key. The type parameter is an optional
string type parameter indicating the value’s data type. The available types are listed in
Table 15.15.
CAUTION
Performing modifications to the Windows Registry can cause harm to the opera-
tion system if performed incorrectly. Use caution when working with the Windows
Registry. It is suggested that a backup of the registry be made before deleting or
writing to the registry.
Example
Listing 15.83 shows how to write a new value to the registry.
</script>
</job>
WshShell.Run()
WSH 2.0+
Syntax
WshShell.Run(cmd, [windowStyle], [waitOnReturn])
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2000
Description
The Run() method runs a specified program in a new process. The program to be run
is specified as the parameter cmd. Two optional parameters can also be specified. The
windowStyle parameter is an integer indicating the appearance of the program’s win-
dow. The valid window styles are listed in Table 15.16. The waitOnReturn parameter
is a boolean value indicating whether the script should wait before executing the next
script command.
Example
In Listing 15.84 the Run() method is used to startup the Notepad application in the
minimized state.
</script>
</job>
WshShell.SendKeys()
WSH 2.0+
Syntax
WshShell.SendKeys(keyStr)
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2001
Description
The SendKeys() method is used to send one or more keystrokes to the active window.
The keys to be sent are specified as the keyStr parameter. This method is typically used
for applications that have no user interface. If sending a combination of keystrokes,
simply group them together in a string. For instance, if sending the keys x, y, and z, use
xyz.
There are some special keys that require a certain syntax. For the +, ^, %, ~, [, and ],
enclose those symbols in braces ({}). Other keystrokes that do not generate any char-
acters have special syntax’s as well. They are listed in Table 15.17.
Example
In Listing 15.85 a WshShell object is created. Then the Run() method is called to start
the Notepad application. Once the Notepad application is up, it is activated using the
AppActivate() method. After being activated, a sequence of keys are sent to the
application.
</script>
</job>
WshShell.SpecialFolders
WSH 2.0+
Syntax
WshShell.SpecialFolders(folder )
Description
The SpecialFolders property returns a collection of special folders. Special folders
within the Windows operating system refer to predefined folders that are built into the
OS. Some examples are the “Desktop”, “Favorites”, and “Startup” folder.
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2003
Example
In Listing 15.86 a WshShell object is first created. Then the SpecialFolders property
is used to create a WshSpecialFolders object.
</script>
</job>
WshShell.WshShortcut
WSH 2.0+
Syntax
WshShell.WshShortcut
Description
The WshShortcut object is a child object of WshShell. Because it is not directly acces-
sible through the WshShell.WshShortcut syntax, see the entry for WshShortcut in this
chapter for more information.
WshShell.WshUrlShortcut
WSH 2.0+
Syntax
WshShell.WshUrlShortcut
Description
The WshUrlShortcut object is a child object of WshShell. Because it is not directly
accessible through the WshShell.WshUrlShortcut syntax, see the entry for
WshUrlShortcut in this chapter for more information.
WshShell.WshEnvironment
WSH 2.0+
Syntax
WshShell.WshEnvironment
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2004
Description
The WshEnvironment object is a child object of WshShell. Because it is not directly
accessible through the WshShell.WshEnvironment syntax, see the entry for
WshEnvironment in this chapter for more information.
WshShell.WshSpecialFolders
WSH 2.0+
Syntax
WshShell.WshSpecialFolders
Description
The WshSpecialFolders object is a child object of WshShell. Because it is not directly
accessible through the WshShell.WshSpecialFolders syntax, see the entry for
WshSpecialFolders in this chapter for more information.
WshShell.WshScriptExec
WSH 5.6+
Syntax
WshShell.WshScriptExec
Description
The WshScriptExec object is a child object of WshShell. Because it is not directly
accessible through the WshShell.WshScriptExec syntax, see the entry for
WshScriptExec in this chapter for more information.
WshShortcut
WSH 2.0+
Syntax
WshShortcut
Description
The WshShortcut object is used to create an object reference to a shortcut. It is instan-
tiated by using the createShortcut method of the WshShell object. Upon being
instantiated, it is stored in memory and not written to disk until the Save method is
called. Table 15.18 lists all the properties and methods associated with the
WshShortcut object.
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2005
Example
Listing 15.87 shows how the WshShortcut object is instantiated within memory,
assigned a target path, and then saved to disk.
// Create a shortcut.
var urlShortcut = WshShellObj.CreateShortcut(“c:\\gopack.url”);
urlShortcut.TargetPath = “http://www.gopack.com”;
urlShortcut.Save();
</script>
</job>
WshShortcut.Arguments
WSH 2.0+
Syntax
WshShortcut.Arguments
Description
The Arguments property provides access to the arguments collection through the
WshArguments object.
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2006
Example
In Listing 15.88 creates a new WshShortcut object and then sets the path to the argu-
ment value entered. So if the script named listing88.wsf were run from the command
line with the following command:
cscript listing88.wsf http://www.w3c.org
The shortcut would be created with the target pointing to the entered URL. Then the
target path is output to the user.
// Create a shortcut.
var urlShortcut = WshShellObj.CreateShortcut(“c:\\myShortcut.url”);
urlShortcut.TargetPath = myArgs.item(0);
</script>
</job>
WshShortcut.Description
WSH 2.0+
Syntax
WshShortcut.Description
Description
The Description property returns a string value containing the description of the
shortcut.
Example
In Listing 15.89 a shortcut object is created and the description is set. When executed,
the description is displayed to the user.
// Create a shortcut.
var myShortcut = WshShellObj.CreateShortcut(“c:\\gopack.lnk”);
</script>
</job>
WshShortcut.FullName
WSH 2.0+
Syntax
WshShortcut.FullName
Description
The FullName property of the WshShortcut object returns a string containing the fully-
qualified path to the shortcut. It is a read-only property.
Example
In Listing 15.90 a shortcut is created and the fully-qualified path is displayed using the
FullName property.
// Create a shortcut.
var myShortcut = WshShellObj.CreateShortcut(“c:\\gopack.lnk”);
</script>
</job>
WshShortcut.Hotkey
WSH 2.0+
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2008
Syntax
WshShortcut.Hotkey = hotKeyStr
Description
The HotKey property is used to assign a key combination to a shortcut or to identify the
key combination assigned to a shortcut. The hotKeyStr parameter is the key combina-
tion to be assigned. It is in the form of [keyModifier]KeyName. The valid
keyModifiers are Alt+, Ctrl+, Shift+, Ext+. (Ext+ means an “Extended Key”, which
refers to any new type of shift key added in the future.) Valid KeyName identifiers are
all alphanumeric keys and F1–F12 function keys.
Example
Listing 15.91 shows how to create a shortcut and then assign a hotkey to the shortcut.
// Create a shortcut.
var myShortcut = WshShellObj.CreateShortcut(“c:\\gopack.lnk”);
myShortcut.HotKey = “Alt+Shift+p”;
</script>
</job>
WshShortcut.IconLocation
WSH 2.0+
Syntax
WshShortcut.IconLocation
WshShortcut.IconLocation = iconLocationStr
Description
The IconLocation property assigns an icon to a shortcut or identifies the icon associ-
ated with a shortcut. If used to assign an icon, the parameter iconLocationStr must be
used. It should include a string to the fully-qualified path to the icon file and an index
that identifies the icon in the collection of icons contained in the file.
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2009
Example
Listing 15.92 shows a shortcut which is created and assigned an icon.
// Create a shortcut.
var myShortcut = WshShellObj.CreateShortcut(“c:\\gopack.lnk”);
myShortcut.IconLocation = “iexplorer.exe,0”;
</script>
</job>
WshShortcut.Save()
WSH 2.0+
Syntax
WshShortcut.Save()
Description
The Save() method of the WshShortcut object is used to save the shortcut to disk.
Without using the Save() method, the shortcut is only stored in memory.
Example
Listing 15.93 shows a shortcut to the gopack.com site being created and then saved to
disk with the Save() method.
// Create a shortcut.
var urlShortcut = WshShellObj.CreateShortcut(“c:\\gopack.url”);
urlShortcut.TargetPath = “http://www.gopack.com”;
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2010
</script>
</job>
WshShortcut.TargetPath
WSH 2.0+
Syntax
WshShortcut.TargetPath
Description
The TargetPath property is used to assign a path to the executable file to which the
shortcut points. It can also be used to identify the path to the shortcut executable file.
Example
Listing 15.94 uses the TargetPath property to set the target URL for the urlShortcut
object. Then the path is displayed to the user using the same TargetPath property.
// Create a shortcut.
var urlShortcut = WshShellObj.CreateShortcut(“c:\\gopack.url”);
</script>
</job>
WshShortcut.WindowStyle
WSH 2.0+
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2011
Syntax
WshShortcut.WindowStyle
WshShortcut.WindowStyle = styleValue
Description
The WindowStyle property is used to identify a window style of a shortcut. It can also
be used to assign a window style with a shortcut. If assigning a style, then a
styleValue must be specified. Valid styles are listed in Table 15.19.
Example
Listing 15.95 creates a new shortcut and assigns a window style to it.
// Create a shortcut.
var myShortcut = WshShellObj.CreateShortcut(“c:\\gopack.lnk”);
</script>
</job>
WshShortcut.WorkingDirectory
WSH 2.0+
Syntax
WshShortcut.WorkingDirectory
Description
The WorkingDirectory property is used to identify a working directory of a shortcut.
It can also be used to assign a working directory to a shortcut.
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2012
Example
Listing 15.96 creates a shortcut and then assigns the WorkingDirectory property with
a specified working directory.
// Create a shortcut.
var myShortcut = WshShellObj.CreateShortcut(“c:\\gopack.lnk”);
</script>
</job>
WshSpecialFolders
WSH 2.0+
Syntax
WshSpecialFolders
Description
The WshSpecialFolders object returns a collection of special folders. This collection
is used to retrieve paths to special folders such as Desktop, Start Menu, and My
Documents. The different types of special folders and their supported operating system
are listed in Table 15.20. In Table 15.21, all the properties and methods associated with
the WshSpecialFolders object are listed.
Example
The code in Listing 15.97 creates a new WshSpecialFolders object referencing the
Desktop special folder.
</script>
</job>
WshSpecialFolders.Count
WSH 2.0+
Syntax
WshSpecialFolders.Count
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2014
Description
The Count method returns the number of enumerated items in the WshSpecialFolders
collection. This method provides the same functionality as the length property.
Example
Listing 15.98 creates a new WshSpecialFolders object and then displays the count of
the special folders collection.
WshSpecialFolders.Item
WSH 2.0+
Syntax
WshSpecialFolders.Item(index)
Description
The Item property exposes a specific item from the WshSpecialFolders collection.
The item to be exposed is specified in the index parameter.
Example
Listing 15.99 uses the Item property to loop through the special folders collection and
get the items.
</script>
</job>
WshSpecialFolders.length
WSH 2.0+
Syntax
WshSpecialFolders.length
Description
The length property returns the number of enumerated items in the
WshSpecialFolders collection. This property provides the same functionality as the
Count() method.
Example
Listing 15.100 shows how the length property is used to display the number of enu-
merated items in the WshSpecialFolders object.
// Echo the number of items in the special folder collection using length.
WScript.Echo(“The special folder length is: “ + WshSpecialFolders.length );
</script>
</job>
WshUnnamed
WSH 5.6+
Syntax
WshUnnamed
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2016
Description
The WshUnnamed object provides access to the read-only collection of arguments with-
out associated names. The WshUnnamed object is returned from the Unnamed property of
the WshArguments object. A named parameter is one that is made up of a key/value pair
in which the key and value are separated with a colon (:) and the key is proceeded by
a forward slash (/). Table 15.22 lists all the properties and methods associated with the
WshUnnamed object.
Example
Listing 15.101 creates a WshArgument object, called WshArgsObj. The Unnamed prop-
erty is then used to access the WshUnnamed object, which is used to display the unnamed
parameters, if such parameters should exist. For example, let us assume that the script
named listing101.wsf was run using the following line:
cscript listing101.wsf /color:green blue red
The string and then the unnamed parameters blue and red would be displayed.
if(WshUnnamedArgsObj.length)
{
WScript.Echo(“Unnamed Arguments:”);
{
WScript.Echo(“No unnamed arguments”);
}
</script>
</job>
WshUnnamed.Count()
WSH 5.6+
Syntax
WshUnnamed.Count()
Description
The Count() method returns the number of WshUnnamed objects in the collection.
Example
Listing 15.102 creates a WshArgument object, called WshArgsObj. The Unnamed prop-
erty is then used to access the WshUnnamed object, which is used to display the count of
unnamed parameters, if such parameters should exist. For example, let us assume that
the script named listing102.wsf was run using the following line:
cscript listing102.wsf /color:green blue red yellow
if(WshUnnamedArgsObj.length)
{
// Echo the count of unnamed parameters.
WScript.Echo(“The count of WshUnnamed object is: “ + WshUnnamedArgsObj.Count);
}
else
{
WScript.Echo(“No unnamed arguments”);
}
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2018
WshUnnamed.Item
WSH 5.6+
Syntax
WshUnnamed.Item
Description
The Item property provides access to each item in the WshUnnamed collection.
Example
Listing 15.103 creates a WshArgument object, called WshArgsObj. The Unnamed prop-
erty is then used to access the WshUnnamed object, which is used to display the count of
unnamed parameters, should such parameters exist. For example, let us assume that the
script named listing103.wsf was run using the following line:
cscript listing103.wsf /color:green blue red yellow orange
if(WshUnnamedArgsObj.length)
{
WScript.Echo(“Unnamed Arguments:”);
</script>
</job>
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2019
WshUnnamed.length
WSH 5.6+
Syntax
WshUnnamed.length
Description
The length property returns the number of command-line arguments passed to a script.
This is the same as the Count property.
Example
The code in Listing 15.104 creates a WshArgument object, called WshArgsObj. The
Unnamed property is then used to access the WshUnnamed object, which is used to dis-
play the count of unnamed parameters, if such parameters should exist. For example,
let us assume that the script named listing104.wsf was run using the following line:
cscript listing104.wsf /color:green blue red yellow
WshUrlShortcut
WSH 2.0+
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2020
Syntax
WshUrlShortcut
Description
The WshUrlShortcut object creates a shortcut to an Internet resource. It is instantiated
by using the createShortcut method of the WshShell object. Upon being instantiated,
it is stored in memory and not written to disk until the Save method is called. Table
15.23 lists all the properties and methods associated with the WshUrlShortcut object.
Example
Listing 15.105 shows how to create a new WshUrlShortcut object. An Internet link to
the www.borders.com site is created within memory.
//Create a shortcut.
var urlShortcut = WshShellObj.CreateShortcut(“c:\\borders.url”);
urlShortcut.TargetPath = “http://www.borders.com”;
</script>
</job>
WshUrlShortcut.FullName
WSH 2.0+
Syntax
WshUrlShortcut.FullName
Description
The FullName property is a read-only string that contains the fully-qualified path to the
WshUrlShortcut object.
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2021
Example
Listing 15.106 uses the FullName property to display its value.
// Create a shortcut.
var urlShortcut = WshShellObj.CreateShortcut(“c:\\borders.url”);
urlShortcut.TargetPath = “http://www.borders.com”;
</script>
</job>
WshUrlShortcut.Save()
WSH 2.0+
Syntax
WshUrlShortcut.Save()
Description
The Save() method is used to save the WshUrlShortcut object to disk. When the object
is initially created, it lives only in memory and is not written to disk unless the Save()
method is used.
Example
Listing 15.107 uses the Save() method to store the shortcut to disk.
// Create a shortcut.
var urlShortcut = WshShellObj.CreateShortcut(“c:\\bmw.url”);
urlShortcut.TargetPath = “http://www.bmwusa.com”;
30 0672321416 CH15c 7/30/01 2:01 PM Page CD:2022
</script>
</job>
WshUrlShortcut.TargetPath
WSH 2.0+
Syntax
WshUrlShortcut.TargetPath
Description
The TargetPath property is used to either assign or identify the path to the executable
file for which the shortcut was created.
Example
In Listing 15.108 a WshUrlShortcut object is created and its TargetPath property is
set.
// Create a shortcut.
var urlShortcut = WshShellObj.CreateShortcut(“c:\\vatech.url”);
urlShortcut.TargetPath = “http://www.vt.edu”;
</script>
</job>
31 0672321416 Index 7/30/01 2:03 PM Page CD:2169
31 0672321416 Index 7/30/01 2:03 PM Page CD:2170
31 0672321416 Index 7/30/01 2:02 PM Page CD:2023
INDEX
Symbols
~ (bitwise NOT operator), 224
: (colon), 72-74, 284, 573, 580, 589,
CD:2016
, (comma), 214-215
. (dot) (pattern matching character), 86
# (hash symbol), 578, 885
“ “ (double quotation marks), 35, 1215
‘ ‘ (single quotation marks), 35
_ (underscore), 37
( ) (parentheses), 61
(…) (pattern matching character), 87
$ (pattern matching character), 87
$1,$2,…$9 property, 474
-- (decrement operator), 48-49, 204-205
--> comment tags (HTML), 33
{ } (curly brackets), 63-65, 77
{x} (pattern matching character), 87
{x,y} (pattern matching character), 86
! (logical NOT operator), 55, 205-206
!= (not equal operator), 57, 206-207
31 0672321416 Index 7/30/01 2:02 PM Page CD:2024
CD:2024 !==
!== (non-identity operator), 58, 207-208 <!-- --> comment tags (HTML), 33
* (pattern matching character), 87 << (shift left operator), 61, 229-230
* (multiplication operator), 47, 213 <<= (shift left assignment operator), 53,
*= (multiplication assignment operator), 230-231
52, 213-214 > (greater than operator), 57, 235-236
= (assignment operator), 37, 232 >= (greater than or equal operator), 58,
== (equal operator), 56-57, 233-234 236-237
=== (identity operator), 58, 234-235 >> (shift right with sign operator), 61,
? (question mark), 573, 886, 1323 237-238
? (pattern matching character), 87 >>= (shift right with sign assignment oper-
?: (conditional operator), 58-59, 218-219 ator), 53, 238-239
& (bitwise AND operator), 60, 210-211 >>> (shift right zero fill operator), 61,
&= (bitwise AND assignment operator), 53, 239-240
212-213 >>>= (shift right zero fill assignment oper-
&& (logical AND operator), 211-212 ator), 53, 240-241
^ (bitwise exclusive OR operator), 219 @cc_on statement, 200
^ (pattern matching character), 87 @if statement, 200-201
^ (XOR bitwise operator), 60 @set property, 201-202
^= (bitwise exclusive OR assignment oper- @_alpha variable, 193-194
ator), 53, 220-221 @_jscript build variable, 195
| (pattern matching character), 87 @_jscript variable, 194
| (OR bitwise operator), 60, 221, 646 @_jscript version variable, 196
|= (bitwise OR assignment operator), 53, @_jscript_build variable, 195
223-224 @_jscript_version variable, 195
|| (logical OR operator), 55, 222-223 @_mac variable, 196
% (modulus operator), 47, 208-209 @_mc680x0 variable, 197
%= (modulus assignment operator), @_PowerPC variable, 197-198
209-210 @_win16 variable, 198
%== (assignment) operator, 53 @_win32 variable, 199
%% (AND) logical operator, 55 @_x86 variable, 199-200
- (bitwise NOT operator), 60 / (division operator), 47, 215
- (subtraction operator), 46-47, 202-203 / (forward slash), 86, 573, 587, CD:2016
- (unary negation operator), 49, 203-204 /n character, 1290
-= (subtraction assignment operator), 52, /r character, 1290
232-233 /= (division assignment operator), 52, 217
+ (addition operator), 46, 49-50, 53, 225 /* */ comment tags (C), 33
+ (pattern matching character), 87 /* / (multiline comments), 216
+ (plus sign), 563 // (single-line comments), 33, 216-217
+= (addition assignment operator), 52, //? (wscript.exe and cscript.exe option), 185
227-228 //B (wscript.exe and cscript.exe option),
++ (increment operator), 48, 226-227 185
[ ] (square brackets) operator, 40, 250 //D (wscript.exe and cscript.exe option),
[…] (pattern matching character), 86 185
[\b] (pattern matching character), 86 //E:engine (wscript.exe and cscript.exe
[^…] (pattern matching character), 86 option), 185
[^x-y] (pattern matching character), 86 //H:cscript (wscript.exe and cscript.exe
[x-y] (pattern matching character), 86 option), 185
< (less than comparison operator), 57-58, //H:wscript (wscript.exe and cscript.exe
228-229 option), 185
<= (less than or equal operator), 58, //I (wscript.exe and cscript.exe option), 185
231-232 //Job:<jobID>(wscript.exe and cscript.exe
<!-- comment tags (HTML), 33 option), 185
31 0672321416 Index 7/30/01 2:02 PM Page CD:2025
addition assignment operator (+=), 227-228 all property (Document object), 636
ADDITION constant (MutationEvent ALL RAW variable (ServerVariables
object), CD:1756 collection), 1324
addition operator (+), 46, 49-50, 53, 225 ALT MASK modifier, code to access, 707
AddPrinterConnection( ) method alt property
(WshNetwork object), CD:1964-1965 code, CD:1491, CD:1499, CD:1579,
addResponseHeader( ) function, 1176-1177 CD:1589
AddWindowsPrinterConnection( ) method, HTMLAppletElement object, CD:1490
code, CD:1966 HTMLAreaElement object, CD:1497
advanced assignment, 52-53 HTMLImageElement object, CD:1577
agent property (request object), 1327-1328 HTMLInputElement object, CD:1585
alert boxes altKey property (MouseEvent object),
code, 1090 CD:1748-1749
displaying, code, 606-609, 627-628 altText parameter (blobImage( ) method),
onResize event handler code, 1133 1190
type properties, code to display, 992, alwaysLowered parameter (Window
1041-1042, 1059-1060, 1080-1081 object), 1134
alert method (Window object), 1085 alwaysRaised parameter (Window object),
alert( ) method, 103-106, 1090 1134
align parameter (blobImage( ) method), anchor length property, hyperlinks,
1190 642-643
align property anchor( ) method (String object), 498
code, 998, CD:1491-1493, CD:1523, Anchor object, 564-565
CD:1564-1566 name property, 566-567
HTMLAppletElement object, CD:1490 text property, 567-568
HTMLDivElement object, CD:1523 unwatch( ) method, 568-569
HTMLHeadingElement object, CD:1564 watch( ) method, 569-570
HTMLHRElement object, CD:1565 x property, 570-571
HTMLIFrameElement object, CD:1570 y property, 571
HTMLImageElement object, CD:1577 anchors, iterating, code, CD:1526-1527
HTMLInputElement object, CD:1585 anchors property
HTMLLegendElement object, CD:1605 array, anchor names, 642
HTMLObjectElement object, CD:1624 Document object, 636
HTMLParagraphElement object, HTMLDocument object, CD:1525
CD:1648 window.document property, 1108
HTMLTableCaptionElement object, AND (%%) logical operator, 55
CD:1673 AND (&) bitwise operator, 60
HTMLTableCellElement object, AOL, Web browser, 108
CD:1674 AppActivate( ) method (WshShell object),
HTMLTableColElement object, CD:1990-1991
CD:1684 appCodeName property (navigator object),
HTMLTableElement object, CD:1688 904-905
HTMLTableRowElement object, appendChild( ) method (Node object),
CD:1703 CD:1455-1457
HTMLTableSectionElement object, appendData( ) method (CharacterData
CD:1710 object), CD:1407, CD:1410
Style object, 649, 662, 688, 995 AppendToLog( ) method (Response
aLink property (HTMLBodyElement object), 1335-1336
object), CD:1507-1509 APPL MD PATH variable
alinkColor property, 636-638, 1108 (ServerVariables collection), 1324
ALL HTTP variable (ServerVariables col- APPL PHYSICAL PATH variable
lection), 1324 (ServerVariables collection), 1324
31 0672321416 Index 7/30/01 2:02 PM Page CD:2027
CD:2028 areas
attributes CD:2029
CD:2030 attributes
code CD:2035
CD:2036 code
code CD:2037
CD:2038 code
code CD:2039
CD:2040 code
code CD:2041
CD:2042 code
code CD:2043
CD:2044 code
code CD:2045
CD:2046 code
code CD:2047
nodeType propertym checking, CD:1465 onKeyUp event handler, 676, 816, 874,
nodeValue property, processing, 1077-1078
CD:1465-1466 onLoad event handler, 677, 817,
noHref property, CD:1500-1501 846-847, 1132
noResize property, CD:1559 onMouseDown event handler, 677-678,
normalize( ) method, CD:1466 874-875
noShade property, CD:1566-1567 onMouseOut event handler, 585-586,
notationName property, reading, 847-848, 875-876
CD:1445-1446 onMouseOver event handler, 586-587,
notations property, reading, CD:1428 848-849, 876-877
noWrap property, CD:1681 onMouseUp event handler, 678-679, 877
Number constructor, 440 onMove event handler, 786, 1132
Number( ) method, 377, 439 onOnMouseDown event handler, 608
Number property, 1187, CD:1982-1983 onOnMouseUp event handler, 609
number property (Error object), display- onReset event handler, 771-772
ing, 345 onResize event handler, 786-787, 1133
Number.valueOf( ) method, 451 onSelect event handler, 1058, 1078-1079
numbers, adding or concatenating, 225 onSubmit( ) method, 772-773
Object object, 453 OnTransactionAbort event, 1310
object property, CD:1495-1496 OnTransactionCommit event, 1310
ObjectContext object, 1309 onUnload event handler, 680, 1133
offscreenBuffering property, 1129 open( ) method, 680, 1136-1137,
onAbort event handler, 814-815 CD:1534
onBlur event handler, 844-845, 928-929, opener property, 1138-1139
946-947, 1038-1039, 1055, 1130 Option object, 915
accessing, 784-785 options property, CD:1665-1666
alert boxes, code to display, 606 options property array, retrieving select
alert boxes, displaying, 627-628 box properties, 988-989
onChange event handler, 754-755, Organization property, 1362
985-986, 1056, 1073-1074 outerHeight property, 1139-1140
onClick event handler, 871, 947-948, outerWidth property, 1141
960 outParamCount( ) method, 1390-1391
alert boxes, code to display, 607 outParameters( ) method, 1391-1392
click events, code, 672 ownerDocument property, reading,
messages, displaying, 629-630 CD:1467
textbox contents, displaying, ownerElement property, CD:1406
1039-1040 ownerRule property, reading, CD:1803
onDblClick event handler, 585, 673, 872 Packages object, 460-461
onDragDrop event handler, 1130 Packages.className property, 461
onError event handler, 815, 1131 Packages.java subpackage, 462
onFocus event handler, 755-756, paddingBottom property, 1019
845-846, 948-949, 1040-1041, paddingLeft property, 1019-1020
1131-1132 paddingRight property, 1020-1021
alert boxes, code to display, paddings( ) method, 1021-1022
607-608 paddingTop property, 1022-1023
cheese, selecting, 630-631 pages, accessing, 1117-1118
onKeyDown event handler, 674, 815, pageX property, 707-708, 849-850
872, 1076 pageXOffset property, 1142-1143
onKeyPress event handler, 675, 816, pageY property, 709, 850-851
873, 1076-1077 pageYOffset property, 1143-1144
31 0672321416 Index 7/30/01 2:03 PM Page CD:2048
CD:2048 code
code CD:2049
CD:2050 code
code CD:2051
CD:2052 code
code CD:2053
CD:2054 code
CD:2056 constants
C D : 2 0 6 0 C S S R u l e . c s s Te x t p r o p e r t y
functions CD:2075
CD:2076 functions
handlers CD:2077
CD:2078 handling
H T M LTa b l e S e c t i o n E l e m e n t . r o w s p r o p e r t y C D : 2 0 8 5
C D : 2 0 8 6 H T M LTa b l e S e c t i o n E l e m e n t . v A l i g n p r o p e r t y
interfaces CD:2087
keywords CD:2089
CD:2090 keywords
methods CD:2093
CD:2094 methods
methods CD:2095
CD:2096 methods
methods CD:2097
CD:2098 methods
methods CD:2099
CD:2100 methods
methods CD:2101
GetAbsolutePathName( ) GetParentFolderName( )
(FileSystemObject object), CD:1865, (FileSystemObject object), CD:1865,
CD:1877 CD:1885
getAttribute( ), CD:1434-1436, CD:1443 getPosition( ), 1275, 1285
getAttributeNode( ), CD:1434-1436 getPropertyCSSValue( ), CD:1792-1794
getAttributeNodeNS( ), CD:1434, getPropertyPriority( ), CD:1792,
CD:1437 CD:1795
getAttributeNS( ), CD:1434, CD:1437 getPropertyValue( ), CD:1793-1796
GetBaseName( ) (FileSystemObject getRectValue( ), CD:1781-1783
object), CD:1865, CD:1878 getRGBColor( ), CD:1781-1784
getComputedStyle( ), CD:1818-1819 getSeconds( ) (Date object), 287,
getCounterValue( ), CD:1781-1782 295-296
getDate( ) (Date object), 286, 289-290 getSelection( ), 637, 1108
getDay( ) (Date object, 286, 290-291 getSlot( ), 397, 403
GetDrive( ) (FileSystemObject object), GetSpecialFolder( ) (FileSystemObject
CD:1833-1834, CD:1865, CD:1879 object), CD:1865, CD:1885-1886
GetDriveName( ) (FileSystemObject getStringValue( ), CD:1781, CD:1784
object), CD:1865, CD:1879-1880 GetTempName( ) (FileSystemObject
getElementById( ), 149, 152, CD:1413 object), CD:1865, CD:1886-1887
getElementsByName( ), CD:1525, getTime( ) (Date object), 287, 296-297
CD:1531-1532 getTimezoneOffset( ) (Date object), 287,
getElementsByTagName( ), CD:1413, 297
CD:1434, CD:1438 getUTCDate( ) (Date object), 287, 298
getElementsByTagNameNS( ), getUTCDay( ) (Date object), 287,
CD:1413, CD:1434, CD:1438-1439 298-299
GetExtensionName( ) getUTCFullYear( ) (Date object), 287,
(FileSystemObject object), 300
CD:1880-1881 getUTCHours( ) (Date object), 287,
GetFile( ) (FileSystemObject object), 300-301
CD:1865, CD:1882 getUTCMilliseconds( ) (Date object),
GetFileName( ) (FileSystemObject 287, 301
object), CD:1865, CD:1882-1883 getUTCMinutes( ) (Date object), 287,
getFloatValue( ), CD:1781-1783 301-302
GetFolder( ) (FileSystemObject object), getUTCMonth( ) (Date object), 287,
CD:1865, CD:1883-1884 302-304
getFullYear( ) (Date object), 286, getUTCSeconds( ) (Date object), 287,
291-292, 305 304
getHours( ) (Date object), 286, 292 getVarDate( ) (Date object), 287,
getItem (VBArray object), 551 304-305
GetLastError( ), 1368-1370 getWindow( ), 397, 403
getLength( ), 1275, 1284 getWrappedException( ), 395-396
getMember( ), 397, 402 getYear( ) (Date object), 287, 305-306
getMilliseconds( ) (Date object), 286, Global object, 365
292-293 Global.escape( ), 370
getMinutes( ) (Date object), 287, 293 Global.isFinite( ), 374
getMonth( ) (Date object, 287, 294-295 Global.Number( ), 376-377
getNamedItem( ), CD:1448-1449 Global.parseFloat, 377
getNamedItemNS( ), CD:1449 Global.parseInt, 378
GetObject( ), CD:1929, CD:1935 Global.String, 379
getOverrideStyle( ), CD:1809-1810 Global.unescape, 380
go( ), 799, 802, 1117
31 0672321416 Index 7/30/01 2:03 PM Page CD:2102
CD:2102 methods
methods CD:2103
CD:2104 methods
methods CD:2105
CD:2106 methods
methods CD:2107
CD:2108 methods
methods CD:2109
CD:2110 methods
methods CD:2111
CD:2112 methods
objects CD:2117
CD:2118 objects
KeyUp events, code, 676 open( ) method, 141, 175, 637, 680, 1108
Link object, 865 OpenAsTextStream( ) method (File object),
onTextarea object, 1063 CD:1845, CD:1854-1856
window.document property, 1108 opener property, 1087, 1138-1139
onLoad event handler, 92, 118, 677, 817, opening
846-847, 1132 documents, code, 680
Document object, 637 files, code, 1286
Image object, 808 OpenTextFile( ) method, CD:1865,
onLoad property (Layer object), 822 CD:1889-1890
onMouseDown event handler, 92, 677-678, Opera, Web site, 108,-109 114, 563
874-875 operations, OR (|), returning values, 60
Button object, 598 operators
Document object, 637 % (modulus), 47
window.document property, 1108 %= (assignment), 53
onMouseDown property (Link object), 865 &= (assignment), 53
onMouseMove event handler, 92 * (multiplication), 47
onMouseOut *= (assignment), 52
event handler, 92, 574, 585-586, + (addition), 46, 49-50, 53
847-848, 875-876 ++ (post-increment), 48
property, 822, 865 ++ (pre-increment), 48
onMouseOver += (assignment), 52
event handler, 92, 574, 586-587, - (subtraction), 46-47
848-849, 876-877 - (unary), 49
property, 822, 865 -= (assignment), 52
onMouseUp -- (post-decrement), 49
event handler, 92, 598, 637, 678-679, -- (pre-decrement), 48-49
877, 1108 / (division), 47, 215
property (Link object), 865 /= (assignment), 52
onMove = (assignment), 37
event handler, 92, 786, 1132 addition (+), 225
property (Frame object), 778 addition assignment (+=), 227-228
onOnMouseDown event handler, alert arithmetic, 45-50
boxes, code to display, 608 assignment, 50-54
onOnMouseUp event handler, alert boxes, assignment (=), 232
code to display, 609 bitwise, 59-61
onReset AND (&), 210-211
event handler, code, 92, 771-772 AND assignment (&=), 212-213
property (Form object), 761 exclusive OR (^), 219
onResize exclusive OR assignment (^=),
event handler, code, 92, 786-787, 1133 220-221
property (Frame object), 778 NOT (~), 224
onSelect event handler, 92, 1046, 1058, OR (|), 221
1063, 1078-1079 OR assignment (|=), 223-224
onSubmit comparison, 55-58
event handler, 92 conditional (?:), 58, 218-219
property (Form object), 761 decrement (--), 204-205
onSubmit( ) method, code, 772-773 delete, 331-332
OnTransactionAbort event, 1308-1310 division assignment (/=), 217
OnTransactionCommit event, 1308-1310 equal (==), 233-234
onUnload event handler, 92, 637, 680, 1133 greater than (>), 235-236
OOP (object-oriented programming), 7-17 greater than or equal (>=), 236-237
31 0672321416 Index 7/30/01 2:03 PM Page CD:2121
p a d d i n g To p p r o p e r t y C D : 2 1 2 1
platform CD:2123
CD:2124 plug-ins
properties CD:2125
CD:2126 properties
properties CD:2127
CD:2128 properties
properties CD:2129
CD:2130 properties
properties CD:2131
CD:2132 properties
properties CD:2133
CD:2134 properties
properties CD:2135
CD:2136 properties
properties CD:2137
CD:2138 properties
properties CD:2139
CD:2140 properties
properties CD:2141
CD:2142 properties
properties CD:2143
CD:2144 properties
CD:2146 readability
scripting CD:2149
CD:2150 scripting
SYSTEMDRIVE CD:2155
URIs CD:2159
url property (HTMLDocument object), code, 797, 920-921, 932, 951, 964
CD:1525 FileUpload object, 746
URL property, 637, 692, 1109, Hidden object, 793
CD:1535-1536 HTMLButtonElement object, CD:1513
URL variable (ServerVariables collection), HTMLInputElement object, CD:1586
1326 HTMLLIElement object, CD:1607
URLEncode( ) method, 1369, 1372 HTMLOptionElement object, CD:1641
usage information (scripts), CD:1950 HTMLParamElement object, CD:1649
useMap property HTMLSelectElement object, CD:1659
code, CD:1583-1584, CD:1599, Option object, 915
CD:1635 Password object, 922
HTMLImageElement object, CD:1577 Radio object, 938
HTMLInputElement object, CD:1586 Reset object, 952
HTMLObjectElement object, CD:1624 Submit object, 1030, 1043-1044
user interface events, CD:1761, CD:1763 text areas, 1082-1083
user interfaces, 154-156 text boxes, 1061-1062
user sessions, 171 Text object, 1046
userAgent property, 904, 913 Textarea object, 1064
UserDomain property, CD:1964, CD:1971 valueOf( ) method
UserName property, CD:1964, CD:1972 Array object, 271
UTC( ) method, 288, 326-327 Boolean object, 274, 279
UTF-8 standard Web site, 366 code, 363-364, 458
\uXXXX escape sequence, 36 Date object, 327
Function object, 353
V Number object, 440
Object object, 453
-v command-line parameter, 161 RegExp object, 467
ValidatePersonalInfo function, 135 values, 1252. See also return values
validation, 98-101, 135 assigning, 54
ValidFrom field (ClientCertificate collec- attributes, CD:1405-1406
tion), 1320 call by value (functions), 77-78
ValidUntil field (ClientCertificate collec- cookies, 138-139
tion), 1320 counter, CD:1782
vAlign property drive type, CD:1835
code, CD:1683, CD:1687, CD:1709, float, CD:1782-1786
CD:1714 Folder.Attributes property,
HTMLTableCellElement object, CD:1892-1893
CD:1674 functions, 79
HTMLTableColElement object, modifiers, 707
CD:1684 numbers, 34-35
HTMLTableRowElement object, primitive Boolean versus Boolean
CD:1703 object, 274
HTMLTableSectionElement object, rect, CD:1783
CD:1710 reference points, 1290
value argument (Boolean object), 273 returning, 60, 79-80
value property string, CD:1784-1786
accessing, 990-991 Submit object, 1043-1044
Attr object, CD:1404 text areas, 1066-1067, 1082-1083
attributes, CD:1405-1406 text boxes, 76, 1049, 1061-1062
Button object, 598 undefined, 36
button’s text, 612-613 variables, 37-38
Checkbox object, 615
31 0672321416 Index 7/30/01 2:03 PM Page CD:2161
verifying CD:2161
CD:2162 versatility
w i n d o w. o n F o c u s e v e n t h a n d l e r C D : 2 1 6 3
C D : 2 1 6 4 w i n d o w. o n L o a d e v e n t h a n d l e r
CD:2166WshRemote object
X-Y-Z
x property (Anchor object), 564
XML, 155, CD:1416
XML-based User Interface Language
(XUL), 154-154
XOR (>) bitwise operator, 60
XUL (XML-based User Interface
Language), 154-156
\XX escape sequence, 36
\XXX escape sequence, 36
www.informit.com
from all our publishing partners, including Sams Publishing ■ Free, unabridged
books from the InformIT Free Library ■ “Expert Q&A”—our live, online chat
with IT experts ■ Faster, easier certification and training from our Web- or
By opening this package, you are agreeing to be bound by the following agreement:
You may not copy or redistribute the entire CD-ROM as a whole, Copying and redistribution of individual
software programs on the CD-ROM is governed by terms set by individual copyright holders.
The installer and code from the author(s) are copyrighted by the publisher and the author(s). Individual pro-
grams and other items on the CD-ROM are copyrighted or are under GNU license by their various authors
or other copyright holders.
This software is sold as-is without warranty of any kind, either expressed or implied, including but not lim-
ited to the implied warranties of merchantability and fitness for a particular purpose. Neither the publisher
nor its dealers or distributors assumes any liability for any alleged or actual damages arising from the use of
this program. (Some states do not allow for the exclusion of implied warranties, so the exclusion may not
apply to you.)
NOTE: This CD-ROM uses long and mixed-case filenames, requiring the use of a protected-mode
CD-ROM Driver.
Installation Instructions
Windows
1. Insert the disc into your CD-ROM drive.
2. From the Windows desktop, double-click the My Computer icon.
3. Double-click the icon representing your CD-ROM drive.
4. Double-click on start.exe. Follow the on-screen prompts to finish the installation.
NOTE: If you have the AutoPlay feature enabled, start.exe will be launched automatically whenever
you insert the disc into your CD-ROM drive.
Macintosh
1. Insert the disc into your CD-ROM drive.
2. Double-click the Pure JavaScript icon when it appears on your desktop.
3. Double-click on start. Follow the on-screen prompts to finish the installation.
Linux/Unix
These installation instructions assume that you have a passing familiarity with Unix commands and the basic
setup of your machine. As Unix has many flavors, only generic commands are used. If you have any prob-
lems with the commands, please consult the appropriate manual page or your system administrator.
Insert the disc into your CD-ROM drive.
If you have a volume manager, mounting of the CD-ROM will be automatic. If you don’t have a volume
manager, you can mount the CD-ROM by typing
mount -tiso9660 /dev/cdrom /mnt/cdrom
NOTE:/mnt/cdrom is just a mount point, but it must exist when you issue the mount command. You
may also use any empty directory for a mount point if you don’t want to use /mnt/cdrom.