JavaScript Tutorial PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 223
At a glance
Powered by AI
The document discusses guidelines for JavaScript development, common uses of JavaScript, and additional event object properties in DOM events.

Developers should support browsers without JavaScript enabled, detect browser capabilities instead of versions, and provide alternatives for unsupported features using <noscript> tags.

JavaScript can be used to modify forms, change images, open windows, and dynamically generate content using DHTML.

5/30/2015

JavaScripttutorial

JavaScripttutorial
Tableofcontents

Importantguidelines
IntroductiontoJavaScript
Examples
AddingJavaScripttoapage
Objectorientedprogramming
Operators
Variables
Controlstructures
Writingwithscript
Writingfunctions
Referencing
Browserinspecificreferencing
Browserspecificreferencing
DHTML
Elementcontents
Windowsizeandscrolling
Eventinformation
Creatingobjects
Creatingtimedelays
Usingcookies
Security
Semicolons
TheJavaScriptobject
W3CDOMintroduction
DOMnodesandtree
DOMtables
DOMCSS
DOMStyleSheets
DOMevents
DOMobjectsandmethods

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

1/223

5/30/2015

JavaScripttutorial

Importantguidelines

First let's learn some important stuff. There are lots of browsers out there that cannot support
JavaScript. Although browsers generally support more and more with each release, the language
itself keeps evolving, and there is already a vast amount of the JavaScript language available for
browserstosupport.Nobrowserwilleversupportallofit,andyoucannotexpectthemto.
Therearemanyreasonswhypeoplecannotorwillnot'upgrade'toyourchosenbrowser.Afeware:
Theyareatworkandtheycanonlyusethesystemdefaultbrowser.
Theywanttoviewpagesmorequicklysotheyuseatextonlybrowser.
Theyareblindorhavepooreyesightsotheyneedatextonlybrowser/reader/Braillereader.
TheyrealisethatthemoreextrafeatureslikeJavaScriptorVBScriptyouuse,themoreyouleave
yourselfopentobecomingatargetforvirusesorvulnerabilityexploits.
They don't like the way some sites insist on taking over their control of the browser, opening
popup windows, breaking the operation of the back button, preventing the context menu from
working, or insisting on making things appear and disappear in a way that causes usability
problems.
Whatevertheirreasons,youshouldnotstopthemfromusingyoursite.IfyoursiteusesJavaScript
for navigation or content, then that navigation and content should be there without JavaScript
enabled.YourJavaScriptcanextractcontentfromthepage,anddowhateveritwantswiththat,but
youshouldmakesurethatcontentisavailablewithoutthescript.Ifyouwanttouseascriptinway
thatyoucannotsimplyextracttheinformationfromthestaticpage,thenyoushoulduse <noscript>
toprovideanalternativeforpeoplethatcannotrunyourscript.
Therearealsomanybrowsersouttherethatyoudonotrealiseexist.Iknowofwelloverahundred
different browsers that support JavaScript to varying degrees. If your script uses something that
browsersmaynotsupport,youshoulddetectifthebrowseriscapableofusingit,andthenfallback
toanaccessiblealternativeifitdoesn't.
Thereisnomagicformulaforthis,butthebasicrulesarethatyoushouldnotdetectabrowsermake
orversion.Youwillgetitwrong,andyouwillmistakenlydetectonebrowserandthinkitisanother,
ending up with you using the wrong code. You will make incorrect assumptions about current and
futurebrowsers,andyouwillcauseproblemsforyourusers.
Thistutorialshouldhelpyoulearnhowtocorrectlydetectcapabilities,andwhereverneeded,itwill
showyouhowtoworkoutwhenabrowsercannotdowhatyouneed,soyoucanhaltyourscript,or
provideanalternative.Whentherearedifferentwaystodothesamething,andsomebrowsersonly
support one, while others support another, it will show you how to correctly work out which one to
use.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

2/223

5/30/2015

JavaScripttutorial

IntroductiontoJavaScript

JavaScript is a programming language that can be included on web pages to make them more
interactive. You can use it to check or modify the contents of forms, change images, open new
windowsandwritedynamicpagecontent.YoucanevenuseitwithCSStomakeDHTML(Dynamic
HyperText Markup Language). This allows you to make parts of your web pages appear or
disappear or move around on the page. JavaScripts only execute on the page(s) that are on your
browser window at any set time. When the user stops viewing that page, any scripts that were
running on it are immediately stopped. The only exceptions are cookies or various client side
storageAPIs,whichcanbeusedbymanypagestostoreandpassinformationbetweenthem,even
afterthepageshavebeenclosed.
Before we go any further, let me say JavaScript has nothing to do with Java. If we are honest,
JavaScript, originally nicknamed LiveWire and then LiveScript when it was created by Netscape,
should in fact be called ECMAscript as it was renamed when Netscape passed it to the ECMA for
standardisation.
JavaScriptisaclientside,interpreted,objectoriented,highlevelscriptinglanguage,whileJavaisa
client side, compiled, object oriented high level language. Now after that mouthful, here's what it
means.
Clientside
Programs are passed to the computer that the browser is on, and that computer runs them.
Thealternativeisserverside,wheretheprogramisrunontheserverandonlytheresultsare
passed to the computer that the browser is on. Examples of this would be PHP, Perl, ASP,
JSPetc.
Interpreted
The program is passed as source code with all the programming language visible. It is then
converted into machine code as it is being used. Compiled languages are converted into
machine code first then passed around, so you never get to see the original programming
language. Java is actually dual half compiled, meaning it is half compiled (to 'byte code')
beforeitispassed,thenexecutedinavirtualmachinewhichconvertsittofullycompiledcode
justbeforeuse,inordertoexecuteitonthecomputer'sprocessor.Interpretedlanguagesare
generallylessfussyaboutsyntaxandifyouhavemademistakesinaparttheyneveruse,the
mistakeusuallywillnotcauseyouanyproblems.
Scripting
This is a little harder to define. Scripting languages are often used for performing repetitive
tasks. Although they may be complete programming languages, they do not usually go into
the depths of complex programs, such as thread and memory management. They may use
another program to do the work and simply tell it what to do. They often do not create their
own user interfaces, and instead will rely on the other programs to create an interface for
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

3/223

5/30/2015

JavaScripttutorial

them.ThisisquiteaccurateforJavaScript.Wedonothavetotellthebrowserexactlywhatto
putonthescreenforeverypixel(thoughthereisarelativelynewAPIknownascanvasthat
makes this possible if needed), we just tell it that we want it to change the document, and it
doesit.Thebrowserwillalsotakecareofthememorymanagementandthreadmanagement,
leavingJavaScriptfreetogetonwiththethingsitwantstodo.
Highlevel
Writteninwordsthatareasclosetoenglishaspossible.Thecontrastwouldbewithassembly
code,whereeachcommandcanbedirectlytranslatedintomachinecode.
Objectoriented
Seethesectionon'objectorientedprogramming'fordetails.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

4/223

5/30/2015

JavaScripttutorial

HowisJavaScriptconstructed

Thebasicpartofascriptisavariable,literalorobject.Avariableisawordthatrepresentsapiece
oftext,anumber,abooleantrueorfalsevalueoranobject.Aliteralistheactualnumberorpieceof
textorbooleanvaluethatthevariablerepresents.Anobjectisacollectionofvariablesheldtogether
byaparentvariable,oradocumentcomponent.
Thenextmostimportantpartofascriptisanoperator.Operatorsassignliteralvaluestovariablesor
saywhattypeofteststoperform.
The next most important part of a script is a control structure. Control structures say what scripts
shouldberunifatestissatisfied.
Functionscollectcontrolstructures,actionsandassignmentstogetherandcanbetoldtorunthose
piecesofscriptasandwhennecessary.
The most obvious parts of a script are the actions it performs. Some of these are done with
operators but most are done using methods. Methods are a special kind of function and may do
thingslikesubmittingforms,writingpagesordisplayingmessages.
Events can be used to detect actions, usually created by the user, such as moving or clicking the
mouse,pressingakeyorresettingaform.Whentriggered,eventscanbeusedtorunfunctions.
Lastlyandnotquitesoobviousisreferencing.Thisisaboutworkingoutwhattowritetoaccessthe
contentsofobjectsoreventheobjectsthemselves.
Asanexample,thinkofthefollowingsituation.Apersonclicksasubmitbuttononaform.Whenthey
clickthebutton,wewanttocheckiftheyhavefilledouttheirnameinatextboxandiftheyhave,we
wanttosubmittheform.So,wetelltheformtodetectthesubmitevent.Whentheeventistriggered,
wetellittorunthefunctionthatholdstogetherthetestsandactions.Thefunctioncontainsacontrol
structurethatusesacomparisonoperatortotestthetextboxtoseethatitisnotempty.Ofcourse
we have to work out how to reference the text box first. The text box is an object. One of the
variablesitholdsisthetextthatiswritteninthetextbox.Thetextwritteninitisaliteral.Ifthetext
boxisnotempty,amethodisusedthatsubmitstheform.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

5/223

5/30/2015

JavaScripttutorial

Examples

All examples on this page and elsewhere in my JavaScript tutorial are provided free of charge.
Pleaseseethetermsandconditionspagefortermsofuse.
These examples are all useful in their own right but when used together can produce spectacular
results.Iwillleavethattoyourowncreativity.
Note that the syntax highlighted source of all the header files I use in these examples, as well as
several others, is available on my JavaScript libraries page. The header files can also be
downloadedfromthere.
Theheaderfilescriptsaremeanttoberealscriptsforrealuse,nottutorials.Ihaveincludedthem
on this page as they can be viewed as examples of real programming, not lessons on how to
program. I agree that they are not always easy to read, but that is mainly because they are
optimisedforrealuse.Youmaychoosetoseethisasabadprogrammingmethod,butIdonot,asI
canalwaysseewhatIwasintendingforthescripttodo,andithelpstocutdownonthetransmitted
filesize,somethingwhichmodemusersarealwayshappyfor.
Togiveyouanexampleofamore'friendly'format,whichiseasiertouseasalearningaid,oneof
my readers has kindly produced a reformatted version of my generic rewritable elements script,
whichisincludedintheemailtheysentme.

NonDHTML
ThemostpopularuseofJavaScriptchangingimageswhenthemousehangsoveralink
Preloadingimagesforuseinmouseoversandprecaching.

ThenextmostpopularuseofJavaScriptopeningnewbrowserwindows
Openingawindowwithcustomisablesettings.

ThenextmostpopularuseofJavaScriptwritingdynamiccontent
Changingwhatiswrittendependingonconditions.

ThenextmostpopularuseofJavaScriptcheckingforms
Formchecking,ensuringaformisfilledincorrectly.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

6/223

5/30/2015

JavaScripttutorial

Slightlylessusedbutjustasuseful,retainingvariablesfromonepageforuseonanotherpage
Complicatedstringmanipulation,takingvariablesfromthelocationbar.
Creating,readingandmodifyingcookies.

Somespecialistscripts
Formmanipulation,offeringthecorrectcountriesforacontinent.
Moreformmanipulation,expandabletreestructure.

Themostirresponsiblescript
Browser sniffing to be used only to help avoid browser specific bugs, not to determine
capability.

DHTML
Appearing/disappearingcontent
PopupMenus.
PopupMenuswithdelayseeGeckoenginebug.
AutogenerationPopupMenuswithdelayGeckoenginebugsremoved.
Tooltips.

Movablecontent
Tooltips.
Staticlogo.
Fallingobjects(snow).
Flyingstars(changesapparentsizeofdivelements).
Fireworks(demonstrateschangingcolour).
Analogueclock.
Mousetrails

Singletrailwithbouncinganimation.
Multipletrailwithseveralpossibilities.

Rewritabledocumentcontent

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

7/223

5/30/2015

JavaScripttutorial

Genericrewritableelements.
(Simple)messagescroller.

W3CDOM
ImportingXMLdatafilesaveryadvancedscriptingtopic.
Solitairegameaveryadvancedscript.
ThesescriptsanymanymoreareincludedonmyJavaScriptlibrariespage.Thepagealsocontains
several utility scripts, which you may find useful for your Web development. Please see the terms
andconditionspagefortermsofuse.

Games
Ok,sotheyarefartoocomplicatedtobeexamples,butalloftheprinciplesarethesameasIhave
described in these tutorials. These games require various different technologies like HTML, CSS,
DHTML, etc. Not all browsers will be able to use all of the games, in particular the 3D games,
becausetheyaredemandingonresources.Thesimplergamesmayevenworkinarchaicbrowsers
likeNetscape3.
Thesegamesareallonmygamessite.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

8/223

5/30/2015

JavaScripttutorial

AddingJavaScripttoapage

You can add a script anywhere inside the head or body sections of your document. However, to
keepyourdocumentwellstructuredtherearesomebasicguidelines:
Most scripts can go inside the document head. This keeps them out of the way of the main
documentcontent.
If your script needs to run at a certain stage during page layout (for example, if it uses
document.writetocreatecontent),itshouldbeputatthecorrectstageofthedocument,almost
alwayssomewhereinsidethedocumentbody.Ifthescriptisverysmall,thenputitallwhereitwill
be used. If it is larger, then put it inside the head inside a function, and you can then call that
functionwhenyouneedit.
Ifyourscriptisusedonmorethanonepage,orifitisofanysignificantsize,thenputitinitsown
file,andloaditinthedocumenthead.Notonlywillthishelptokeeptheclutterofthedocument,
butitwillalsohelpavoidpotentialsyntaxproblems(Iwillcovertheselater).Asanextrabenefit,
these can be used by multiple pages, allowing browsers to use their cache, and saving
bandwidthforyouandyourvisitors.

Addingascripttothepage
To insert JavaScript into a web page, use the <script> tag. You should use the type attribute to
specifythetypeofscriptbeingused,whichinthecaseofJavaScriptis text/javascript.Itisalso
possible to the language attribute to say what JavaScript version you are using. In practice, this
number means very little to browsers. They may claim to support a specific version, but will have
vastlydifferentcapabilities.AllJavaScriptsupportingbrowserscurrentlyinusewillsupportalevelof
JavaScript equivalent to JavaScript 1.2 (represented as "javascript1.2") or higher, so this is what I
willteachyouinthistutorial.
Browsers will generally choose an arbitrary version number that they will claim to support, and will
runanyscriptthathaseithernolanguageversionnumber,oraversionequaltoorlowerthanthe
one they claim to support. Since the language is so unreliable, you should generally omit this
attribute,althoughitiscommontoseescriptsusingit.Yourscriptcanthendetectifthebrowseris
capableofrunningyourscript,anditcandothisalotmoreaccuratelythantheversionnumbercan.
Thisisanexampleofascripttag,usedtoincludeascriptinyourpage:
<scripttype="text/javascript">
//JavaScriptgoeshere
</script>

If your script is incapable of providing its own fallback, but it is needed to access the page, you
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

9/223

5/30/2015

JavaScripttutorial

shouldincludesupportfornonJavaScriptbrowsersbyusing:
<noscript>
<p>ThiswillnotbedisplayedifJavaScriptisenabled</p>
</noscript>

Usingcomments
Commentsallowyoutoleavenotestoyourselfandotherpeopleinyourscript,andareusefulasa
reminder of what the script is doing and why. The double slash indicates a single line comment.
Everythingafteritonthesamelinewillbeignoredbythescriptengine.Theslashasteriskindicates
a block comment. Everything after it will be ignored by the script engine until an asteriskslash is
encountered.
<scripttype="text/javascript">
//Thisisasinglelinecomment
/*Thisisa
blockcomment*/
</script>

Usingexternalscriptfiles
You can also use a separate header file to contain the JavaScript (usually *.js) making it easy to
shareacrosspages:
<scriptsrc="whatever.js"type="text/javascript"></script>

Whenusingheaderfiles,ifyouputanyscriptcodeinbetweenthe <script...>and </script>tags,


it will only be executed if the browser does not support header files (assuming it does support the
versionofJavaScriptshowninthelanguageattribute,ifyouusedone).Inreality,thisisonlyforvery
oldbrowsersthatarenotusedatallanymore,sothereisnoneedforanythingtobeputthere.
Scripts in header files are executed as if they were in the main page. If the script referances any
external files, such as images, the addresses it uses are relative to the main page, not the script
URI.

Commentingoutyourscripts
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

10/223

5/30/2015

JavaScripttutorial

This is not needed any more. All current browsers are aware of script tags, and how to treat their
contents,sincetheyhavebeenpartofHTMLsinceHTML3.BrowsersthatdonotunderstandHTML
3orscripts(thesearevirtuallyneverusednow)willdisplaythescriptasifitwasthecontentofthe
page. You can hide the script from them by commenting out your script with standard HTML
comments.Browsersthatunderstandscriptwillsimplyignorethesecomments,andwilljustinterpret
thescriptwithinthem.TheopeningcommentisignoredasifitwereanormalsinglelineJavaScript
comment.Theclosingcommentwillnot,soitneedstohaveaJavaScriptcommentputbeforeit:
<scripttype="text/javascript">
<!
//JavaScriptgoeshere
//>
</script>

TheseHTMLcommentsshouldnotbeusedifyouareusinganexternalscriptfile,andarenottobe
usedanywhereelseinyourscripts.

DealingwithXHTML
NotethatwhenItalkaboutXHTML,Iamtalkingaboutpagesthatareservedusingacontenttypeof
application/xhtml+xml the majority of pages that use XHTML markup are actually served as
text/htmlandasaresultarecorrectlytreatedasHTML,notXHTML.

The rules in XHTML are different. Script tags are not treated as being special. Their contents are
treated as any other part of XHTML, so various operators can be misinterpreted as part of the
markup.Toavoidthis,itisbesttoputallscriptsinexternalscriptfilessothattheydonotinterfere
withthepageitself.Ifyoufeeltheneedtoputsomethingdirectlyonthepage,youcandeclareitas
CDATA(thedefaultforscriptcontentsinnormalHTML):
<scripttype="text/javascript">
<![CDATA[
//JavaScriptgoeshere
]]>
</script>

IfyoufeelthecompulsiontocommentoutyourscriptinXHTML,youmustuseamoreuglystructure
tocontainyourscripts.Again,thisreallyisnotneeded,sincebrowsersthatdonotunderstandscript
alsodonotunderstandXHTML,butincaseyouwanttouseit(maybeyouareservingitasXHTML
tosomebrowsers,andHTMLtoothers),thisiswhattouse:
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

11/223

5/30/2015

JavaScripttutorial

<scripttype="text/javascript">
<!//><![CDATA[//><!
//JavaScriptgoeshere
//><!]]>
</script>

Controllingwhenthescriptisactivated
Bydefault,anyscriptyouwritewillbeprocessedasthedocumentloads.Forexample:
<scripttype="text/javascript">
varmyVariable='Hello';
window.alert(myVariable);
//asthedocumentloads,amessageboxsaying'Hello'willbedisplayed
</script>

Sometimes, this may be undesirable and it may be better to write functions (see the section on
Writingfunctions)andactivatethemlater.
To activate JavaScript, you can use HTML events. Modern browsers can detect a vast number of
eventsonmostelements.Olderbrowsersaremorelimitedandcanonlydetectthestandardsetof
eventsonspecificelements.TheonesthatwillworkinallbrowsersIhavetestedare:
input,textarea,select
onclick,onkeydown,onkeyup,onkeypress,onchange,onfocus,onblur,etc.
form
onsubmit,onreset
a
onclick,onmouseover,onmouseout,onfocus,onblur
body
onload,onunload
Check with the HTML specifications on theW3Csite for more details. 'a' elements can also detect
onmousemove in all current browsers, but not some of the older browsers that are not used any
more.Forsomeoftheseolderbrowsers,suchasNetscape4,itispossibletocompensateusinga
combinationofonmouseover,onmouseoutandthendocument.captureEventsandonmousemoveon
the body (see the section on Eventinformation). The Eventinformation and more advanced DOM
eventschaptersofthistutorialshowhowtolistenformoreeventtypes,andobtaininformationfrom
them.
Thesearesomeexamplesofusingevents(shownhereusingtraditionalinlineeventhandlerslater
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

12/223

5/30/2015

JavaScripttutorial

oninthistutorial,Iwillshowyoualternativewaystoattacheventstoelementsthatwillnotrequire
youtoalteryourHTML):
<aonmouseover="name_of_function(params)"href="somepage.html">
<inputonkeypress="myVariable=2;startTest();">
<selectonchange="self.location.href=this.options[this.selectedIndex].value;">
<bodyonunload="window.alert('bye')">

Another

way

of

making

HTML

activate

JavaScript

is

to

use

<ahref="javascript:name_of_function(params)"> but in general it is best to use events, so the link

can provide an accessible alternative if JavaScript is not available (the event handler can prevent
thebrowserfromusingthelinknormallyifscriptingisavailable).
Inallthesecases,thescriptiscontainedwithinHTMLattributes,andissubjecttothenormalrulesof
HTML entities. If you need to put quotes in the script in between the quotes in the html, use the
HTML entity &quot or &#34 for " style quotes or if your quotes in the HTML are done using the '
quotes (which is unusual ...), you can use &#39 to represent these in the script. If you need to
include<or>operators,youshouldusethe&ltand&gtentities.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

13/223

5/30/2015

JavaScripttutorial

Objectorientedprogramming

Objects
An object is a 'thing'. For example a number is an object. An array is an object. Your browser
windowisanobject.Aforminyourdocumentisanobject.Therearehundredsmore,andinsome
casesyoucancreateyourown.
Objectscanhaveobjectsinthem.Forexample,yourdocumentcanhaveaforminit.Thisformisa
'child object' of the document. Therefore the document is the 'parent object' of the form. To
referencethechildobject,wehavetogothroughtheparentobject,eg.document.myForm
Anarraycanhavenumbersinitscells.Aswehavealreadydiscussed,thearrayisanobject,andso
wouldbeacellwithinit,andsoisthecontentofthecell.Wecannotrefertothecellitself,butwe
canrefertoitscontents:myArray['cellnameornumber']forexample.

Classes(ortypes)
Aclassisagroupofobjectsthataresimilarinsomeway.Forexample,anumberandapieceoftext
can both be stored as a variable (in a way, like the variables you would use in mathematical
algebra).Inessence,wecansaythatpiecesoftextandnumbersareexamplesofclass'variable'.
Numbers can be sub divided into two groups, integers and floats (or doubles). Integers are whole
numbers:1,2,3,4,0,1,2,etc.Floatshavedecimalpoints:1.1,5.7,0.5,etc.Inthiscase,wecan
saythat3isaninstanceofclassvariable,(sub)classnumber,(sub)classinteger.
In fact, a variable is a type of object. All instances of class 'object' have a certain two methods:
toString() and valueOf(). Therefore, as 3 is an instance of class object, (sub)class variable,

(sub)classnumber,(sub)classinteger,itwillinheritthetoString()andvalueOf()methodsprovided
bytheclass'object'.
ClassesarenotsoimportantinJavaScriptastheyareinmanyotherobjectorientedprogramming
languages.Classescanbecreatedwhenyoudefineyourownclassesofobjects,butitisnotusual
tocreateyourown'sub'classes.

Collections
Ifyouneedtoknowwhatarraysare,seethesectiononVariables.
Therearemanyarraysthatareinbuiltintoeachdocument.Thedocumentitselfisanarrayincertain
uses. The most obvious of these collections is the images collection. To refer to images in the
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

14/223

5/30/2015

JavaScripttutorial

document,weuse
document.images['nameofimage']

Thisisaspecialkindofarray,knownasacollection.

Properties
Take,forexample,animage.WhenwedefineimagesinHTML,wewrite:
<imgsrc="frog.gif"name="myImage"height="10"width="10"alt="Afrog">

Thepropertiesoftheimagewouldbesrc,name,height,width,altandifwealsousedStyleSheets
wemighthaveincludedseveralmore(likebackgroundcolorforexample).Allpropertiesareatype
ofobjectsotorefertothesrcofmyimage,Iwouldwritedocument.images['myImage'].src

Methods
Therearealwaysactionsthatareassociatedwithobjects.Forexample,aformmaybesubmittedor
reset. The actions are methods. To submit a form in nonobjectoriented programs, we might write
submit('nameofform')

That would simply be a function. In object oriented programming like JavaScript, we would use
document.nameOfForm.submit()

The reason this is a method and not just a function is that each form will have its own submit()
function built in, which is referred to using the object oriented syntax shown above. You will never
havetowritemethodsinyourselfunlessyoucreateyourownobjects,thebrowserdoesthatforyou.
Youcanthinkofitlikethis:
Withthenonobjectorientedway,wewouldtellafunctiontosubmittheform.
Withtheobjectorientedway,wewouldtelltheformtosubmititself.
Ifwanted,youcanrunseveralmethodsinturnonthesameobjectbyusing:
referenceToTheObject.method1().method2().method3().method1again()

Inthiscase,method1mustreturnaclassofobjectthathasthemethod'method2'etc.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

15/223

5/30/2015

JavaScripttutorial

Operators

Themostcommonoperatorsaremathematicaloperators+,,/,*(add,subtract,divide,multiply)for
example. Operators can be split into two groups, comparison operators and assignment or 'action'
operators. Comparison operators test to see if two variables relate to each other in the specified
way,forexample,onevariableisahighernumberthantheother.Otheroperatorsperformanaction
onavariable,suchasincreasingitbyone.
Thefollowingtablegivesthosethataremostcommonlyused.TheJavaScript1.3operatorssuchas
the identity operator === are supported by all current browsers, but are not used as often as the
others.Oldbrowsersthatdonotunderstandthemwilljustproduceerrors.
JavaScriptoperators
Operator Uses
addstwonumbersorappendstwostringsifmorethanonetypeofvariableis
+

appended,includingastringappendedtoanumberorviceversa,theresultwillbea
string

subtractsthesecondnumberfromthefirst

dividesthefirstnumberbythesecond

multipliestwonumbers

dividethefirstnumberbythesecondandreturntheremainder

assignsthevalueontherighttotheobjectontheleft

+=
=

>

<

>=

<=

theobjectontheleft=theobjectontheleft+thevalueontherightthisalsoworks
whenappendingstrings
theobjectontheleft=theobjectontheleftthevalueontheright
numberontheleftmustbegreaterthanthenumberontherightthisalsoworkswith
stringsandvalues
numberontheleftmustbelessthanthenumberontherightthisalsoworkswithstrings
andvalues
numberontheleftmustbegreaterthanorequaltothenumberontherightthisalso
workswithstringsandvalues
numberontheleftmustbelessthanorequaltothenumberontherightthisalsoworks
withstringsandvalues

++

incrementthenumber

decrementthenumber

==

thenumbersorobjectsorvaluesmustbeequal

!=

thenumbersorobjectsorvaluesmustnotbeequal

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

16/223

5/30/2015

JavaScripttutorial

<<

bitwiseleftshift

>>

bitwiserightshift

&

bitwiseAND

bitwiseOR

bitwiseXOR

bitwiseNOT

logicalNOT(thestatementmustnotbetrue)

&&

logicalAND(bothstatementsmustbetrue)

||

logicalOR(eitherstatementmustbetrue)

in

objectorarrayontherightmusthavethepropertyorcellontheleft

===

thenumbersorobjectsorvaluesmustbeequal,andmustbethesamevariabletype

!==

thenumbersorobjectsorvaluesmustnotbeequal,ormustnotbethesamevariable
type

Note,ifyoudonotsetthe language="javascript1.2"attributeinthe<script>tag, 0 == false == ''


andundefined==null.Ifyoudosetthelanguageattributeto 'javascript1.2',Mozilla/Firefoxand
otherGeckobrowsers(butnoneoftheothermajorbrowsers)willchangethissothatnoneofthese
will equate to each other. Since the attribute is deprecated anyway, and the JavaScript versions
wereneverstandardised,youshouldnotrelyonthisbehaviour.Ifyouneedthatbehaviour,usethe
===and!==operators.

Therearealsoafewoperatorsthatcanalsobeusedlikefunctions:
void
voidstatementorvoid(statement)(seethesectiononwritingfunctions)

typeof
typeofvariableortypeof(variable)returnsthetype(orclass)ofavariable.

eval
eval(string)interpretsastringasJavaScriptcode.

There are also the 'var','new'and'delete' operators. See the section on variables for examples of
theiruses.AlsoseethesectionontheMathobjectoperatorsbelow.
Note that JavaScript has no logical XOR operator. If you need that functionality, see my separate
XORarticle.

Operatorprecedence

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

17/223

5/30/2015

JavaScripttutorial

If you ask JavaScript to perform a calculation using multiple operators, those operators will be
evaluatedinaspecificorder.Forexample 3+6*7iscalculatedas (6*7)+3becausethe*is
calculatedbeforethe+.Theorderinwhichtheseareevaluatedis:*/%++(wherethesecond+
isappendingstrings).Tochangetheorderinwhichtheyarecalculated,useparenthesis()asthe
contents of parenthesis are calculated before the contents outside the parenthesis. For example,
3+6*7=45but(3+6)*7=63

TheMathobjectmethods
Inreality,thesearemethodsoftheMathobjectbuttheyareusedinplaceofoperators.
Mathobjectmethods
Operator

Whatitdoes

Math.abs(n)

Returnstheabsolutevalueofn

Math.acos(n)

Returns(inradians)cos1ofn

Math.asin(n)

Returns(inradians)sin 1ofn

Math.atan(n)

Returns(inradians)tan 1ofn

Math.atan2(n,k)

Returnstheangle(rads)fromcartesiancoordinates0,0ton,k

Math.ceil(n)

Returnsnroundeduptothenearestwholenumber

Math.cos(n)

Returnscosn(wherenisinradians)

Math.exp(n)

Returnse n

Math.floor(n)

Returnsnroundeddowntothenearestwholenumber

Math.log(n)

Returnsln(n)
Note,tofindlog 10(n),useMath.log(n)/Math.log(10)

Math.max(a,b,c,...) Returnsthelargestnumber
Math.min(a,b,c,...) Returnsthesmallestnumber
Math.pow(n,k)

Returnsn k

Math.random()

Returnsarandomnumberbetween0and1

Math.round(n)

Returnsnroundedupordowntothenearestwholenumber

Math.sin(n)

Returnssinn(wherenisinradians)

Math.sqrt(n)

Returnsthesquarerootofn

Math.tan(n)

Returnstann(wherenisinradians)

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

18/223

5/30/2015

JavaScripttutorial

Variables

VariabletypesarenotimportantinJavaScript.Theymaybeinterchangedasnecessary.Thismeans
thatifavariableisastringoneminute,itcanbeanintegerthenext.Thebasicvariabletypesare:
character
'a'or'@'or'k'etc.
string
'hdttgs846hs()Gettheidea'
integer
0or1or2or3or4etc.or1or2or3or4etc.
float(ordouble)
23.546or10.46
boolean
trueorfalse
function
AfunctionseethesectiononFunctions
object
AnobjectseethesectiononObjectorientedprogramming
array
Atypeofobjectthatcanstorevariablesincells(seebelow)
regularexpression
Apatternthatcanbeusedtomatchstringsorsubstrings
undefined
Avariablethathasnotbeengivenavalueyet
null
Avariablethathasbeendefinedbuthasbeenassignedthevalueofnull
Integer and float are grouped together as 'number'. Character and string are grouped together as
'string'.
Use the typeof operator to find out which variable type your variable is. Note, typeof will return
'object' for arrays, regular expressions and null in most current browsers. In future, browsers are
insteadexpectedtoreturn'null'fornull.

Definingvariables
See the section on 'Referencing' subsection 'Avoiding referencing conflicts' to see how to choose
namesforyourvariables.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

19/223

5/30/2015

JavaScripttutorial

Normalvariables
Itisgoodpracticetopredefineallvariablesusingthe var keyword (this is known as declaring the
variables). It is possible to define the variable, leaving its value undefined, or assigning a value
immediately,oreventodefinemultiplevariablesinasinglecommand:
varvariablename;
varvariablename=value;
varvari1=value,vari2=anotherValue,vari3;

JavaScriptisfairlylenient,andwillcreateaglobalvariableifyouforgettousethe'var'keyword,but
you assign a value to an undeclared variable (if you attempt to read the value of an undeclared
variable,itwillthrowanerror,asdiscussedbelow).However,thiscanleadtoproblemsifyouend
up accidentally overwriting variables from another scope (this will be covered in the chapter on
Functions). Once a variable is defined do not use 'var variablename' again unless you wish to
completely overwrite the variable. It makes no sense to redeclare a variable with the var keyword
withinthesamescope,butbrowserswillnotcomplainifyoudoit.
Thesearesomeexamplesofhowtodefinevariables,inthiscase,astring,anumber,andaregular
expression:
varmyFish='Afishswamintheriver';
varmyNumberOfGoats=23;
varmyPattern=/<[^>]*@[^<]*>/gi;

Notethatvariablescanbedefinedatanypointinyourscript,includinginsideacontrolstructurethat
causesthatstatementnevertobeexecuted.However,nomatterwhereyouchoosetodefineyour
variable, the JavaScript engine will create the variable at the start of the current scope. It will hold
thevalueundefineduntilastatementisexecutedthatgivesitavalue.

Objects
WebTV2.6doesnotsupportthe{}syntaxforcreatingobjects.

Ifyouwanttocreatevariablesthatyouwanttobeabletogivechildpropertiesto,youmustdefine
thevariableasanobject.Todefineavariableasanobject,useeitherthenewObject()or{}syntax:
varvariableName=newObject();
varvariableName={myFirstProperty:1,myNextProperty:'hi',etc};

Youcanthenassignchildobjectsorpropertiestothatobjectasyouwant:

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

20/223

5/30/2015

JavaScripttutorial

variableName.aPropertyNameIMadeUp='hello';
variableName.aChildObjectNameIMadeUp=newObject();

Note that if you want to run a method on an object that you just created, for true JavaScript 1.2
compliance, you must surround the object declaration with brackets (early Netscape 4 will have
problems otherwise). This example will not work in early Netscape 4, and other browsers made at
thesametime:
newDate().getTime()

ThisexamplewillworkinallJavaScriptsupportingbrowsers:
(newDate()).getTime()

ThisappliestoallobjecttypeslikeArray,Image,Option,Object,Dateandonesyoucreateyourself.

Arrays
WebTV2.6doesnotsupportthe[]syntaxforcreatingarrays.

ArraysaresimilartotheObjectwehavejustdefined,butwithsomesmalldifferences.Iliketothink
of arrays as boxes. Inside the box, there are several compartments or cells. We can vary the
numberofcompartments.Torefertothecontentsofacompartment,wewritethenameofthebox,
thenwewritesquarebrackets,insidewhichweputthenameornumberofthecompartment.
Tocreateanarray,useeitherthenewArray()or[]syntax:
varnameOfArray=newArray();
varnameOfArray=newArray('content_of_first_cell','and_the_second',8,'blah','etc');
varnameOfArray=['content_of_first_cell','and_the_second',8,'blah','etc'];

Youcanalsouseasinglenumberasaparameterwhencreatingthearrayobject.Ifthenumberisa
positive integer, an array will be created with that many cells, all of which will be empty:
newArray(5).Notethatifyousetthelanguageversiontojavascript1.2,somebrowsers(butnotall)

willcreateanarraywithasinglecellcontainingthenumber5.Forthisreason,itisbestnottousea
singlenumericparameterwhencreatingthearrayusingthenewArray(number)syntax.
To refer to the contents of its cells, use the syntax nameOfArray[name_or_number_of_entry] (if using
namesinsteadofnumbers,thenameshouldbeinquotes).Numericarraysstartat0,not1,sothe
firstcellisnumber0.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

21/223

5/30/2015

JavaScripttutorial

InJavaScript,arraysandobjectsarealmostequivalent,andaccessinganamedcellofanarrayis
the same as accessing a property of an object. However, it is important to note that most of the
special array functionality is based on you using numeric arrays most array methods act only on
numerickeys,andwillignorenamedproperties.Ifyouareusingarrayswithonlynamedproperties,
then you are almost certainly using them for the wrong reason, and should probably be using
objects instead. However, for the purpose of demonstration, if a cell of an array is called 'mycell',
youcoulduseeitherofthesetoaccessitscontents:
nameOfArray['mycell']
nameOfArray.mycell

Therearesomeimportantdifferencesbetweenarraysandobjects.Bydefault,arrayshavefarmore
methods attached to them, for stepping through a numeric array, or splitting it into pieces. In
addition,ifnumbersareusedforentries,youcanfindouthowmanyentries(orvariables)thearray
isholding,usingnameOfArray.length
It is possible to create multidimensional arrays, by creating aditional arrays as the contents of the
cellofanotherarray:
varnameOfArray=newArray(newArray(1,2,3,4),'hello',['a','b','c']);

You can refer to the cells of that array using the square bracket notation twice (or multiple times,
dependingonhowmanydimensionsyourarrayhas):
nameOfArray[name_or_number_of_entry][name_or_number_of_inner_entry]

Othertypesofobjects
Browsers will have many built in types of objects. All JavaScript capable browsers will provide the
followingaditionalobjecttypes:
Date
Createsadateobject,whichcanperformcalculationsbasedonthedate,forexample:
varmydate=newDate();
window.alert('Theyearis'+mydate.getFullYear());

Image
Creates an image that is not visible but is stored in cache. Setting the src attribute of the
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

22/223

5/30/2015

JavaScripttutorial

imagecausestheimagetobeloadedandstoredinthebrowser'scache:
varmyimage=newImage();
myimage.src='thing.gif';

Now each time I want to change an image on the page, I can say
document['imagename'].src = myimage.src; and the image will change, without having to

waitforthenewimagetoload.
Option
Createsanoptionthatcanbeaddedintoaselectinput,forexample:
varmyoption=newOption('text','value');
selectInput.options[selectInput.options.length]=myoption;

Seethesectionon'Creatingobjects'forhowtocreateyourownobjectsthatarenotoneofthepre
defined object types. DOM compliant browsers will provide far more object types these will be
coveredinlaterchaptersofthistutorial.

Deletingproperties
OnseveraloccasionshereIhavecreatedpropertiesforobjects.Evenifthesearesettoundefined
or null, they still exist, holding that new value, and will be found using the forin control structure.
Youcandeletethemcompletelybyusingthe'delete'keyword:
deletemyObject.itsProperty;

Ofcourse,unlessyouhaveseriouscomputermemoryconsiderations,orsecurityrisks,itisusually
notnecessarytodothisatall,sinceJavaScriptenginescleanupafterthemselvesoncethevariable
isnolongerreferenced.

Avoidingerrorswithvariables
Ifatanytimeyourefertoavariablethatdoesnotexist,youwillcauseanerror.However,JavaScript
allowsyoutorefertoonelevelofundefinedchildpropertiesofanobject(specifically,itallowsyouto
refertononexistantpropertiesofanyvariablethatisnotnullorundefined,butitwillnotallowyou
torefertotheirproperties,sinceanundefinedpropertycannothavepropertiesofitsown).Thisisa
very important rule to learn, as it forms the basis of object and capability detection, and is
fundamental to making cross browser scripts. The following series of examples will demonstrate
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

23/223

5/30/2015

JavaScripttutorial

whatwillthrowerrors:
varmyObject=newObject(),nonObject='',nonObject2;

Thissetseverythingupforthefollowingexamples.Sofar,everythingisfine,butinthecodebelow,b
isundefined.Notonlythat,butithasneverbeendeclaredasexisting.Thiswillcauseanerrorwhen
thecodeattemptstoreaditsvalue:
vara=b+5;

In the code below, c has also not been defined or declared. It will not throw an error, however,
becausethecodeisassigningavaluetoit.Thiswillcausethescriptenginetoautomaticallydeclare
itintheglobalscope:
c=5;

Inthenextexample,theparentobjecthasbeendefined,butitspropertyhasnot.Sincethisisonly
onelevelofundefinedproperties,thisisallowed,andwillnotcauseanerror:
varb=myObject.myChild;

Inthenextexample,theparentobjecthasbeendefined,butitspropertyhasnot.Tryingtorefertoa
childofthenonexistentpropertymeanstherearenowtwolevelsofundefinedproperties.Thiswill
causeanerror:
b=myObject.myChild.itsChild;

The actual reason it causes an error is because the code attempts to access the property of an
objectthatdoesnotacceptproperties(implicitly'undefined'inthiscase),andwillcauseanerrorif
an attempt is made to access them. The same would happen if myObject.myChild was explicitly
definedasnullorundefined.
In the next example, the parent object has been defined, but it is a type of variable that cannot
acceptcustomchildproperties,suchasanumberorstring.Tryingtocreateachildpropertywillnot
throw an error, since it is only one level of undefined properties. However, it will not do anything,
sincethenewpropertywillberejected:
nonObject.itsChild=7;
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

24/223

5/30/2015

JavaScripttutorial

window.alert(nonObject.itsChild);
//Thiswillalert'undefined'

Null and undefined are special, however, as they cannot have any properties at all, custom or
native. Any attempt to access a property of a variable that holds the value null or undefined, will
resultinanerror:
nullVariable=null;
nullVariable.itsChild=7;
//Thiswillthrowanerror

Inthenextexample,theparentobjecthasbeendeclared,butitwasnotgivenavalue.Asaresult,it
holds the value undefined. Trying to refer to a child property means there are now two levels of
undefinedproperties,andwillthrowanerror:
nonObject2.itsChild=7;

Referencingavariableorjustitsvalue
If you assign one variable to another, there are cases where this merely copies the value in one
variable and 'pastes' it into the other, but there are also cases where instead of copying the
variable,itjustprovidesyouwithanewwaytoreferencethatvariable.Thefollowingisanexample
ofwherethismightoccur:
varmyNewVariable=myOldVariable;

IfmyOldVariablewasalreadydefinedasastring,number,boolean,nullorundefined,itwouldsimply
havecopiedmyOldVariableand'pasted'itintomyNewVariable.Ifthenewvariablewerechanged(for
example,usingmyNewVariable='somenewvalue';),myOldVariableretainsitsoldvalue.
If, on the other hand, myOldVariable was already defined as a function, array, object, regular
expression or option (or any other type of object except null), myNewVariable would have been
created as a pointer to myOldVariable. The children of myOldVariable would now also be the
children of myNewVariable. If the new variable were changed (for example, using
myNewVariable = 'some new value';), it would only alter the value of myNewVariable so that it no

longer references the same contents as myOldVariable. However, changing the child properties of
myNewVariablewillchangethepropertiesoftheobjectitreferences,andasaresult, myOldVariable

wouldalsoseethechange:

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

25/223

5/30/2015

JavaScripttutorial

varmyOldVariable=newObject();
varmyNewVariable=myOldVariable;
myNewVariable.newChild='Hello';
alert(myOldVariable.newChild);
//Thiswillalert'Hello'

Moreaboutnumbers
JavaScript understands numbers in several formats, allowing you to specify numbers in hex,
decimal,andoctal.Ifa0precedesanumberandthereisnonumberhigherthan7,thenumberis
consideredtobeinoctal(base8)andifthenumberisprecededby0x,thenitisconsideredtobein
hex(base16)andcanalsocontaincharactersA,B,C,D,E,F.Neithermaycontaindecimalpoints.
With decimal numbers, 12e+4 may be used to replace 12x10 4 and 12e4 may be used to replace
12x10 4etc.
There are a few numbers that are held by the Math object and can be used as variables with the
exception that you cannot assign values to them. These are known as constants. There are some
constantsavailablethatgivethedocumentareaofthewindowthatisavailableforwritingto.These
requirespecificreferencingtoobtainandsohavebeenincludedinthesectiononreferencingitems,
objectsandelements,subsection'Windowsize'.
TheavailableMathobjectconstantsare:
Mathobjectconstants
Mathobjectproperty Value(approx) Mathematicalequivalent
Math.E

2.718

Math.LN2

0.693

ln(2)

Math.LN10

2.303

ln(10)

Math.LOG2E

1.442

log 2(e)

Math.LOG10E

0.434

log 10(e)

Math.PI

3.142

Pi

Math.SQRT1_2

0.707

(sqrt(2)) 1orsqrt(1/2)

Math.SQRT2

1.414

sqrt(2)

Specialstringcharacters
Thereareafewstringcharactersthatcanbeescapedwithabackslashandcanbeusedtoreplace
untypeablecharacters.Theseare:
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

26/223

5/30/2015

JavaScripttutorial

\n
Anewlinecharacter.Usethisifyouwanttoinsertalinebreakintotext.
\f
Aformfeed.Trynottousethisever.Use\ninstead.
\r
Acarriagereturn.Trynottousethisever.Use\ninstead.
\t
Atabcharacter.
\\
A\character
\/
A/character(mostwebdevelopers[myselfincludedonoccasion]forgetthisonegenerally,
browsers will have no trouble with you forgetting the backslash but it is important for
representing closing tags and in theory you should always use the backslash escape when
writingaforwardslashseethesectiononWritingwithscriptfordetailsofwhereitisneeded)
If you need to recognise a Windows linebreak, you need to look for \r\n. If you are trying to add a
linebreak (for example, when modifying the value of a textarea input), you should insert a \n
character. This will work cross browser. Note that browsers on Windows may convert this \n
characterintoa\r\nautomatically,dependingonwhereyouuseit.
OldMacOperatingSystems(OS9andbelow)used\rforlinebreaks,butasfarasmytestsshowed,
they are converted to \n by JavaScript. However, just be aware that you may encounter some of
these, especially in text inputs (Mac OS 9 is still in use among some Mac users). Unix based
OperatingSystems(includingMacOSX)use\nforlinebreaks.
Ifyouarewritingastringthatcontainsdoublequotes,theeasiestwaytodealwithitistosurroundit
withsinglequotes.Youshouldalsousedoublequotesifyourstringcontainssinglequotes:
varmystring='Andhesaid"help"twice';
varmystring="HelpAndy'scat";

You may notice a problem. What if you have both single and double quotes in your string? The
solution is to use the escape character '\' to excape the quotes (in fact, you can always escape
quotes,evenifthestringisdelimitedbytheothertypeofquotes).Forexample,bothofthefollowing
arevalid:
varmystring='Andhesaid"helpAndy\'scat"twice';
varmystring="Andhesaid\"helpAndy'scat\"twice";

Ifyourstringbecomestoolongtofitononeline(thisreallydoesn'tmatteryoucanmakethetext
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

27/223

5/30/2015

JavaScripttutorial

aslongasyouwant),andyouwanttosplititontoseverallines,simplyendthestring,followitwith
theconcatenationoperator+andstartanewstringonthenextline:
varmystring='firstlineofthestring'+
'stillonthefirstlineofthestringit\'slikeweneverbroketheline';

Note,intheory,youcanuse\tobreakthestring:
varmystring='like\
this';

Butthishassignificantproblemsthe\willnotalwayscopewithtrailingwhitespace,mayormaynot
correctly treat the leading whitespace before the new line, and does not work correctly in all
JavaScriptimplementations:
Netscape4(inventorsofJavaScript),Escape,Opera7.6andICEbrowserincludethelinebreaks
inthestring.
Internet Explorer, Mozilla/FireFox, Opera 8+, Safari/Chrome/Konqueror, iCab and OmniWeb
ignorethelinebreakcharacters.
ICEbrowsersometimesignoresthewholestring.
Imentionthisonlyforcompleteness.Donotuseit.Itiseasierandbettertousetheconcatenation
operatorasshownabove.

Regularexpressions
Opera 46 has a major bug in its regular expression handling and will fail on even the simplest regular
expressions.
Pocket Internet Explorer, Internet Explorer for Windows CE and iCab 2 do not support regular expressions
properly.

Certain methods, like the stringObject.replace() and stringObject.match() methods, can


recognise patterns in text. To do this, they use regular expressions. These are well documented
elsewhere so I will not describe the syntax here. Basically, what you can do is use special
characters to recognise text patterns (like \w for characters az, AZ, 09 and _). To define a
collection of characters as a regular expression, you use the / character (sometimes with a g or i
afterit).Forexample,theregularexpression/\/\*[\w\W]*\*\//matchesblockcomments.
Some rare browsers do not support regular expressions. In theory, you should be able to detect
regularexpressionsupportusingthis:
if(window.RegExp){varmyRegularExpression=newRegExp("pattern");}
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

28/223

5/30/2015

JavaScripttutorial

ThisshouldnotproduceerrorsinPocketInternetExplorerandInternetExplorerforWindowsCE(as
they do not understand the /pattern/options syntax or support the RegExp object). However, as
Opera6andiCab2supporttheRegExpobject,butfailtouseitcorrectly,yourscriptswillstillfail,
thoughhopefullywithouterrors.Thankfully,currentreleasesofOperaandiCabdosupportregular
expressionscorrectly.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

29/223

5/30/2015

JavaScripttutorial

Controlstructures

The'if'statement
if(myVariable==2){
myVariable=1;
}else{
myVariable=0;
}

IfmyVariablehadbeen2itwouldnowbe1.Ifithadbeenanythingotherthan2itwouldnowbe0.
'If' statements can also test for the occurence of a child object of an object that may not exist. For
example, some browsers provide document.body.style while some older browsers do not even
providedocument.body.Inthesebrowsers,writing'if(document.body.style)'wouldjustproducean
error (see the section on 'Variables' subsection 'Avoiding errors with variables'). In order to solve
thisproblem,wecouldwritethis:
if(document.body){
if(document.body.style){etc.}
}

However, the && operator has a useful feature that we can use here to combine the two 'if'
statementsintoone:
if(document.body&&document.body.style){etc.}

The first test would be false, so the browser would not proceed to the second. This is known as a
shortcircuit.The||operatorhasasimilarfeature,butitwillonlyevaluatethesecondtestifthefirst
onefails.
JavaScriptunderstandsthatifthe'{'and'}'(curlybrace)charactersareleftout,thenonlythenext
commandbelongstothatstatement:
if(x<5)
x++;
window.alert(x);

Here,thealertwillalwayshappenreguardlessofx,butxwillonlybeincrementedifxislessthan5.
This may seem convenient, as it allows you to make your code a tiny bit shorter, but I recommend
avoidingthissyntax.Itmakesyourcodehardertoread,especiallyifyoustartnestingyourcontrol
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

30/223

5/30/2015

JavaScripttutorial

structures. It also makes it easy to forget to put them in when you needed them, and also makes
debuggingcodemuchharder,sinceyouwillneedtogobackthroughyourcodetoaddthemsothat
you can add extra debugging tests. It is best to always use the curly braces, even if they are
optional.
Asalways,thereisanexception.Nested'if'statementslikethiscanstarttogetdifficulttomanage:
if(myVariable==2){
myVariable=1;
}else{
if(myVariable==5){
myVariable=3;
}else{
myVariable=4;
}
}

Bystrategicallyremovingcurlybraces,thatcanusefullybereducedtothisconstruct(whichyoumay
recognisefromotherprogramminglanguages)notethat'elseif'isnotwrittenas'elseif':
if(myVariable==2){
myVariable=1;
}elseif(myVariable==5){
myVariable=3;
}else{
myVariable=4;
}

The'for'loop
Thisisoneofthemostcommonconstructsinuse.Typically,itisusedtocyclethroughthecontents
ofanarray,ortocreateaspecificnumberofnewobjects,butitcandomanymoreusefulthingsif
needed.Thesyntaxofthe'for'loopisasfollows:
for(starting_initialise;continue_as_long_as_condition;do_this_each_time)

starting_initialise
This is where you define new variables that you will use in the loop, typically for use with
incremental counting. As with all variables, you must declare them (if you have not done so
already).Youcandefinemultiplevariablesifneeded,using:
varmyVariable1=value,myVariable2=another_value;

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

31/223

5/30/2015

JavaScripttutorial

These variables are not restricted to being inside the 'for' loop, and will be available to all
codeaftertheloop(inthesamescopeastheloop).
continue_as_long_as_condition
Thisiswhereyoudefinetheconditonsunderwhichtheloopshouldcontinuetoexecute.The
syntaxisexactlythesameasforthe'if'statement,soyoucanapplymorethanonecontinue
conditionbyusingthe&&or||operators:
myVariable1<=5&&myVariable2>=70;

Iftheconditionisnotsatisfiedwhentheforloopbegins,thenitwillneverloopthroughit.
do_this_each_time
Once the end of the loop is reached, it will do whatever you tell it to here. Typically, this is
usedtoincrementor decrement a stepping variable, and it is possible to perform actions on
morethanonevariablebyseparatingthemwithacomma:
myVariable1++,myVariable2=4

Thefollowingisafullexample.
for(varmyVariable=1;myVariable<=5;myVariable++){
myArray[myVariable]=1;
}

myArray[1]tomyArray[5]arenow1.

The'forin'loop
The'forin'loopisusedtocyclethroughallexposedpropertiesofanobject(orarray).Everytime
youcreatepropertiesormethodsonanobject,thesewillbeaddedtothelistofpropertiesthatwill
be exposed. Most internal properties (the ones that JavaScript creates) will also be exposed, but
JavaScriptenginesareallowedtohideinternalpropertiesandmethodsiftheywantto.Youshould
notrelyonanyspecificbehaviourhere,butnotethatsomebrowserswillgivetheinternalproperties
andmethodsofintrinsicobjects,andsomewillnot.
Again, you should declare the variable names that you use, if you have not done so already. The
syntaxofthe'forin'loopisasfollows:
for(varmyVariableinanObjectOrArray){

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

32/223

5/30/2015

JavaScripttutorial

This will run through the loop, once for each exposed property in anObjectOrArray. Each time it
loops, it assigns the next property name as a string value to myVariable. You can then use array
notation to access the value of that property. The following example writes all the exposed
propertiesofthedocumentobject:
for(varmyVariableindocument){
document.write(myVariable+'='+document[myVariable]+'<br>');
}

Note that if you use this loop on an array, it will list the numbered and named keys, including the
internal'length'property.Itisveryeasytomakemistakeshere,sobecarefulnottomistakethese
propertytypesforeachother.

The'while'loop
The'while'loopisidenticalinbehaviourtothe'for'loop,onlywithouttheinitialsetup,andloopend
actions.Itwillcontinuetorunaslongastheconditionissatisfied:
varmyVariable=1;
while(myVariable<=5){
myArray[myVariable]=1;
myVariable++;
}

myArray[1]tomyArray[5]arenow1.

Usingafeatureoftheincrement(anddecrement)operatorhere,itispossibletoshortenthecode
inside the loop to be just 'myArray[myVariable++] = 1;', and it would have exactly the same effect.
Firstly, it would use the value of myVariable to index the array cell, then it would increment
myVariable.
This also works in reverse 'myArray[++myVariable] = 1;'. Firstly, it would increment the value of
myVariable,thenitwouldusethenewvaluetoindexthearraycell.IfIhaddonethis, myArray[2]to
myArray[6]wouldnowbe1.

These features also work outside loops, but this is where you will most commonly see them, so I
haveincludedthemhere.

The'dowhile'loop

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

33/223

5/30/2015

JavaScripttutorial

This is similar to the while loop, but with an important difference. The condition is evaluated at the
endoftheloop,meaningthateveniftheconditionisneversatisfied,itwillstillrunthroughtheloop
atleastonce.
varmyVariable=1;
do{
myArray[myVariable]=1;
myVariable++;
}while(myVariable<=5);

myArray[1]tomyArray[5]arenow1.

The'switch'statement
The'switch'statementislikerepeated'if'statements,testingasinglevaluetoseeifitmatchesone
ofasetofvalues:
switch(myVar){
case1:
//ifmyVaris1thisisexecuted
case'sample':
//ifmyVaris'sample'(or1,seethenextparagraph)
//thisisexecuted
casefalse:
//ifmyVarisfalse(or1or'sample',seethenextparagraph)
//thisisexecuted
default:
//ifmyVardoesnotsatisfyanycase,(orifitis
//1or'sample'orfalse,seethenextparagraph)
//thisisexecuted
}

Ifacaseissatisfied,thecodebeyondthatcasewillalsobeexecutedunlessthebreakstatementis
used.Intheaboveexample,ifmyVaris1,thecodeforcase'sample',casefalseanddefaultwillall
be executed as well. The solution is to use break as follows (The use of the break statement is
describedbelow).
switch(myVar){
case1:
//ifmyVaris1thisisexecuted
break;
case'sample':
//ifmyVaris'sample'thisisexecuted
break;
casefalse:
//ifmyVarisfalsethisisexecuted
break;
default:
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

34/223

5/30/2015

JavaScripttutorial

//ifmyVardoesnotsatisfyanycase,thisisexecuted

//break;isunnecessaryhereastherearenocasesfollowingthis
}

The'with'statement
Takeforexamplethefollowingexample:
x=Math.round(Math.LN2+Math.E+Math.pow(y,4));

Usingthe'with'statement,thiscanbereplacedwith:
with(Math){
x=round(LN2+E+pow(y,4));
}

Note that the 'with' statement brings extra variable names into the current scope. In the example
above, if I already had a variable called pow before the 'with' statement, this variable would be
unavailable inside the with statement, as it would have been replaced by the method of the Math
object (as would any other variables that matched property or method names). Once the 'with'
statementiscomplete,theoldvariableswouldbecomeavailableagain.

Thequick'if'statement
Thisisknownastheconditionalorternaryoperator,andisaneasywaytoassigndifferentvaluesto
avariable,dependingonacondition.
varmyVariable=document.getElementById?1:0;

Thisisidenticalto:
if(document.getElementById){
varmyVariable=1;
}else{
varmyVariable=0;
}

Thetrycatchfinallystatement
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

35/223

5/30/2015

JavaScripttutorial

Netscape4,InternetExplorer4andWebTVdonotsupportthisstructureandwillproduceerrorsifyouuseit.

The 'try catch finally' control stucture allows you to detect errors and quietly deal with them
without producing error messages or aborting the script, and in fact, without even interrupting the
flowofthescriptthatisrunning.Thismakesitsuperiortotheoriginalwayofhandlingscripterrors
(withouterrormessages)wherescriptsarecompletelyaborted:
window.onerror=referenceToFunction;

Thesyntaxofthe'trycatchfinally'controlstuctureisasfollows:
try{
//dosomethingthatmightcauseanerror
}catch(myError){
//ifanerroroccurs,thiscodewillberun
//twopropertieswill(bydefault)beavailableonthe
//objectpassedtothestatement
alert(myError.name+':'+myError.message);
}finally{
//optionalthiscodewillalwaysberunbeforethe
//controlstructureends,evenifyourethrowtheerror
//inthecatch
}

If an error occurs in the 'try' section, it immediately jumps to the 'catch' part, passing some
information about the error. Different browsers provide different information for the same error so
don'ttrustit(intheory,DOMbrowserswilluseaspecificsetoferrortypes,butthisdependsontheir
levelofDOMsupportInternetExploreristheleastcomplianthere).Oncethe'try'or'catch'parts
havebeenrun,the'finally'partisrunifyouhaveprovidedone,thenthescriptfollowingthecontrol
structureisrun,unlessyouthrowanothererror.
If you nest these statements (one 'try catch' inside another), you can rethrow the error from the
'catch'partoftheinnerstatementtothe'catch'partoftheouterstatement(the'finally'partifthere
isonewouldstillberunbeforetheouter'catch'isrun,butthescriptfollowingtheinnerstructure
willnotberun).Thisisdoneusingthe'throw'method:
try{
//...someothercodegoesinhere
try{
vara=nonexist.b;//thiswillproduceanerror
}catch(myError){
//thiscatchestheerrorandalertsthemessage
alert(myError.message);
//rethrowtheerroruptotheoutertrycatch
throw(myError);
}
//...someothercodegoesinhere
}catch(myErrorObject){
//Irethrewthefirsterror,sothisisthesameerrorobject
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

36/223

5/30/2015

JavaScripttutorial

//themessageshouldbethesame
alert(myErrorObject.message);
}

Youcanalsothrowyourownerrorsatanypointbycreatinganobjectwiththerequiredproperties,
andpassingitastheparameterwhenusingthrow:
try{
varmyEr=newObject();
myEr.name='Myerror';
myEr.message='YoudidsomethingIdidn\'tlike';
throw(myEr);
}catch(detectedError){
alert(detectedError.name+'\n'+detectedError.message);
}

Whatiswrongwithit?
It'slackofsupportinolderbrowserswasitsonlymajorfailing.Thankfullythesebrowsersarehardly
used any more. It may have been useful to use this structure detect errors in Netscape 4 (like the
'this'keyword+inlinemethodbugforexampletherearelotsmoreerrors),butthatbrowserdoes
notsupportthestatement.Itwouldalsobeusefulforcheckingforstupidbugs,likewherechecking
for something like navigator.taintEnabled causes errors in older versions of Internet Explorer.
However,theerrorisnotcorrectlythrownfortheseerrors.
Unfortunately, if you use this structure in any script run by a browser that does not support it, the
browser will abort the entire script with errors, even if it does not use the part containing the
structure.Thankfully,theseoldbrowserscanbesafelyignored.
It should never be used to detect if a browser supports a method or property like
document.getElementByIdasaproperobjectdetectwouldsuffice.

Sowhenshoulditbeused?
It can be used for W3C DOM scripting, where you may want to avoid DOM mutation errors (for
example), which are valid errors, but serve to warn you not to do something, and do not always
needtoabortthewholescript.OlderbrowsersdonotsupporttheDOManyway,soitdoesn'tmatter
if they don't understand this part of it. However, they will still run the script (it is not possible to
protectthembyusingthelanguageattributeonthescripttag,asyouneedtouseJavaScript1.2
notanythinghighertoenableInternetExplorer5support).Thismeansthattheolderbrowserswill
stillproduceerrors,unlessyoudefinetheolderrorhandlingmethodinanearlierscript.
It can be used for throwing your own errors if you create the 'error' deliberately under certain
circumstances.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

37/223

5/30/2015

JavaScripttutorial

It can be used to check if accessing a frameset frame will cause a browser security error (for
example,ifthepageintheframebelongstoanothersite).
Itcouldalsoenableyoutoavoidproblemswheredifferentbrowserssupportthesamemethodsbut
expect a different syntax, for example, the selectBox.add method (I did not include this method in
myDOMsectionofthetutorialduetothisproblem):
try{
selectBox.add(optionObject,otherOptionObject);
}catch(e){
selectBox.add(optionObject,index);
}

Conditionalswithoutacondition?
You may notice in the example for "The quick 'if' statement" that I tested for a property without
testingforanyspecificvalue:'if(document.getElementById)'
Thatisvalid,andisoneofthemostusefulpartsofJavaScript.Thisisaveryimportantruletolearn,
asitformsthebasisofobjectandcapabilitydetection,andisfundamentaltomakingcrossbrowser
scripts.Thiswillbetrueif:
document.getElementById!=""&&
document.getElementById!=0&&
document.getElementById!=false&&
document.getElementById!=undefined&&
document.getElementById!=null

Theoppositeisalsopossible:'if(!document.getElementById)'
Thiswillbetrueif:
document.getElementById==""||
document.getElementById==0||
document.getElementById==false||
document.getElementById==undefined||
document.getElementById==null

Using this, you can detect one type of capability, and if it fails, detect another type, and continue
untilyoufindonethatworks.
You can also do this anywhere where a condition is expected, such as with the 'while' loop
condition,the'dowhile'loopconditionandthe'continue_as_long_as_condition'intheforloop.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

38/223

5/30/2015

JavaScripttutorial

Checkingforpropertieswith'in'
WebTVcrashesifyouusethe'in'operatortocheckforapropertythatdoesnotexist.
Netscape 4, Internet Explorer 5.0 on Windows and Internet Explorer on Mac cannot use the 'in' operator as
shownhere.

The'in'operatorusedinthe'forin'loophasanotherpurpose.Itcanalsobeusedtocheckforthe
existence of named properties of an object. In most cases, it is best to use a conditional without a
condition,asshownabove.However,therearesomecaseswhereyouwanttotestfortheexistence
of a property even thought the property's value may be one that does not evaluate to true. An
examplewouldbewhereyouwanttocheckfortheexistenceofapropertywhosevaluemaybe0,
oranemptystring,ornull.
If you know what the type of the property will be, it is possible to achieve this using identity
operators,orthetypeofoperator,asshownhere:
if(typeof(document.body.innerHTML)=='string'){

However,itisalsopossibletousethe'in'operatortotestforaproperty.Thisallowsyoutotestfor
its existence, no matter what value it currently holds, and no matter what type of value it currently
has (even if it has been assigned a value of undefined). In the 'for in' loop, the 'in' operator
returned the name of properties as a string, and so here, it expects the name to be a string. This
limitstheusefulnessalittle,asitcanonlysearchforthename,andcannotbeusedtoseeifoneof
thepropertiesholdsaspecificvalueorvaluetype.
if('innerHTML'indocument.body){

Notethatthisisaround20timesslowerinInternetExplorerthantheconditionalwithoutacondition,
asshownabove.Inmostotherbrowsers,thetwoalternativesperformaboutthesame.Ingeneral,I
consideritbesttousethemorecommonalternatives,unlessyouhaveaspecificusethatneedsthe
behaviourofthe'in'operator.

Assignmentsinsideaconditional
JavaScript allows you to perform an assignment at the same time as testing if the assignment
worked.Thiscanbeusedinsideanyconditional,includinginsidean'if','for','while'and'dowhile'.
if(x=document.getElementById('mydiv')){...}

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

39/223

5/30/2015

JavaScripttutorial

do{
alert(node.tagName);
}while(node=node.parentNode);

NotethatInternetExploreronMacwillproduceanerrorifyoutrytodothiswithanarray,whenit
stepsofftheendofthearray.

Continueandbreakstatementsandlabels
Labels
Labels are used to name the 'while', 'do while', 'for', 'for in' and 'switch' control structures. The
syntaxusedis:
LabelName:
ControlStructure

LabelsareveryrarelyusedinJavaScript.

Thebreakstatement
Writingbreakinsideaswitch,for,forin,whileordowhilecontrolstructurewillcausetheprogram
tojumptotheendofthestatement.Ifyoujustuse,forexample:
for(varx=1;x<5;x++){
vary=1;
while(y<7){
y++;
if(y==5){break;}
document.write(y);
}
}

Thescriptwilljumppasttheendofthewhileloopwhenyis5.Butifyouusethis:
myForLoop:
for(varx=1;x<5;x++){
vary=1;
while(y<7){
y++;
if(y==5){breakmyForLoop;}
document.write(y);
}
}
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

40/223

5/30/2015

JavaScripttutorial

Thescriptwilljumppasttheendoftheforloopwhenyis5.

Thecontinuestatement
Writingcontinueinsidea'for','forin','while'or'dowhile'controlstructurewillcausetheprogram
to jump to the test condition of the structure and reevaluate it having performed any
'do_this_each_time'instructions.Ifyoujustusethis,forexample:
for(varx=1;x<5;x++){
vary=1;
while(y<7){
y++;
if(y==5){continue;}
document.write(y);
}
}

Thisscriptwilljumptothetestconditionofthewhileloopwhenyis5so5willneverbewrittenbut6
and7willbe.Ifyouusethisinstead:
myForLoop:
for(varx=1;x<5;x++){
vary=1;
while(y<7){
y++;
if(y==5){continuemyForLoop;}
document.write(y);
}
}

Here,thescriptwillincrementxaspartoftheforloopandthenreevaluatetheforcondition.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

41/223

5/30/2015

JavaScripttutorial

Writingwithscript

Be careful when writing with script. If script is not available, that content will not be created. You
shouldlimityouruseofthistopartsofthepagethatarenotneededtoaccesspagecontent.Ifyou
do write important parts of the page that are unavailable without scripting, you should use
<noscript>tagstoprovideanalternative.

Writingwhilethepageisstillloading
Ifyourcodeisbeingexecutedwhilethepageisstillloading(inotherwords,ifitisrunaspartofthe
initialpagelayout)putthefollowing:
<scripttype="text/javascript">
document.write('<p>Whateveryouwanttowrite<\/p>');
document.writeln('<p>Whateveryouwanttowrite<\/p>');
//writelnputsalinebreakaftertheline.
//ThisistreatedasalinebreakinthesourceofHTML
</script>

Itwillwritewhateveryouput,inwhateverpartofthepagethescriptiscurrentlyrunning.Ofcourse,
youcanincludeHTMLtagsintheretooorsomepreprogramming.
Notethatifyouwritecontentusinganeventhandler(suchastheonloadhandlerforanimage),it
willbetreatedasifthepagehascompletedloading,evenifithasnot.

Writingafterthepagehasloaded
Afterthepagehascompletedloading,theruleschange.Insteadofaddingcontenttothepage,itwill
replace the page. To do this, you should firstly open the document stream (most browsers will
automatically do this for you if you just start writing). Then you should write what you want, and
finally, you should close the document stream. Again, most browsers will automatically close the
stream for you. The notable exception here is the Mozilla/Firefox family of browsers, that will
continue to show a loading graphic until you close the stream. Some other browsers may fail to
renderpartorallofthecontent.Justtobesafe,makesureyoualwaysclosethestream.
<scripttype="text/javascript">
window.onload=function(){
document.open();
document.write('<p>Whateveryouwanttowrite<\/p>');
document.write('<p>Morestuffyouwanttowrite<\/p>');
document.close();
};
</script>
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

42/223

5/30/2015

JavaScripttutorial

Thatwillremoveeverythingthatiscurrentlybeingshownandreplaceitwithwhatyouwriteinthere.
Thisistheequivalentofmovingtheusertoacompletelynewpage.Youshouldput<html>tagsand
thingslikethatintheretooifyouwanttousethatmethod.
YoumaynoticethatIclosemyHTMLtagsinsidethescriptwithabackslashbeforetheforwardslash
intheclosingtag.Thisisarequirementofthespecification(andcancausetheHTMLvalidatornot
tovalidateyourpageifyouforgetit),althoughallbrowserswillunderstandifyouomitthebackslash.
However,sinceyoucanwriteHTMLwithscript,youcanwritestyleorevenscripttagswithit,making
one script import another. If you omit the backslash on any </script> tags that you are writing with
thescript,thebrowserwillreadthatastheclosingtagforthecurrentscript,andyourscriptwillfail.
Thesameappliestoopeningorclosingcomments(althoughIfailtoseewhyyouwouldwanttowrite
commentsusingascript).Thesecanbewrittenas'<'+'!'and''+'>'.Whenthescriptruns,the
plussigntellsittoappendthestrings,creatingavalidHTMLcomment.

Problemswitholdbrowsers
Althoughnotinuseanymore,youmaywanttobenicetoolderbrowserslikeNetscape4.Ifusing
document.writetodynamicallywriteadivelement,donotgivethedivaninlinestylewithleft:ortop:

positioning.ThiswillcauseNetscape4tofailcompletelyandbeunrecoverablewithoutcarefuluse
ofdialogsandtaskkills.
Also, Netscape 4 will completely fail to load if you attempt to use this method to create a
<divstyle="position:absolute"> and instead, you should use the unnofficial <layer> tag. You can

useif(document.layers)todetectifthelayertagshouldbeused.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

43/223

5/30/2015

JavaScripttutorial

Writingfunctions

Generalsyntax
PrealphaversionsofTkhtmlHv3donotcorrectlyinterprettheFunctionclassconstructor.

Functionsgrouptogetherscriptcodecontrolstructures,operations,methodcalls,etc.inthesame
wayasanormalscript.Thesefunctionscanthenbecalledwhenneeded,andthecodecontained
withinthemwillberun.Thismakesitveryeasytoreusecodewithouthavingtorepeatitwithinyour
script.
Functionsaredefinedusingoneoftheseconstructs:
Normalfunctionconstruct
functionnameOfFunction(listOfVariableNames){
functioncodeshouldbewrittenhere
}

Anonymousfunction,assignedtoavariable
UsingthissyntaxforobjectmethodsinearlyNetscape4versionswillcauseproblemswiththe
'this'keywordduetobugs.
nameOfFunction=function(listOfVariableNames){
functioncodeshouldbewrittenhere
};

Normalfunctionconstruct,assignedtoavariable
nameOfFunction=functionanotherNameForTheFunction(listOfVariableNames){
functioncodeshouldbewrittenhere
};

Note that in this particular case, because the function is being assigned, and not defined
normally,thename anotherNameForTheFunctioncanbeusedbythecodeinsidethefunction
to refer to the function itself, but the code outside the function cannot see it at all (note that
some browsers, mainly Internet Explorer, do not implement this correctly, so you should not
relyonititisbettertousearguments.calleeasshownbelow).
TheFunctionclassconstructor
functionName=newFunction("functioncodeshouldbewrittenhere");
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

44/223

5/30/2015

JavaScripttutorial

Thisconstructevaluatesthecodeasastring,andismuchslowerthanassigninganonymous
functions.Itshouldonlybeusedinplaceswhereitisactuallyneeded.
TheFunctionclassconstructorwithparameters
functionName=newFunction("varName","varName2","etc.","functioncode");

See the section on 'Referencing' subsection 'Avoiding referencing conflicts' to see how to choose
namesforyourfunctions.
Functionsarecalledusingoneofthese:
nameOfFunction(listOfVariables);
window.nameOfFunction(listOfVariables);
object.onEventName=nameOfFunction;

When created using the normal function construct, the definition does not have to appear at the
start of the script (though it is usually best to do so for the sake of clarity). It can even be defined
afterthethecodethatcallsit.Inmostcases,nomatterwhereyouchoosetodefineyourfunction,
theJavaScriptenginewillcreatethefunctionatthestartofthecurrentscope.
Note that you should never create a function using the normal function construct inside an 'if'
statement(oranyequivalentcontrolstructure):
if(someCondition){
functionfunctionName(){
...thiswillnotworkinmostbrowsers...
}
}

ThisispermittedbyMozilla'sJavaScript1.5,butthisconflictswithECMAScript3,thecorelanguage
used by JavaScript 1.5. As a result, Mozilla based browsers allow it, and most others do not (they
will always evaluate the function, even if the condition evaluates to false). It is best not to rely on
either behaviour, and do not try to declare functions in this way. Declaring functions inside these
statements is possible in all current browsers using assigned anonymous functions, and this is the
correctwaytoachievethedesiredeffect:
varfunctionName;
if(someCondition){
functionName=function(){
...
};
}

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

45/223

5/30/2015

JavaScripttutorial

Passingvariablestofunctions
Variablespassedtoafunctionareknownasarguments.
When a function is called, the variables or values passed to it in the brackets are assigned to the
variablenamesinthebracketsofthefunctiondefinition.
functioncheckval(passvar){
//ifIranthefunctionusingthecommand"checkval('hello')"
//thenpassvarwouldtakeonthevalue'hello'
if(passvar!=""){
document.myform.mytextinput.value=passvar;
}
}

This function, when called, will set the value of a text input to whatever value of passvar was, as
longaspassvarwasnotblank.
Asanexample,partofmyhtmlwillcontainthis:
<inputtype="button"onClick="checkval('pygmy')">

Whentheuserclicksonthebutton,thetextinput'svaluewillchangeto'pygmy'.
Youcanpassmorethanonevariabletoafunctionusingcommastoseparatethevalues:
functionfunctionName(variable1,variable2,variable3,etc.){functioncode}
functionName(5,6,7,etc.);

Ifnotenoughvariablesarepassedtofillupallofthevariablesinthefunctiondeclaration,thenany
remaining variables will contain the value undefined. You can pass no variables to a function like
this
functionfunctionName(){functioncode}
functionName();

IfIcalledthatlastfunctionusingsomethinglikethis:
functionName(1,2,3,myVar,window,'stringybit')

ThevariableswouldstillbepassedtothefunctionbutIwouldonlybeabletoaccessthevariables
usingtheargumentscollection(whichcanalsobereferencedasreferenceToFunction.arguments).
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

46/223

5/30/2015

JavaScripttutorial

Youcanusetheargumentscollectiontorefertothearguments,evenifyoudidnotwritethevariable
nameinthefunctiondefinition,oryoucanmixitsothatsomevariablenamesaredefinedbutothers
areonlyavailableusingtheargumentscollection:
functionfunctionName(variable1,variable2){
window.alert(variable1);//alerts5
window.alert(arguments[0]);//alerts5
window.alert(variable2);//alerts6
window.alert(arguments[1]);//alerts6
window.alert(arguments[2]);//alerts7
window.alert(functionName.arguments[3]);//alerts8
}
functionName(5,6,7,8);

The argumentscollectionalsohasaveryusefulproperty arguments.callee. This is a reference to


the function itself, meaning that code running inside an anonymous function can still obtain a
referencetothefunctionthatisbeingrun.Thispropertyisnotavailableinsomeolderbrowsers.

Usingthereturnstatement
The return statement causes a function to stop executing at that point. The code that called the
functionwillstillcontinuetoexecute.
functiondoWhatever(){
varapod=Math.pow(3,7);
return;
//thefollowingcodewillnotbeexecuted,
//nomatterwhat
apod*=34;
if(700*3<=apod){
return;
//returnonitsownismoreusually
//usedaspartofaconditional
}else{
window.alert('Thescripthasmadeamistake');
}
}

Thefollowingisanexampleofusingthereturnstatementtoreturnavariablefromafunction:
functionappendComment(passvar){
//inthiscase,IhavepassedastringvariableandIreturn
//astringvariable.IcouldreturnanyvariabletypeIwant.
passvar+='withoutyourhelp';
returnpassvar;
}
varmyString=appendComment('Ididit');
//myStringisnow'Ididitwithoutyourhelp'
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

47/223

5/30/2015

JavaScripttutorial

Note that if you need your code to work in older browsers, it is important to make sure that if the
returnstatementisusedtoreturnavalue,youmustensurethatinallcases,thefunctionreturnsa
value,orsomeNetscape4versionswillproduceerrors.
Take,forexample,theactionoffading.Iwanttowritethesamethingrepeatedly,slowlyfadingfrom
onecolourtoanother.Ratherthanhavingtocalculatethismanually,Iwanttorunsomescriptthat
calculatesthefadeforme.Thescriptwillrunnicelyaspartofafunction,wherethefunctionreturns
thenextcolourateachstep,whichIcanthenuse.Thisisuseful,becauseIcanthenusethesame
functiontoproduceavariationofthesameeffectlateron,basedondifferentparameters.
functionfadeColour(fromcol,tocol,fadePortion){
//intheformatfadeColour('ff0098','fe0934',0.23)
varoF=[],oT=[],oP=[];
varoH=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
//getthered,greenandbluesubstrings...
for(varx=0;x<3;x++){
//...andconvertthemfromhexintodecimal...
oF[x]=eval('0x'+fromcol.substring(2*x,(2*x)+2));
oT[x]=eval('0x'+tocol.substring(2*x,(2*x)+2));
//...addontherequiredportionofdifferencebetweenthetwo...
oP[x]=Math.round(oF[x]+((oT[x]oF[x])*fadePortion));
//...andconvertitbackintohex...
oP[x]=oH[(oP[x](oP[x]%16))/16]+oH[oP[x]%16];
}
//...andputthembacktogetheragainasacolourstring
return'#'+oP.join('');
}
for(vary=0;y<10;y++){
//in10steps,fadethecolouralsoseethesectiononwritingwithscript
document.write('<spanstyle="color:'+fadeColour('d2cbff','000099',y/9)+
';">Fade!<\/span>');
}
for(vary=0;y<12;y++){
//in12steps,fadethecolour
document.write('<spanstyle="color:'+fadeColour('ff0000','000000',y/11)+
';">Fade!<\/span>');
}

Fade!Fade!Fade!Fade!Fade!Fade!Fade!Fade!Fade!Fade!
Fade!Fade!Fade!Fade!Fade!Fade!Fade!Fade!Fade!Fade!Fade!Fade!
Warning, if you are returning a value from a function, do not call the function directly from the
<ahref= method to activate it, or many browsers will (correctly) create a new page containing the

returnedvalueasthepagecontent.Youcanstilluse return;onitsown.Youcanonlyreturnvalues
ifyoucallthefunctionscriptfromanotherpieceofscript(likeanotherfunction).
Ifyouneedtocallthefunctionusingthe<ahref=method,usethevoidoperator.
Note,returningfalseformanyeventswillcanceltheaction.Asanexample,ifausersubmitsaform,
returning false will cause the form not to be submitted. The exception is onmouseover, where
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

48/223

5/30/2015

JavaScripttutorial

returning true will stop the mouseover from having any effect (such as with a link, where returning
truewillstopthelinkurlfrombeingdisplayedinthestatusbar).

Variablescope
VariablescopeisoneoftheveryusefulfeaturesoflanguageslikeJavaScript,soeventhoughitmay
seemalittlecomplicated,itisworthtakingthetimetolearnhowitworks.
Inabasicscript,theremaybeanynumberofvariablesandfunctions.Takethefollowingexample:
vara=1,b=2,c=3;
functionsample(){
vard;
a=7;
}
sample();
alert(a);

Thevariables a,band carenotinsideanyfunctionwhentheyaredeclared,sotheyareinascope


called the global scope. They are available anywhere. Code anywhere else in the script, including
inside the sample function, has access to them. The sample function is also global, since it is not
insideanyotherfunctions.Ifanyotherpieceofcodechangesthecontentsofthosevariables,then
every other part of the code now sees the new contents. As a result, the alert here will show '7',
sincethevalueheldbytheglobalvariableischangedwhenthefunctionisrun.
Variable d is defined inside the sample function, so it is not global. It is in the local scope of the
function. What that means is that only the code inside the function can see it. Code outside the
functiondoesnotevenknowitexists.Thishappenswithanyfunction.Theyhavetheabilitytocreate
theirownscopes,andtheirownlocalvariables,withouttheminterferingwithvariableslocatedinthe
global scope. Variable names written in the brackets of the function definition are also created as
variablesinthelocalscope(andthesameappliestotheargumentscollection):
functionsample(myvar){
//myvarisnowavariableinthelocalscope
alert(myvar);
}
sample('hello');

Nowtrythismodificationtotheearliercode:
vara=1,b=2,c=3;
functionsample(){
vara,d;
a=7;
}
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

49/223

5/30/2015

JavaScripttutorial

sample();
alert(a);

Here,thevariable aisredefinedinsidethefunction.Becauseitisdeclaredusingthe varkeyword,it


becomesalocalinstanceofavariable.Eventhoughitsharesthesamenameasaglobalvariable,
the two are completely independent. The changes made to that variable inside the function only
affectthelocalvariable,nottheglobalone.Asaresult,thealertwillshow'1',andnot'7'.
Nowimaginethatthecodeinsidethefunctionwantstoreferencetheglobalvariable 'a'insteadof
thelocalone.Theglobalscopeisspecial.InJavaScript,theglobalscopecanbereferencedusing
the name 'window'. The code inside the function can use window.a to reference the global 'a'
variable.Incidentally,thisiswhymethodslikealertcanbecalledusingeitheralertorwindow.alert,
since these methods are globally available (unless they are overwritten in the current scope, of
course).

Nestedfunctions
It is possible to create functions inside other functions. Simply declare another function inside the
codeofanexistingfunction:
vara=1,b=2,c=3;
functionsample(){
vara,d,e;
functionanothersample(){
vare,f;
}
anothersample();
}
sample();

Inthatexample,theanothersamplefunctiononlyexistsinsidethesamplefunction,anditcanonlybe
called by the code inside the sample function. Code outside that function does not even know it
exists.Thescopesarealsonested,sothecodeinsidethe anothersamplefunctionhasaccessto b
and c from the global scope, a and d from the sample scope, and then e and f from its own local
scope.Itcanalsousewindow.atoreferencethevariableafromtheglobalscope.
Ofcourse,ifyouassignareferencetothenestedfunctiontoaglobalvariable,thenthefunctioncan
be accessed globally through that variable. There is not much point in doing that here, but it
becomes very useful when creating object methods (these will be covered in detail in a later
chapter).

Scopeshavememory

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

50/223

5/30/2015

JavaScripttutorial

Scopesareactuallyveryclever,sincetheypersistovertime.Imaginethatthecodeinsideafunction
creates a local variable. It also creates an event handler function that will be triggered when the
userclicksalink:
functionsample(){
vara=20;
document.links[0].onclick=function(){
alert(a);
};
}
sample();

The action that calls the event handler (inner) function happens much later, a long time after the
scriptthatcreatedithasfinishedrunning.However,thevariable 'a' has survived, so the alert will
displaythenumber20.

Usingscopetopreventconflicts
Imaginethatyouarerunningascriptthatusesmanyglobalvariableandfunctionnames.Youwant
toputanotherscriptonthesamepage,butthereisachancethatthetwoscriptswillusethesame
variablenamesaseachother,andmayconflict.Itiseasytoworkaroundthisproblembyputtingthe
codefromeachscriptinsideafunction,andrunningthefunction.Thatway,thelocalscopeprovided
bythefunctionwillprotectthevariablesoverwritingeachotherintheglobalscope.Notethatwhen
doingthis,itisveryimportantthatyouremembertodeclareyourvariablesproperly.
Theeasywaytodothiswithoutcreatingaglobalfunctionistocreateananonymousfunction,and
enclosing it in parenthesis (internally, the engine will then replace that entire construct with the
function reference). You can then use the openclose parenthesis to run it immediately. This
constructmaylookalittleodd,butitworks:
(function(){
//Putyourscriptcodeinhere
})();

Usingnestedfunctionscopetopreserveinstantaneousvalues
Thisisanadvancedtopicthatiscoveredinitsownarticle.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

51/223

5/30/2015

JavaScripttutorial

Referencing

Howbrowsersaffectit
Referencingis,inmyexperience,thehardestthingtolearntogetright.Itisnothelpedbythefact
thatthemethodsrequiredmaybedifferentindifferentbrowsersandsoyouhavetoincludeseveral
different versions of the code to ensure it will work in all of them. I have put together a list of the
mostpopularbrowsersavailablethatsupportJavaScript.
Opera, Mozilla and Safari/Chromebased browsers currently have the highest level of JavaScript
support, but many scripts are poorly written, and are based on the implementation of just a few
browsers,typicallyjustInternetExplorerandoneotherbrowser.Unfortunately,InternetExplorer8
doesnothaveaverygoodJavaScriptimplementation.Itoftendoesnotcomplywiththestandards,
relying instead on authors to use its nonstandard extensions. Many authors do not realise these
are nonstandard, and end up writing code that relies on these extensions. Other browsers may
implement some of these extensions in an attempt to get these scripts to work. To make matters
worse, when running in quirks mode, Internet Explorer 9+ removes support for the standards
approach, and reverts to the scripting support of earlier versions. Scripts that need to run in both
standards and quirks mode will still need to allow for both approaches, even if older versions of
InternetExplorerarenotbeingused.
What I have done in this tutorial is to carefully test the responses of as many different browser
enginesasIcould,andputtogethersomethingthatworksinasmanyofthemaspossible.Where
possible, I will rely on the standards compliant version, and only fall back to the alternatives if a
standardscomplianttechniquecannotbeused.
AlthoughtheW3CDOMmakesitpossibletoaccessanyobjectusingastandardDOMstructure,the
older approaches are still possible, and widely used on the Web. These older approaches will be
coveredfirstinthistutorial,asitisnecessarytoknowthemwhendealingwithcodethatisdesigned
toworkinallpossiblebrowsers,includingtheolderones.

Objecthierarchy
To reference items (objects) on the page, refer to an object structure or hierarchy. The topmost
object is usually 'document' and the next will be different depending on the document structure.
Mostelements(HTMLtags)cannotbereferencedinall4 thgenerationbrowsers.Thosethatcanare:
body,referredtoasdocument
div,referredtousingbrowserspecificreferences,targettingitsid
span, referred to using browser specific references, targetting its id (it is best not to reference
thisfor4 thgenerationDHTMLaslayersbrowsershavebugsthatwillshowupifyoudo)
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

52/223

5/30/2015

JavaScripttutorial

img,referredtothroughthedocumentobjecttargettingitsname
a,referredtothroughthedocumentobjecttargettingitsindex
form,referredtothroughthedocumentobjecttargettingitsname
input,selectortextarea,referredtothroughtheformtargettingitsname
In most browsers, these components will be available to scripts immediately after they have been
written.Ifbeingwrittenbyscript,theyshouldbeavailableimmediately,butinsomeolderbrowsers
theymaynotbeavailableuntilthatscripthascompletedexecuting(afterthe</script>tag).Insome
more poorly written old browsers, these document components will only be available after the
documenthasloaded.
Youcandetectwhenthedocumenthasloadedusingthewindow.onloadevent(whichcanalsobe
writteninHTMLas <bodyonload=...).Strangely,olderGeckobrowsers(Mozilla/Firefox1/Netscape
6+)willneedatleastonenonentitycharactertobewrittenbetweentheelement'sopeningtagand
thescript,eveniftheelementisanimage,ortheelementwillnotbeavailabletoscriptuntilafterthe
pageloads.
Thereareafewotherselementsthatcanbereferenced.Foralistofobjects,properties,collections
and methods, refer to the section on The JavaScript object. In 5 th generation browsers (the vast
majority of browsers in use today), all elements can be rederenced using the DOM. This will be
coveredinlatersections.
I have written a generic referencing function that can be used to reference all document
components that can be referenced (except links), but I suggest you work through the next few
sections of the tutorial first instead of taking a shortcut. You might actually understand what I am
doing,insteadofblindlyusingmycodewithoutknowinghowitworks.

Avoidingreferencingconflicts
RememberthatallnamesinJavaScriptarecasesensitive.NamesmustbeginwithazorAZor_
and may only contain the characters az, AZ, 09 and _. The convention is to use names that
describetheobject.Ifthenameismadeupofmorethanoneword,thereshouldneverbeaspace
between the words and it is not usual to have an underscore ( _ ) between the words. The usual
practiceistocapitalisethefirstletterofallwordsexceptthefirst.
For example, I have a variable that I will be using to store some text about me. I decide the best
name is 'text about me' and I must remove the spaces and capitalise the first letters of all words
exceptthefirst.Therefore,thevariablenamebecomes'textAboutMe'.
In order to avoid referencing conflicts, you must make sure that no two JavaScript objects or
documentelementsaregiventhesamename(exceptinputsseethenextsection).
Whenchoosingnamesforvariables,functionsandbothnamesandIDsofHTMLelements,thereis
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

53/223

5/30/2015

JavaScripttutorial

a set of reserved words which you must not use, regardless of the case. These are: abstract,
arguments, boolean, break, byte, case, catch, char, class, const, continue, debugger, default,
delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if,
implements,import,in,instanceof,int,interface,long,native,new,null,package,private,protected,
public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try,
typeof,var,void,volatile,while,with.
In addition, it is generally a good idea not to use names that conflict with the names of existing
properties or methods of the global/window object (unless you really want to overwrite them). See
thesectiononTheJavaScriptobjectformoredetails.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

54/223

5/30/2015

JavaScripttutorial

Browserinspecificreferencing

Notethattoavoidreferencingproblems,notwoelementsshouldever be given the same name or


id.Theonlyexceptionisforminputswhichcansharenames.

Globalreferences
Variables are referenced simply by typing their name, or by using window.variableName for global
variables.
Functions are referenced simply by typing their name, or by using window.functionName for global
functions.
'window' (or 'self') may be used to reference the global object for the current document,

regardlessofwhatscopeyourscriptisrunningin.Ifyourscriptisrunninginanotherscriptandyou
are having trouble referencing global variables because a local variable uses the same name, this
problem can be quickly solved by adding 'window.' to the start of the variable name. For example
window.myvariable

Byasimilarnature,youcanuse'this'torepresentthecurrentobject.Bydefault,'this'willbethe
window object. If you are writing the script as part of a HTML event handler, 'this' will be the

elementthatdetectedtheevent.Forexample,thiscanbeusedtoalertthevalueofthetextinput:
functionmyFunction(x){window.alert(x.value);}
...
<inputtype="text"onkeypress="myFunction(this)">

Using this same function from a script running in the global scope, the word 'this' refers to the
window object. The window object does not have a value property, so the function would alert

'undefined'.
However,ifthe onkeypressmethodisactivatedmanually,theword 'this'onceagainreferstothe
input,sothefunctionwillalertthevalueoftheinput:
document.forms[0].elements[0].onkeypress();

Framesetreferences
There are four very useful references that refer to parts of a frameset. These are 'window' or
'self', 'window.parent', 'window.top' (window is usually omitted) and the window.frames
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

55/223

5/30/2015

JavaScripttutorial

collection.
selfandwindow

Theserefertotheglobalobjectofcurrentwebpage.
parent

Referstothewindowobjectofthepagethatisholdingthecurrentpageinaframeset.
top

Referstothewindowobjectofthepageatthetopoftheframeshierarchy.
window.frames[nameOrNumberOfFrame]

Referstoaframeoriframeheldbythecurrentpage.
Withiframes(ifthebrowsersupportsthem)youhavetousetheextraword'window'ontheendto
reference the window object of the document contained by the iframe (there are alternatives, but
thisoneworksinallbrowsersthatsupportiframes,makingitsuperiortoallothertechniques,since
theyonlyworkinaselectionofbrowsers):
window.frames[nameOrNumberOfFrame].window

Ifthepageistheonlypagebeingdisplayed, top,parent,selfand windowwillbeequal.Ifthepage


isbeingheldwithinaframeset,selfandtopwillnotbeequal.Ifthepageisthepagecontainingthe
frameset,andititselfisnotbeingheldwithinaframeset, selfand topwillbeequal.Ifsomeoneis
loading your page into their frameset and you don't want them to, you can use the selftop
relationship to remove your page from their frameset and replace their frameset page with your
pageusing:
if(self!=top){top.location.replace(self.location.href);}

Note,Icouldhaveusedthis:
if(self!=top){top.location.href=self.location.href;}

However, that makes the browser add the new entry into its history, so if they clicked their back
button, they would be forwarded back to your page again. Unfortunately, Gecko browsers
(Mozilla/Firefox/Netscape6+)willonlyallowthesecondoptionastheyhaveveryhighsecuritylevels
relatingtocrosssitescripts.
Notethatusingscriptstoforcepagesinandoutofframesetsisaverybadidea.Itcausesusability
problemsformanyusers,breakssearchengines,andannoysyourvisitors.Iknowyouknowhowto
doit,butthatdoesnotmeanthatyoushould.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

56/223

5/30/2015

JavaScripttutorial

With all frames, the name is set using the name="nameOfFrame" attribute in the <frame...> tag. The
number is automatically generated by the browser in the order that the frames are defined in the
HTML,beginningat0.
Tofullyreferencethewindowobjectofanotherframewheninsideaframeset,useoneofthese:
parent.frames.otherframename
parent.frames['otherframename']
parent.frames[2](assuming2istheindexoftheframe)
parent.otherframename

Fromthere,youcanreferenceitemsinsidethatdocumentusingdocument.whatever
parent.frames['otherframename'].document.images['imagename'].src="sample.gif";

Take,forexample,thefollowingframepagestructure.Themainpagemain.html(whichbydefault
has no name, although it can be set with JavaScript, or by opening the page with
target="newName")containstwoframes 'left'and 'right'.'left'containsthepage'links.html'.
'right' contains a page inner.html containing a further two frames 'banner' and 'mainpart'.

Thelocationsof 'banner'and'mainpart'areupper.htmlandlower.htmlrespectively.Thenamesof
the files are irrelevant, but it helps me to explain the structure to you. This produces the following
frametreestructure:
unnamedframe(main.html)
____________|____________
||
left(links.html)right(inner.html)
__________|______________
||
banner(upper.html)mainpart(lower.html)

Thefollowingexamplesusetheframescollection,althoughanyoftheabovesyntaxeswouldbefine.
Ifascriptwererunninginmain.html,itwouldbeabletoreferencethewindowanddocumentobjects
oflower.htmlusingthis:
window.frames['right'].frames['mainpart']
window.frames['right'].frames['mainpart'].document

If a script were running in lower.html, it would be able to reference the window object of links.html
usingeitherofthese:
window.parent.parent.frames['left']
window.top.frames['left']
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

57/223

5/30/2015

JavaScripttutorial

Attempting to access the contents of a frame before they have loaded will cause an error. In all
browsers,thewindowobjectwillnotexistforthatframeunlessthepagehasloaded.
if(!window.frames['nameOfFrame']){window.alert('Framehasnotloaded');}

Thisalgorithmalsoworkswithiframes,withoutrequiringanychanges.

Forms
NotethatthischangesinNetscape4andotherlayersbrowsersiftheformisputinsideapositioned
element.SeethesectiononElementcontentsformoredetails.Sincethesebrowsersarenolonger
inuse,thisbehaviourcanbesafelyignored.
To fully reference a form, use document.formname for a form that was defined with the
name="nameOfForm"attributeinthe <form...>tag,or document.forms[number_of_form]eithershould

work.Thenumberisgeneratedautomaticallybythebrowserintheorderthattheformsaredefined
intheHTML,beginningat0.
Tofullyreferenceaninput,useanyofthese:
reference_to_form.inputname
reference_to_form.elements['inputname']
reference_to_form.elements[number_of_input_(not_image_input)]

Name is defined using the name="nameOfInput" attribute in the <input ...>, <textarea ...>,
<button...>or <select...> tags. Number is generated automatically by the browser in the order

thattheinputsaredefinedintheHTML,beginningat0.
You can read or write the value of text inputs and textareas with their 'value' property. See the
sectiononTheJavaScriptobjectforafulllistofwhatpartsofaformcanbereadorchanged.
Ifmorethanoneinputofanykindinthesameformsharethesamename(asiscommonwithradio
button inputs), they must be referenced using the numerical array associated with that name. The
arraywillcontainanentryforeachinputwiththatname,inascendingorderofhowtheyappearin
thesourceofthedocument,beginningat0.Forexample,ifaradiobuttonhasthename'mybutton',
itcanbereferencedusingthis:
document.nameOfForm.mybutton

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

58/223

5/30/2015

JavaScripttutorial

But if two radio buttons share the name 'mybutton', the second button (for example) can be
referencedusingthis:
document.nameOfForm.mybutton[1]

This will be the case for any input type, even if inputs of different types share the same name. In
practice,radiobuttonswillalmostalwaysshareaname,andcheckboxesmayoccasionallysharea
name.Evenifinputsshareaname,theywillstillhaveindividualentriesintheelementscollection.
For

select

boxes,

each

individual

option

can

be

referenced

using

input_name.options[number_of_option].Forexample:

if(document.myForm.mySelect.selectedIndex==1){
document.myForm.mySelect.options[3].selected=true;
if(!document.myForm.myRadio[1].checked){
document.myForm.myRadio[2].checked=false;
document.myForm.myRadio[1].checked=true;
document.myForm.myRadio[0].checked=false;
}
}

Youcanreferencethevalueofanoptiontagwith'.value'andthetextitdisplayswith'.text'.You
can also find out how many options there are by using the '.length' property of the options
collection.
Note,settingaselectoptiontonullwillremoveitfromtheselectbox:
document.forms[number_of_form].mySelect.options[0]=null;

All other options will have their index numbers adjusted to reflect this change. To add or replace
one,usethis:
document.forms[number_of_form].mySelect.options[number]=newOption('text','value');

Mostcommonly,numberusedisthelengthofthecollection,asthatwilladdthenewoptionontothe
end:
document.forms[number_of_form].mySelect.options.length

Warning:althoughtheselectInputObject.selectedIndexpropertyshouldbereadwrite,itisreadonly
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

59/223

5/30/2015

JavaScripttutorial

inInternetExplorer4.Ifthiscausesproblems,youcarusethis:
selectInputObject.options[index].selected=true;

Images
Note that this changes in Netscape 4 and other layers browsers if the image is put inside a
positionedelement.SeethesectiononElementcontentsformoredetails.Sincethesebrowsersare
nolongerinuse,thisbehaviourcanbesafelyignored.
Toreferenceanimage,useanyofthese:
document['imagename']
document.images['imagename']
document.images[number_of_image]

Nameisdefinedusingthe name="nameOfImage"attributeinthe <image...>tag.Numberisgenerated


automaticallybythebrowserintheorderthattheimagesaredefinedintheHTML,beginningat0.
Note, if you compare document['imagename'].src to a string constant, you will find that in some
browsersitmaybethesamewhereasinothersitisnot.Thisisbecausesomebrowserswillgivethe
image src in the format 'myimage.gif' whereas others may give it in the format
'http://mydomain.co.uk/myimage.gif':
if(document['imagename'].src=="pig.gif"){
...
if(document['imagename'].src==myImage.src){

A solution to this is to use the string method 'indexOf()'. If the parameter is not contained within
thestring,themethodreturns1,elseitreturnsthepositionofthefirstoccurrenceoftheparameter
withinthestring.Forexample:
if('http://mydomain.co.uk/myimage.gif'.indexOf('myimage.gif')+1){
//Thiswillbeexecuted
}
if('http://mydomain.co.uk/myimage.gif'.indexOf('yourimage.gif')+1){
//Thiswillnotbeexecuted
}
if('http://mydomain.co.uk/myimage.gif'.indexOf('image.gif')+1){
//Thiswillbeexecuted.BEWARNED,thismaycauseaproblem
}

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

60/223

5/30/2015

JavaScripttutorial

Links,anchorsandareas
NotethatthischangesinNetscape4andotherlayersbrowsersifthelinkisputinsideapositioned
element.SeethesectiononElementcontentsformoredetails.Sincethesebrowsersarenolonger
inuse,thisbehaviourcanbesafelyignored.
Toreferencean <a...>element,therearetwoways(excludingthoseprovidedbytheDOM).Ifthe
name attribute is set, so making the element an anchor (used in <ahref="#nameOfLink">) you can
refertoitusingthis:
document.anchors[number_of_<a>_element]

Alternatively,ifthehrefattributeisset,youcanrefertoitusingthis:
document.links[number_of_<a>_element]

Numberisgeneratedautomaticallybythebrowserintheorderthatthelinksoranchorsaredefined
intheHTML,beginningat0.
As<area...>tagsalsohavethehrefattribute,theymayalsobeaccessedusingthelinkscollection,
butnottheanchorscollection.Ifan<a...>elementhasboththethehrefandnameattributesset,it
will appear in both collections, although its index may be may not be the same in each. In layers
browsers, any links or anchors referred to using the anchors collection will have only the name
propertyavailable.Thecollectionprovidesaccesstotheanchorspurelyforthepurposeofchanging
thename,usedwhensettingthelocationwithlocation.hash.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

61/223

5/30/2015

JavaScripttutorial

Browserspecificreferencing

Thefactthatthisreferencingisbrowserspecificdoesnotmeanthatitwillnotworkinallbrowsers.
Whatitdoesmeanisthatyouwillhavetoincludemorethanonewayofreferencingitemstoensure
thatyoumanagetoreferencethemcorrectly.Therearefourwaystoreferenceitems:
W3CDOM
Netscapelayerscompliant
Netscapealternativecompliantstrictlyspeaking,thisisalsolayerscompliant
ProprietaryDOM
ThemainoneistheW3CDOM,whichissupportedbyallcurrentbrowsers.Lateroninthistutorial,I
will move over to concentrating only on the DOM version, since it is much more capable than the
others. However, since this stage of the tutorial deals with the tasks required for 4 th generation
DHTML,Iwilluseallofthesetechniques,sothecodewillworkinolderbrowsersaswell.Whenyou
writeyourowncode,someofthismaybeunnecessary,dependingonwhatbrowserspeopleuseto
viewyoursite,butyouwillfrequentlyencountercodethatusestechniques,soithelpstounderstand
whattheyaredoing,andwhy.
Therearemanysimilaritiesandcrossoversbetweenthedifferentmethodsandinmanycasesthere
areonlytwodifferentvariationsrequiredatatime,forexamplewhenfindingthesizeofthescreen
orthebuttonofthemousethatwasclicked(seethesections'Windowsizeandscrolling'and'Event
information').
Writingscriptusingbrowserspecificreferencingisnotdifficult.Themainthingtorememberisnever
to make assumptions. Just because a browser uses Netscape compliant syntax to reference an
element,thatdoesnotmeanthatisusesNetscapecompliantsyntaxtoreferencethestyle.
The way I will show you to write never makes assumptions. What is more, it uses all four types of
syntax (where they exist) allowing browsers that support any one of the types of referencing to
work.Thatistheonlywaytoproducetruecrossbrowserscripts.
Todownloadthebrowsersthemselves,seemylistof'4 th+generation'browsers.

Elementposition
Internet Explorer will only get the values right after the page has loaded, until then it returns incorrect values,
usually0,0.
Safari1.3getstheoffsetwrongforfixedpositionelements,asitaddsonthe8pixelbodymargin.
WebTV,Escape,NetFront3.3,TkhtmlHv3andOmniWeb4.2donotprovideawaytoworkoutthepositionof
elements(forabriefwhile,Escape4.8could).
Netscape4canonlyworkoutthepositionsoflinks,nototherelements.
Netscape4willnotprovidethexandypropertiesaschildrenofthelinkobjectifthenameattributeisset.Instead,
theywillbechildrenofthecorrespondinganchorobject.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

62/223

5/30/2015

JavaScripttutorial

Opera 8 can have trouble working out positions if the BODY or HTML element has auto left/right margins, or
display:table.

IamunsureofthecapabilitiesofNetBox,iPanelMicroBrowserandOpenTVhere.

Asanexampleofbrowserspecificscript,Iwilldemonstratehowtofindthepositionofanelementon
a web page. Note, that in older browsers, this can be a little unreliable with elements that are in
anotherelementthatispositionedabsolutelyorrelativelyusingCSS.TobenicetoNetscape4,Iwill
demonstratethiswithalink,butitcouldworkanywhereinotherbrowsers.
InNetscapecompatiblebrowsers,everylinkobjecthastwopropertiesthatgiveitscurrentposition,
linkObject.x and linkObject.y. In DOM compatible browsers, these do not exist. Instead, the
elementObject.offsetLeft and elementObject.offsetTop properties are given. These give the

positionofthelinkrelativetoanarbitraryancestornode,knownastheoffsetParent.DifferentDOM
browsersgiveadifferent offsetParent,somemaysaytheparagraphthatthelinkisin,whilesome
maysaythecontainertheparagraphisin.Thiscanallgetabitcomplicated.
Fortunately, with DOM browsers, the offsetParent will also have the offsetTop and offsetLeft
properties, giving its position relative to its offsetParent, and so the cycle continues, until the
offsetParent is the topmost node in the document, which will always be at offset (0,0). We can

access the offsetParent using elementOrCurrentNode.offsetParent. So all we have to do is add


the offsets together and we will end up with the same answer as we would if we had the
linkObject.xandlinkObject.yproperties.

There is one exception to this if an element has position:fixed, its offsetParent should be the
viewport,whichcannotbereferenced,sothe offsetParentis nullinstead.However,its offsetTop
and offsetLeft still hold real values. (The situation is actually the same for the HTML or BODY
elementwhentheyareattachedtotheviewport,buttheygenerallyhavenooffsetthere,soitdoes
notmatter.)Whatthismeansisthatevenwhenthe offsetParentisnull,youstillneedtoremember
to add on the last set of offsetTop and offsetLeft values. Opera 9+, Internet Explorer, and
ICEBrowsergetthisright.Otherbrowserswilltreatthe offsetParentofafixedpositionelementas
eithertheHTMLorBODYelements,butthisisharmlessbecausetheythemselveshavenooffsets,
sothealgorithmwillalwayswork.
Thefollowingfunctionreturnsanarraycontaining[leftPosition,topPosition]foranelement.
functionfindPosition(oElement){
if(typeof(oElement.offsetParent)!='undefined'){
for(varposX=0,posY=0;oElement;oElement=oElement.offsetParent){
posX+=oElement.offsetLeft;
posY+=oElement.offsetTop;
}
return[posX,posY];
}else{
return[oElement.x,oElement.y];
}
}
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

63/223

5/30/2015

JavaScripttutorial

Testithere:getthepositionofthislink.
Withlinks,youcanalsocheckwhatthetextofthelinkis:
vartheText=linkObject.text?linkObject.text:linkObject.innerText;

Elementpositionwithscrollingoffsets
Operadoublesthescrollingoffsetsforinlineelements,butisreliableforblockelements.

ThesimplefindPositionscriptcalculatesthepositionofelementsanywhereonthepage,butonlyif
they are not inside a scrollable element. This serves the vast majority of purposes, and is the
preferred approach in most cases. Inside a scrollable element (created using the overflow style),
the element can scroll the contents, but the calculated position will assume the element is not
scrolled at all. To work out the position after scrolling, the script needs to step through all parent
elements (or positioned containers if at least one element in the offsetParent chain is positioned
absolutely),andsubtractanyscrollingoffsetsforthem.
Workingoutwhichscrollableelementsareactuallygoingtoaffectthepositionrequiresknowledgeof
whatelementsarecontainersforanypositionedelementsinthechain.Thiscanbecomplicatedto
calculateforascript,sotheeasiestapproachistomakesurethateveryelementwithan overflow
of anything other than visible also has a position style set to something other than the default
static.Thisway,theywillallappearinthe offsetParentchain,andcanbeeasilysubtractedinthe

sameloopthataddstheoffsetLeftandoffsetTop.
As a separate complication, there is the document scrolling. The document scrollbar can be
producedbyeitherthe BODYor HTMLelements,dependingonthebrowser,DOCTYPE,and overflow
stylesontheelements.Differentbrowsersalsoreflectthisscrollingindifferentwayswhenchecking
for scrolling on these elements, and this makes it completely unreliable. The easiest approach is
simply to exclude any scrolling on these elements. If needed, it can be added later by working out
howfarthedocumenthasbeenscrolled(coveredinthewindowsizeandscrollingchapter).
The scrolling offset for each element is available as the scrollTop and scrollLeft properties for
those elements. The following code performs as described (including making sure it does not
subtract any scrolling for the target element itself). Make sure all scrollable elements have the
positionstylesetasshownabove.
functionfindPositionWithScrolling(oElement){
if(typeof(oElement.offsetParent)!='undefined'){
varoriginalElement=oElement;
for(varposX=0,posY=0;oElement;oElement=oElement.offsetParent){
posX+=oElement.offsetLeft;
posY+=oElement.offsetTop;
if(oElement!=originalElement&&oElement!=document.body&&oElement!=
document.documentElement){
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

64/223

5/30/2015

JavaScripttutorial

posX=oElement.scrollLeft;
posY=oElement.scrollTop;
}
}
return[posX,posY];
}else{
return[oElement.x,oElement.y];
}
}

Note that this performs much more slowly than the simple findPosition script, so it should only be
usedwhereabsolutelynecessary.
ItispossibletouseDOMtostepuptheentireparentNodechainandsubtractthescrollingoffsetsfor
elementsfromthevaluereturnedbythesimplefindPositionscript.Ifthecomputedpositionstyleis
fixed it can stop. If it is absolute it can stop including scrolling offsets until it reaches another

element whose computed position style is not static (done by jumping to the element's
offsetParent). This would then work without needing to set the position style on all scrollable

elements.However,askingabrowsertoperformthismanycomputationswillcausethescripttorun
veryslowly,soshouldbeavoided.Idonotrecommendusingthiscode,butitishereifyoustillfeel
youneedit:
functionfindPositionWithScrolling(oElement){
functiongetNextAncestor(oElement){
varactualStyle;
if(window.getComputedStyle){
actualStyle=getComputedStyle(oElement,null).position;
}elseif(oElement.currentStyle){
actualStyle=oElement.currentStyle.position;
}else{
//fallbackforbrowserswithlowsupportonlyreliableforinlinestyles
actualStyle=oElement.style.position;
}
if(actualStyle=='absolute'||actualStyle=='fixed'){
//theoffsetParentofafixedpositionelementisnullsoitwillstop
returnoElement.offsetParent;
}
returnoElement.parentNode;
}
if(typeof(oElement.offsetParent)!='undefined'){
varoriginalElement=oElement;
for(varposX=0,posY=0;oElement;oElement=oElement.offsetParent){
posX+=oElement.offsetLeft;
posY+=oElement.offsetTop;
}
if(!originalElement.parentNode||!originalElement.style||typeof(
originalElement.scrollTop)=='undefined'){
//olderbrowserscannotcheckelementscrolling
return[posX,posY];
}
oElement=getNextAncestor(originalElement);
while(oElement&&oElement!=document.body&&oElement!=document.documentElement)
{
posX=oElement.scrollLeft;
posY=oElement.scrollTop;
oElement=getNextAncestor(oElement);
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

65/223

5/30/2015

JavaScripttutorial

}
return[posX,posY];
}else{
return[oElement.x,oElement.y];
}
}

HowthevariousDOMpartsofthisworkwillbecoveredinlaterchaptersofthistutorial.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

66/223

5/30/2015

JavaScripttutorial

DHTML

One of the most popular uses of JavaScript is DHTML (Dynamic HyperText Markup Language).
Strictlyspeaking,DHTMLisusingJavaScripttomodifytheCSSstylesofHTMLelements.Allcurrent
browsers support much more than I will describe at this stage of the tutorial. For now, I will
concentrate on the capabilities introduced by 4 th generation browsers. Old browser versions (such
asNetscape4andOpera6)limittheabilitiesof'4 thgeneration'DHTML,asthesecanonlyhandle
basic DHTML. However, they still provide easily enough flexibility to make features like popup
menus,messagescrollers,mousetrailsorfallingsnoweffects.
Thisrequirespartsofthepagetomoveorappear/disappear.Incurrentbrowsers,thiscanbedone
with any element, and in older browsers can be done reliably using the div element and in many
casesthespanelement,whentheyarepositionedusingtheposition:absoluteorposition:relative
style(exceptwhenchangingthedisplaystyle).Personally,IalmostalwaysusethedivelementandI
canguaranteethatitwillworkwitheverythingIshowyouhere.Someveryoldbrowsers(particularly
Netscape4)haveproblemsusingthespanelementwhenpositionedabsolutely.
Once you have set up the HTML (using a few workarounds for bugs), you can reference the
positionedelement. You can then use that reference to change the visibility,position, background
colour,zindex,clippingandsizeofthepositionedelement.Youcanevenrewritethecontentsofthe
positioned element or create new positioned elements after the page has loaded. DHTML also
allowsyoutochangethebackgroundcolourofthewholedocumentandchangethedisplaystyleof
ANYelement.
Sadly, DHTML is always browser specific, in other words different browsers require different
commands (though with current browsers supporting the DOM, it is often possible to use only that
approachincurrentWebsites).UsingthetechniquesIwillshowyou,thisisnotdifficulttoworkwith,
tomakesurethatnomatterwhatsyntaxthebrowserexpects,thescriptcancheckwhattouse,and
useitcorrectly.Manyauthorsmakethemistakeofdetectingbrowsersandassumingcapabilities,or
detecting one capability and assuming another. This tutorial does not rely on these mistaken
assumptions.Atnopointshouldyouneedtodetectspecificbrowsers.

4 thgenerationbrowsers
There are several browsers that I know of that can handle DHTML (often called 'version 4' or '4 th
generation' browsers, even though their version number may not actually be as high or low as 4).
Thefollowinglistgivesadifferentlineforeachsignificantlydifferentbrowser.Someofthesebrowser
enginesareusedinalargenumberofotherbrowsers.Forexample:
The Internet Explorer (Win) engine is used in Maxthon, Avant, many AOL versions, and many
others.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

67/223

5/30/2015

JavaScripttutorial

TheGeckoengineisusedinCamino,KMeleon,Flock,andmanyothers.
The Opera engine is used on a large number of mobiles and devices, in a variety of different
applications.
TheKHTML/WebkitengineisusedinChrome,OmniWebandseveralotherbrowsers.

Majorbrowsers
InternetExplorer5+(Win)
Usesdocument.getElementByIdanddocument.all
MozillaGecko(FireFox,Netscape6+)
Usesdocument.getElementById(alsosecretlyusesdocument.all)
Opera7+
Uses document.getElementById and document.all (document.all is secretly supported in
Opera9.5+)
KDEKHTML/WebKit(Safari,Chrome,Konqueror3+,OmniWeb4.5+)
Usesdocument.getElementById(Chrome/Safari3alsosecretlyusesdocument.all)

Minorbrowsers
Thesebrowsersarenotusedverymuch,orarenolongerthecurrentversionsofthesebrowsers.
Somemayhavesignificantbugs,limitedcapabilities,orlimitedeventdetection.
SeveraloftheseusetheMozillaOrganization'sJavabasedRhinoJavaScriptenginetopowertheir
browsers.TheRhinoJavaScriptengineonlypowerstheJavaScriptlanguageinterpreter,itdoesnot
govern how JavaScript interacts with the web page. Each browser will have its own DHTML (or
DOM)implementation.
(Internet)Explorer5(Mac)
Usesdocument.getElementByIdanddocument.all
iCab3
Usesdocument.getElementByIdanddocument.all
InternetExplorer4(Win)
Usesdocument.all
(Internet)Explorer4(Mac)
Usesdocument.all
Opera56
Usesdocument.getElementById
MozillaRhinoengine(ICEbrowser)
Usesdocument.getElementByIdanddocument.all
MozillaRhinoengine(Escape/Evo5)
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

68/223

5/30/2015

JavaScripttutorial

Usesdocument.getElementByIdanddocument.all
MozillaRhinoengine(Escape4)
Usesdocument.layers
MozillaRhinoengine(Cluebrowser)
Usesdocument.getElementByIdanddocument.all
Tkhtml+EES(TkhtmlHv3)
Usesdocument.getElementById
Netscape4
Usesdocument.layers
OmniWeb4.2
Usesdocument.layers(alsooptionallysupportsdocument.all)
iCab2
Usesdocument.getElementByIdanddocument.all
Konqueror2
Usesdocument.getElementByIdanddocument.all

Televisionormobiledevicebrowsers
Due to the limitations of the devices that these browsers run on, most will have limited event
detection.Severalpopularbrowsersenginesarealsousedinmobile/TVbrowsers,includingOpera,
WebKitandGecko.Othersusetheirownengines,andaregivenbelow:
NetFront
Usesdocument.getElementById
PocketInternetExplorer
Usesdocument.allanddocument.getElementByIdinnewerversions
Netgem4browser(NetBox)
Usesdocument.getElementById
OpenTV
Usesdocument.getElementById
iPanelMicroBrowserwithadvancedmodules
Usesdocument.getElementById
WebTV(MSNTV)PlusandextendedClassic
Usesdocument.all(andnonnestedlayersalternative)

Moreinformation
For more details of these browsers, and to download them, please see my list of '4 th+generation'
browsers.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

69/223

5/30/2015

JavaScripttutorial

(Youcanalsotrythissiteforafairlycompletelist.)
While many JavaScript and DHTML functions worked in Konqueror 2, the browser was unable to
detectandhandleeventsproperlysomostDHTMLapplicationsdidnotwork.Konqueror3isabig
improvementandisnowahighlycapablebrowser,soIhavegivencompatibilitynotesforKonqueror
3+only.
I am unsure of the abilities of NetBox, iPanel MicroBrowser and OpenTV as I do not have them to
test. The NetBox site claims partial CSS 2, so I assume CSS positioning, and W3C DOM 1, so I
assume DHTML. OpenTV claims absolute CSS positioning and DOM DHTML. The EIS claims that
one of their advanced modules for iPanel MicroBrowser can handle DOM. They might not support
innerHTMLbecausethatisnotpartoftheDOMstandard,eventhoughithasbeenwidelyaccepted
byalmostallDOMbrowsers.
NotethateventhoughEscape4isalayersbrowser,likeNetscape4,itsupportsboththeNetscape
syntax and the style object for changing element style, with the exception of clipping. WebTV 2.8+
alsosupportsbothsyntaxes,butisaproprietaryDOMbrowser.

SettinguptheHTML
There are two types of positioning that are of interest here. These are absolute and relative.
Absoluteallowsyoutopositionanelementanywhereyouwantto,inrelationtothepage.Relative
positionstheelementwhereitnormallywouldbe,andoffsetsitbywhateveramountyouspecify.
Most DHTML is done with absolutely positioned elements. Relatively positioned elements do not
acceptthe'clip'styleanddonotallowtheirclippingtobechanged.Theusefulfeatureofrelatively
positionedelementsisthattheybecomecontainersforabsolutelypositionedelements.Soifyouput
anabsolutelypositionedelementinsidearelativelypositionedelement,itspositionwillbeinrelation
totherelativelypositionedelement,andnotthewholepage.
Youcancreateanabsolutelypositionedelementsusingthis:
<divid="mydiv"style="position:absolute;left:10px;top:120px;">contents</div>

Andyoucancreateanrelativelypositionedelementsusingthis:
<divid="mydiv"style="position:relative;left:10px;top:120px;">contents</div>

The ID is important, because that is what will be used to reference the positioned element. Layers
browserscallthesepositionedelements'layers'.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

70/223

5/30/2015

JavaScripttutorial

Bugs/workarounds
If using document.write to create the positioned element, Netscape 4 will fail to load the page.
Netscape4isnotimportantanymore,soIsuggestyouignoreit.Ifyoureallyneedtosupportit,you
can use the unofficial <layer ...> tag instead of an absolutely positioned div, and the unofficial
<ilayer...>taginsteadofofarelativelypositioneddiv.Useif(document.layers)tofindoutifyou

needto.
Similarly in Netscape 4, setting any styles using inline style attributes on elements inside a
positionedelementwillcausethepagenottoload.Instead,createaclassfortheelementsandstyle
theminthemainstylesheet.

Referencingthepositionedelement
iCab2doesnotsupportpositioning,butitcanstillreferencetheunpositionedelement.

Toreferenceapositionedelement,thereareseveralways.Theofficialoneisastandardcalledthe
W3CDOM.Itissupportedwellenoughbyallcurrentbrowsers.Therearealsotwoalternativesfor
thefewoldbrowsersthatmaystillbeinuse.Oneofthesetechniqueshastwodifferentversions.

DOM
DOMbrowsersusethe document.getElementByIdmethodtoreferencetheelement.Youcanusea
simple if statement to check for the existence of this method. In all current browsers, this will be
supported, so in the majority of current scripts, you can simply assume it is supported, and ignore
theotherapproaches.
if(document.getElementById){

varmyReference=document.getElementById('divID');
}

ProprietaryDOM
Proprietary DOM browsers use the document.all collection to reference the element. Some
browserssupportboththeDOMandproprietaryDOMforreferencingelements.
if(document.all){

varmyReference=document.all['divID'];
}

Layers
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

71/223

5/30/2015

JavaScripttutorial

Layersbrowsersusethe document.layerscollectiontoreferencetheelement.Layersinthelayers
collection can be accessed using either their ID or their numerical index. They will also be able to
reference the element through document.divID (where divID is the id that you gave the div).
Netscape4wasthemainlayersbrowser,andwasthefirstbrowsercapableofperformingDHTML.
However,thelayersapproachhasbeenabandonedbycurrentbrowsers.
if(document.layers){

varmyReference=document.layers['divID'];
}

Layers also have one behaviour that sets them apart from the other approached, and can make
themdifficulttowritefor.Ifapositionedelementisinsideanotherpositionedelement,theinnerone
does not appear inside the layers collection of the document. Instead, it appears inside the layers
collectionforthedocumentobjectoftheouterlayer.Thismeansthatthattoreferenceanylayerby
its ID, you must recursively step through every layers collection in the document, until you find the
rightone.SinceIDattributesmustbeuniquewithinadocumentanyway,thisapproachisneedlessly
convoluted,whichisoneofthereasonswhyitwasabandoned.

Combiningtheapproaches
The three techniques can be combined into a single function, that will use the DOM method if it is
available.Failingthat,itwillusetheproprietaryDOM,andfailingthat,layers.Ifitfailstofinditinthe
document's layers collection, it steps through the entries in the collection, and checks the layers
collectionofeachofthose,andcontinuesrecursively.
functiongetRefToDiv(divID,oDoc){
if(document.getElementById){
returndocument.getElementById(divID);}
if(document.all){
returndocument.all[divID];}
if(!oDoc){oDoc=document;}
if(document.layers){
if(oDoc.layers[divID]){returnoDoc.layers[divID];}else{
//repeatedlyrunthroughallchildlayers
for(varx=0,y;!y&&x<oDoc.layers.length;x++){
//onsuccess,returnthatlayer,elsereturnnothing
y=getRefToDiv(divID,oDoc.layers[x].document);}
returny;}}
returnfalse;
}

Changingthevisibility
iCab2doesnotsupportvisibility.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

72/223

5/30/2015

JavaScripttutorial

OmniWeb4.2frequentlymakesmistakeswithvisibility.
Manydevicebrowserswillignorevisibilitywheninsmallscreenreformattingmode.

Changing the visibility style allows you to make a positioned element appear and disappear. It
can be set to either 'visible' or 'hidden'. Layers browsers use 'show' and 'hide'. There are
somelayersbrowsersthatsupportbothversions.Thecodeherewilldetectwhatissupportedand
useit,insteadofdetectingonethingandassumingsomethingelse.
Onceyouhavereferencedthepositionedelement,youwillneedtoreferenceitsstyle.Innonlayers
browsers,youwillhavetoadd'.style'totheendofthereference.Layersbrowserstreatthestyles
as direct properties of the element itself. To work out which one to use, simply check for the
existenceofthestyleproperty.Youcanthensettherelevantvalue:
So,afterallofthat,afullsetofinstructionstomakeapositionedelementvisiblewouldbe:
functionshowDiv(divID_as_a_string){
//getareferenceasabove...
myReference=getRefToDiv(divID_as_a_string);
if(!myReference){
window.alert('Nothingworksinthisbrowser');
return;//don'tgoanyfurther
}
//nowwehaveareferencetoit
if(myReference.style){
//DOM&proprietaryDOM
myReference.style.visibility='visible';
}else{
//layerssyntax
myReference.visibility='show';
}
}
showDiv('myDiv');
......
<divstyle="position:absolute;left:0px;top:0px;"id="myDiv">
contents
</div>

Testithere:showthehiddenelement.
Of course, don't actually alert the message 'Nothing works in this browser', instead, offer them an
alternativethatdoesnotrequirethefancyscript.

Changingtheposition
iCab2doesnotsupportpositioning.
OmniWeb4.2doesnotunderstandrelativepositioningandmakesmistakeswithabsolutepositioning.
WebTVcanonlychangehorizontalposition,notvertical.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

73/223

5/30/2015

JavaScripttutorial

Cluebrowsersometimesonlyallowshorizontalpositiontobechanged,andsometimesdoesnotallowpositions
tobechangedatall.

Youcanadjustthepositionbyusing leftor topthesamewayasweused visibilityabove,and


thenspecifyingthepositioninpixels.(Note,thistopisnotthesameasthe window.topmentionedin
thesectiononframesetreferences.)Inordertoretrievethe leftand toppropertiesasIamabout
todo,the leftand topstylesmusthavebeensetusingtheinlinestylesyntax,orbybeinginitially
setwithJavaScript.
When a strict doctype is used, many browsers require you to use the correct units (20px, not 20),
but many older browsers do not understand this, such as Opera 5 ( 'top' only), layers browsers,
WebTVetc.Thereisnodirectwaytodetectifabrowserunderstandstheunitsornot,sinceitmay
acceptthevalues,evenifitdoesnotsupportthem.Forthisreason,Idetect document.childNodes,
as this is one of the basic requirements for proper DOM support. DOM style requires units to be
used,andthereforeallbrowsersthatunderstandDOMalsounderstandtheunits.
Inthisexample, leftand top are both initially set to 10px using an inline style attribute. The code
will check if it needs to use a '.style' reference, and if so, it will change the reference the style
objectinstead,allowingthestyletobechangedforallversionsinjustonestep.Itwillthenretrieve
thecurrentpositions,addonthenewamountandsetthatasthenewposition.Whenitretrievesthe
current value, it uses parseInt, because the value may contains the units, depending on the
browser.
<divstyle="position:absolute;left:10px;top:10px;"...
......
varnoPx=document.childNodes?'px':0;
if(myReference.style){myReference=myReference.style;}
myReference.left=(parseInt(myReference.left)+10)+noPx;
myReference.top=(parseInt(myReference.top)+20)+noPx;

Thedivwillmove10pixelsdown,and20pixelstotheright.Itwillnowbeatcoordstop:30pxleft:
20px
Testithere:movethiselement.
Thiscanquiteeasilybeusedalongwithatimerwhichfireseveryfewmillisecondsandrepositionsa
positionedelementaccordingtothescrollingoffsettomaketheelementappearstaticonthescreen
( position:fixed;ispreferred,however).

Changingthebackgroundcolour

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

74/223

5/30/2015

JavaScripttutorial

OldGeckobrowsershavebugsthatareeasilyavoided.SeemyGeckoenginemouseoutbugdocumentation.
WebTVandOmniWeb4.2donotallowyoutochangethebackgroundcolour.

Itwouldbenicetochangethetextcolouraswell,butlayersbrowserscannotdothat.Tochangethe
backgroundcolour,therearethreeways.Layersbrowsersuse bgColor.DOMandproprietaryDOM
browsers can use background and backgroundColor. Opera 5.x can only change the background
style, all the others (including Opera 6+) can change both. 'myReference' must be obtained as
above. Note some versions of Opera 5 will only change the background colour if it has already
beenexplicitlydefined,andisnotinherited.
Warning, Opera 77.1 will return the string 'Warning' if you check for bgColor so if you are
checkingforwhichonetochange,youmustputthatsyntaxlast.
if(myReference.style){myReference=myReference.style;}
if(myReference.background){
//supportedbymostbrowsers
//likeGeckobrowsersandtheIEseries
myReference.background='#00ff00';
}elseif(myReference.backgroundColor){
//supportedbymostbrowsers
myReference.backgroundColor='#00ff00';
}elseif(myReference.bgColor){
//usedbylayersbrowsers
myReference.bgColor='#00ff00';
}else{
//FAILURE,thereisnowaytochangethebackgroundcolour
}

Assettingthewrongonewillnotcauseanyproblems,thiscanbeeasilysimplifiedto:
if(myReference.style){myReference=myReference.style;}
myReference.bgColor='#00ff00';
myReference.background='#00ff00';
myReference.backgroundColor='#00ff00';

Testithere:changethebackgroundcolourofthiselement.

Changingthezindex
iCab2doesnotsupportpositioningsocannotsupportzindex.
WebTVandCluebrowserdonotsupportzindex.

The zindex of positioned elements defines what order they should be stacked above each other.
The zindex should be a positive integer. The higher the zindex, the more positioned elements it
willbestackedontopof.Twoelementsmustnotbegiventhesamezindex.Toreadthe zindexof
apositionedelement,itmustbealreadydefinedusingtheinlinestylesyntax.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

75/223

5/30/2015

JavaScripttutorial

if(myReference.style){myReference=myReference.style;}
myReference.zIndex=100;

Testithere:Clickthelinkineachpositionedelementtoraiseits zindexabovethe zindex of the


otherelement.
Element1.
Element2.
Increaseitszindex.
Increaseitszindex.

Changingtheclipping
Opera6,Konqueror3.0,OmniWeb4.2,WebTV,NetFront3.3,iCab2andTkhtmlHv3donotsupportclipping
(iCab2doesnotsupportpositioningsocannotsupportclip).
InternetExplorer7doesnotfollowcurrentstandardswhenusing"standardsrenderingmode",andneedsspecial
attention,asshownbelow.
InOpera77.1(fixedinlaterreleases),thebackgroundcolourshowsthroughtheclippingonclippedelements.
Thesolutionistocliponeelementandholdacolouredelementinsideit.
AlthoughEscape4.xsupportsthestyleobject,itdoesnotsupportthestyle.clipsyntax.

Clippingcanonlybeusedonabsolutelypositionedelements.
Thistechniqueisusuallyusedformessagescrollers.Inbrowsersthatdonotsupportclipping,itis
possibletoprovidethemwithaniframesothatthecontentsofthatcanbescrolled.Pleaseseemy
scrollerexampleforamoredetailedexplainationofwhatclippingisandhowitworks.
Youmaywanttocheckthattheelementcanbeclipped(thereisnorealneedto,asbrowsersthat
do not understand it will just ignore you). This is very difficult as browsers like Opera 6 will give
'rect()' if asked for the clip style but have no way of using it. I have found no good way to do this.
ThebestIcandoistocheckif myReference.innerHTMLand myReference.clip are supported. I do
not know of any browsers that should have problems with this as they support innerHTML but not
clipping,butdogive'rect()'ifaskedfortheclipstyle.However,settingtheclippinginbrowsersthat
donotsupportitwillnotcauseerrors,itjusthasnoeffect.AsEscapesupportsthestyleobjectbut
doesnotsupportthestyle.clipsyntax,itisimportanttomakesureitusestheclipobjectinstead,so
thisisputfirst.
if(myReference.clip){
myReference.clip.left=0;
myReference.clip.top=0;
myReference.clip.right=10;
myReference.clip.bottom=10;
}elseif(myReference.style){
//toprightbottomleft
myReference.style.clip='rect(0px,10px,10px,0px)';
}else{
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

76/223

5/30/2015

JavaScripttutorial

//FAILURE,nothingworks
}

Test it here: select a clipping rectangle for the positioned element below. The background shows
throughwherevertheclippinghidespartsoftheelement:
rect(0px,250px,20px,0px)
rect(10px,250px,30px,0px)
rect(20px,250px,40px,0px)
BackgroundBackgroundBackground
Lineoneofthepositionedelement.Yourbrowserdoesnotsupportclipping.
BackgroundBackgroundBackground

NotethatalthoughtheCSS2.1standardrequiresbrowserstosupportrect()withcommasbetween
parameters, Internet Explorer 6 and 7 do not apply the rule if it contains commas, if the page's
DOCTYPE triggers "standards rendering mode". (This is due to a mistake in the CSS 2.0
specification.)Notethatthisonlyapplieswhenthestyleissetwithastylesheetifsetwithascript,it
willworkwiththecorrectsyntax.Toavoidthisproblem,simplysetthestyletwiceinthestylesheet,
oncewithcommas,andoncewithout.Browserswillusewhicheverversiontheyunderstand.

Changingthesize
WebTVcannotchangeelementsize.
Escape/Evo5willproduceerrorsbecauseIcheckfordocument.childNodes.
ICEbrowserwillchangeelementsize,butmaynotshowanychangeuntilthebrowserwindowisresized.
iCab2producesstrangeoverlapswhenchangingsizebecauseitdoesnotsupportpositioning.
InCluebrowser,theelementmayjustdisappear.

Layers browsers expect you to use the resizeTo method, while a few browsers expect you to
changethepixelWidthandpixelHeightpropertiesofthestyleobject.Allotherbrowsersexpectyou
to change the height and width properties of the syle object. You can set these last two anyway,
reguardlessofwhatthebrowserexects,becausethebrowserwilljustignorethem.Somebrowsers
will not rearrange the contents of the element to suit the new size. In layers browsers, this is
equivalenttosetting clip.bottomand clip.right, which are the properties that should be read to
getthecurrentsize.Althoughthisisnotaccurateasthelayercouldextendbeyondeitherofthese
clips,itisthebestthatlayersbrowsersprovide.Tochangeonlywidthorheightinlayersbrowsers,
youmustchangetherightorbottompropertiesoftheclipobject.
Some browsers will not shrink the element smaller than its contents. Some will clip the contents to
thenewsize.Somewillrearrangethecontentstofitthenewsize.Somewillshrinktheelementbut
leavethecontentsastheywere,stillvisible.
As with element position, some older browsers do not like to have the units (px) written after the
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

77/223

5/30/2015

JavaScripttutorial

size, while newer browsers require it for strict doctypes. Again, a quick detect sorts the good
browsersfromthenotsogood.
if(myReference.style){myReference=myReference.style;}
if(myReference.resizeTo){
myReference.resizeTo(newWidth,newHeight);
}
varnoPx=document.childNodes?'px':0;
myReference.width=newWidth+noPx;
myReference.pixelWidth=newWidth;
myReference.height=newHeight+noPx;
myReference.pixelHeight=newHeight;

Tryithere:selectanewsizefortheelement:
20x20
30x40
backto50x50
Test
Test

Rewritingthecontents
Opera6andOmniWeb4.2cannotrewritethecontentsofpositionedelements.
WebTVmayjustcrash.
Layersbrowserscanonlyrewritethecontentsofabsolutelypositionedelements.
Netscape4losesstyleinpositionedelementswhentheircontentsarerewritten.
InCluebrowser,theelementmayjustdisappear,alongwiththedocumentbelowit.

This functionality has been completely replaced in the W3C DOM, using various methods. The old
DHTML approach should not be used in any new Web pages, and is best removed and replaced
with DOM functionality (or innerHTML, which has now been standardised, and supported by all
currentbrowsers).Itisretainedheretoallowittoberecognised.
Inthefollowingexample,myReferenceisobtainedasbefore.Mostbrowsersprovidethe innerHTML
property,whichyoucanrewritewiththenewHTML.Layersbrowsersallowyoutousethemethods
open, write and close on the document object of the layer. Some browsers (like Opera) will also

provide the document property of the positioned element, but that is a reference back to the main
document.Rewritingthatwillcausenoendofproblemssowemustcheckthatthisisnotthecase
first.
if(typeof(myReference.innerHTML)!='undefined'){
//usedbyallcurrentbrowsers
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

78/223

5/30/2015

JavaScripttutorial

myReference.innerHTML='some<b>new</b>content';
}elseif(myReference.document&&myReference.document!=window.document){
//usedbylayersbrowsers
myReference.document.open();
myReference.document.write('some<b>new</b>content');
myReference.document.close();
}

It is also possible to extend support to Opera 5 and 6 if needed, by providing an iframe (which
shouldbegivenanameattribute),checkingifithasloaded,thenrewritingitscontents:
if(typeof(myReference.innerHTML)!='undefined'){
//usedbyallcurrentbrowsers
myReference.innerHTML='some<b>new</b>content';
}elseif(myReference.document&&myReference.document!=window.document){
//usedbylayersbrowsers
myReference.document.open();
myReference.document.write('some<b>new</b>content');
myReference.document.close();
}elseif(window.frames&&window.frames.length&&window.frames['nameOfIframe']){
//usedbybrowserslikeOpera6
myReference=window.frames['nameOfIframe'].window;
myReference.document.open();
myReference.document.write('some<b>new</b>content');
myReference.document.close();
}

Testithere:rewritethecontentsofthepositionedelementbelow(theOpera56workaroundisnot
included).
Thisisthepositionedelement.Thecontentshavenotyetbeenrewritten.

Creatingnewpositionedelements
Opera6andOmniWeb4.2,NetFront3.2andCluebrowsercannotcreatepositionedelementsoncethepage
hasloaded.
WebTVwillreplacetheentirecontentoftheparentelementasitincorrectyalwaysreadsinnerHTMLasablank
string.
iCab2cannotpositiontheelementandshouldcreatethemasunpositionedelements.

This functionality has been completely replaced in the W3C DOM, using createElement. The old
DHTML approach should not be used in any new Web pages, and is best removed and replaced
withDOMfunctionality.Itisretainedheretoallowittoberecognised.
As the page is loading, we can create new positioned elements using document.write, or just
regular HTML. Once the page has loaded, 5 th generation browsers allow us to create any new
elements, but some 4 th generation browsers also allow us to create elements after the page has
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

79/223

5/30/2015

JavaScripttutorial

loaded.
Mostbrowsersallowthe innerHTMLpropertyofanelementtobemanipulated(theInternetExplorer
series also provide insertAdjacentHTML, but most other DOM browsers do not include it). Layers
browsers(withtheexceptionofOmniweb4.2)provideaconstructorthatcreatesnewemptylayers,
whose contents can then be written. Before trying to use this constructor, we must check it exists.
Although OmniWeb 4.2 provides the Layer constructor, using it causes errors, so I use
document.classestoisolateOmniWeb4.2andprotectitfromthescript.

Withthelayerssyntax,thenewlayerisenteredintothelayerscollectionsusingitsnumericalindex
butisnotenteredintothecollectionwithaname,sowecanadditthereourselvesifwewantto.We
also have to specify a nominal maximum width. It will be positioned differently in different layers
browsers,sowehavetopositionitexactlyourselves.Itwillbehidden,sowemustshowit.Withthe
innerHTML syntax, we can create ANY new content, but to be cross browser, I will create a

positionedelement.
Opera 77.1 incorrectly strips all existing tags in the parent element of their style attributes when
reading innerHTML, producing an odd effect. To combat this, I use insertAdjacentHTML if the
browserprovidesit,asthisdoesnotproduceproblems.
Thisfirstexamplewillcreateanewpositionedelementasachildofthedocument.
if(document.layers&&window.Layer&&document.classes){
//createalayer350pxwide
document.layers['newName']=newLayer(350);
//writeitscontent
document.layers['newName'].document.open();
document.layers['newName'].document.write('newcontent');
document.layers['newName'].document.close();
//styleit
document.layers['newName'].left=0;
document.layers['newName'].top=0;
document.layers['newName'].visibility='show';
}elseif(document.body){
vartheString='<divstyle="position:absolute;left:0px;top:0px;'+
'width:350px;">newcontent</div>';
if(document.body.insertAdjacentHTML){
document.body.insertAdjacentHTML('beforeEnd',theString);
}elseif(typeof(document.body.innerHTML)!='undefined'){
document.body.innerHTML+=theString;
}else{
//FAILURE,nothingworks
}
}else{
//FAILURE,nothingworks
}

Th next example will create a new positioned element as a child of an existing positioned element
(myReferenceisobtainedasabove):

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

80/223

5/30/2015

JavaScripttutorial

if(document.layers&&window.Layer&&document.classes){
//createalayer350pxwide
document.layers['newName']=newLayer(350,myReference);
//writeitscontent
document.layers['newName'].document.open();
document.layers['newName'].document.write('newcontent');
document.layers['newName'].document.close();
//styleit
document.layers['newName'].left=0;
document.layers['newName'].top=0;
document.layers['newName'].visibility='show';
}else{
vartheString='<divstyle="position:absolute;left:0px;top:0px;'+
'width:350px;">newcontent</div>';
if(myReference.insertAdjacentHTML){
myReference.insertAdjacentHTML('beforeEnd',theString);
}elseif(typeof(myReference.innerHTML)!='undefined'){
myReference.innerHTML+=theString;
}else{
//FAILURE,nothingworks
}
}

Test it here: create a new element (new elements will alternate in colour and will be slightly offset
fromeachothertomakeitmoreeasytoseewhatishappening).
Thisistheoriginalcontentoftheexistingpositionedelement.Itwillnotbechanged.

Changingthebackgroundcolourofthewholedocument
Opera5,OmniWeb4.2andEscape/Evocannotchangethebackgroundcolourofthedocument(Escapewill
changethebackgroundcolour,butonlyattheveryendofthedocument,afterallofthecontent).
Opera6andCluebrowserwillonlychangethecolourbehindthecontent,theoriginalbackgroundcolourwill
remainwherethecontentissmallerthanthewindow.
NetFront3.3willallowyoutosetthecolourto'',butwillnotshowanychangeuntilyouscroll.

Therearethreewaystochangethebackgroundcolour.Oldbrowsersusethe bgColorpropertyto
stylethebackgroundoftheentiredocument.Incurrentbrowsers,theHTMLelementandtheBODY
element are rendered separately, by default with the HTML element taking up just a few pixels
outsidetheBODY.Theyareabletobestyledseparately,sotochangethedocumentbackground,
both of them need to be changed. The HTML element is referenced in these browsers as
document.documentElement,andtheBODYisreferencedasdocument.body.

Settingthewrongonewillnotcauseerrors(aslongastheyexist),soIsetallofthematthesame
time.
if(document.documentElement&&document.documentElement.style){
document.documentElement.style.backgroundColor='red';}
if(document.body&&document.body.style){
document.body.style.backgroundColor='red';}
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

81/223

5/30/2015

JavaScripttutorial

document.bgColor='red';

Testithere:changethebackgroundcolourofthisdocumentto:
#f6f6f6
#d2cbff
#777777
''(returnstodefault)notallowedbysomeoldbrowsers

Changingthedisplaystyleofanyelement
WebTVdoesnotsupportthedisplaystyle.
OlderbrowserssuchasNetscape4,Escape4,Opera6,OmniWeb4.2,NetFront3.2andCluebrowsersupport
thedisplay:nonestyle,butdonotallowJavaScripttochangeit.Seetheguidelinesbelow.
iCab 2 sometimes makes mistakes with rendering when changing the display style and interprets 'block' as
'returntodefault'.
Manydevicebrowserswillignorethedisplaystylewheninsmallscreenreformattingmode.
InternetExplorer4onWindowsdoesnotunderstandinlinedisplay.
Escape4doesactuallyallowyoutochangethedisplaystyle(onlyblock,inlineandnoneaccepted)usingthe
styleobject,butonlyonlayersandilayers.Sincethebestuseofthedisplaystyleisforunpositionedelements,
andconsideringthatchangingfromnonetoinlineorblockhasnoeffectinEscapeuntilthewindowisresized,i
donotrecommendevenattemptingit.

Allcurrentbrowserssupportthedisplaystyle,andcanbetoldtodisplayanyelementlikeaninline
element ( display:inline;), like a block element ( display:block;), or not to display it at
all( display:none;). Most also support many other display styles. However, some older browsers do
not allow the display style to be changed with JavaScript, so if the display style is initially set to
'none'andthenyouattempttosetitto'block'or'',thedisplaystylewillnotactuallychange,andthe
contentwillremaininvisible.ThisisalsothecaseforbrowserswhereJavaScriptisdisabled.
Forthisreason,itisbesttochangethedisplaystylewithscriptafterthepagehasloaded.Browsers
thatdonotunderstanditwilljustignoreyou,andallowtheusertoviewthecontent.Itmaynotbeas
neatasbeingabletoshowandhideit,butatleasttheywillbeabletoseeit.
Thedisplaystyleisdifferentfromthevisibilitystyle.Settingthevisibilitystyleto'hidden'willhidethe
element from view, but will leave the space for it. Setting the display style to 'none' will remove it
fromviewandwillrearrangethecontentsofthepagetofillthehole.Thiscanmakethefeaturevery
usefulformenusystems,aswithverysimpleprogramming,thebrowsercantakecareofallthere
arrangingtomakethepagelookniceagain.
Browsers that allow elements to have their display style changed will all use
document.getElementByIdor document.all,not document.layers. This makes life slightly easier. Of

course, it is nice to be able to tell users that this will not work in their browser, so we will want to
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

82/223

5/30/2015

JavaScripttutorial

detectifthebrowserallowsustochangethedisplaystylefirst.Todothis,wemustinitiallysetthe
display style using inline style sheets, with it set the the element's default display ( 'inline' for
elementslikespans,and'block'forelementssuchasparagraphsorDIV).

TheHTML
Inthisexample,Iwillhaveaspaninsideaparagraph:
<p>Thisisaparagraph.
<spanstyle="display:inline;"id="aUniqueId">Thisisaspan
withintheparagraphwhosedisplaystylehasbeensetto
'inline'usinganinlinestylesheet.</span>Thisisanother
sentenceintheparagraph,butnotinthespan.<p>

TheJavaScript
functionchangeDisplay(elementId,setTo){
vartheElement;
if(document.getElementById){
//DOM
theElement=document.getElementById(elementId);
}elseif(document.all){
//ProprietaryDOM
theElement=document.all[elementId];
}
if(!theElement){
/*Thepagehasnotloaded,orthebrowserclaimsto
supportdocument.getElementByIdordocument.allbut
cannotactuallyuseeither*/
return;
}
//Referencethestyle...
if(theElement.style){theElement=theElement.style;}
if(typeof(theElement.display)=='undefined'){
//Thebrowserdoesnotallowustochangethedisplaystyle
//Alertsomethingsensible(notwhatIhavehere...)
window.alert('Yourbrowserdoesnotsupportthis');
return;
}
//Changethedisplaystyle
theElement.display=setTo;
}

Tryithere:selectadisplaystyleforthespanintheparagraphbelow:
''(default)
'inline'
'block'
'none'
This is a paragraph. This is a span within the paragraph whose display style has been set to
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

83/223

5/30/2015

JavaScripttutorial

'inline'usinganinlinestylesheet.Thisisanothersentenceintheparagraph,butnotinthespan.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

84/223

5/30/2015

JavaScripttutorial

Elementcontents

TheDOMprovidesaneasywaytoreferenceallelements,nomatterwheretheyareinadocument.
However,itispossibletoreferencemanyelementsinawaythatworksinDOMbrowsers,andolder
browsers. This can be useful if you need your scripts to work in browsers like Netscape 4, even
thoughtheyarenotusedanymore.
Layers browsers like Netscape 4 are different to all other browsers. They give each positioned
element a new document object. All forms, images, links and child layers inside that layer, must be
referenced through this new document object. So instead of document.formname, it becomes
myReference.document.formname,etc.

Howtoreferenceanythinginagenericway
MacroMedia first came up with a generic referenceall function for use in their 'wysiwyg' page
editors.Itcouldreferenceimagesandformsandalltypesoflayers.Thiswouldlookforanyobject
with a name or id that matched the required name. Inspired by that, I have written my own
(completelyseparately)thatcouldalsoreferenceafewotherthings.Itisalittlelargerasaresult.
Theonlythingitcannotreferenceisalinkobject,becauseduetorestrictionsinolderbrowsers,link
objects are only accessible using their numerical index. Also, unlike anchor objects, the name
attribute is not accessible with link objects, even if they have one. If referred to using the anchors
collection, the link properties are not available, although the name attribute is. By checking every
anchor to see if its name matches the requested name, I can reference the correct anchor.
However,Icannotreferencethelink.
Notethatifthenamereferstoinputsinaformthatsharethesamename,thisfunctionwillreturnthe
collectionofinputssharingthatname.
functionMWJ_findObj(oName,oFrame,oDoc){
/*ifnotworkingonalayer,documentshouldbesettothe
documentoftheworkingframe
iftheworkingframeisnotset,usethewindowobject
ofthecurrentdocument
WARNING:crossframescriptingwillcauseerrorsif
yourpageisinaframesetfromadifferentdomain*/
if(!oDoc){if(oFrame){oDoc=oFrame.document;}else{oDoc=window.document;}}
//checkforimages,forms,layers
if(oDoc[oName]){returnoDoc[oName];}
//checkforpDOMlayers
if(oDoc.all&&oDoc.all[oName]){returnoDoc.all[oName];}
//checkforDOMlayers
if(oDoc.getElementById&&oDoc.getElementById(oName)){
returnoDoc.getElementById(oName);}
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

85/223

5/30/2015

JavaScripttutorial

//checkforformelements
for(varx=0;x<oDoc.forms.length;x++){
if(oDoc.forms[x][oName]){returnoDoc.forms[x][oName];}}
//checkforanchorelements
//NOTE:onlyanchorpropertieswillbeavailable,
//NOTlinkproperties(inlayersbrowsers)
for(varx=0;x<oDoc.anchors.length;x++){
if(oDoc.anchors[x].name==oName){
returnoDoc.anchors[x];}}
//checkforanyoftheabovewithinalayerinlayersbrowsers
for(varx=0;document.layers&&x<oDoc.layers.length;x++){
vartheOb=MWJ_findObj(oName,null,oDoc.layers[x].document);
if(theOb){returntheOb;}}
//checkforframes,variablesorfunctions
if(!oFrame&&window[oName]){returnwindow[oName];}
if(oFrame&&oFrame[oName]){returnoFrame[oName];}
//ifcheckingthroughframes,checkforanyoftheabovewithin
//eachchildframe
for(varx=0;oFrame&&oFrame.frames&&x<oFrame.frames.length;x++){
vartheOb=MWJ_findObj(oName,oFrame.frames[x],oFrame.frames[x].document);if(
theOb){returntheOb;}}
returnnull;
}

withoutcomments,thisbecomes:
functionMWJ_findObj(oName,oFrame,oDoc){
if(!oDoc){if(oFrame){oDoc=oFrame.document;}else{oDoc=window.document;}}
if(oDoc[oName]){returnoDoc[oName];}if(oDoc.all&&oDoc.all[oName]){return
oDoc.all[oName];}
if(oDoc.getElementById&&oDoc.getElementById(oName)){return
oDoc.getElementById(oName);}
for(varx=0;x<oDoc.forms.length;x++){if(oDoc.forms[x][oName]){return
oDoc.forms[x][oName];}}
for(varx=0;x<oDoc.anchors.length;x++){if(oDoc.anchors[x].name==oName){
returnoDoc.anchors[x];}}
for(varx=0;document.layers&&x<oDoc.layers.length;x++){
vartheOb=MWJ_findObj(oName,null,oDoc.layers[x].document);if(theOb){return
theOb;}}
if(!oFrame&&window[oName]){returnwindow[oName];}if(oFrame&&oFrame[oName]){
returnoFrame[oName];}
for(varx=0;oFrame&&oFrame.frames&&x<oFrame.frames.length;x++){
vartheOb=MWJ_findObj(oName,oFrame.frames[x],oFrame.frames[x].document);if(
theOb){returntheOb;}}
returnnull;
}

Thisfunctioncanbecalledintwowaystoreferenceaniteminthecurrentdocument:
vartheOb=MWJ_findObj(NameOrId);

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

86/223

5/30/2015

JavaScripttutorial

To reference an item in any other document in a frameset, you can choose how high in the frame
structuretostart.Rememberthatifusing'top',someoneelsemayloadyourpageintheirframeset,
andthiswillproduceanerror.
vartheOb=MWJ_findObj(NameOrId,ReferenceToTopMostFrameToSearch);

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

87/223

5/30/2015

JavaScripttutorial

Windowsizeandscrolling

Findingthesizeofthebrowserwindow
Cluebrowsercanonlyworkoutwindowwidth.
Tkhtml Hv3 has the body/documentElement clientHeight/Width values reversed versions before September
2007alsodonotsupportinnerHeight/Width,sotheycannotworkwiththisscript.

Therearesomeconstantsavailablethatgivethedocumentareaofthewindowthatisavailablefor
writingto.Thesewillnotbeavailableuntilafterthedocumenthasloadedandthemethodusedfor
referencingthemisbrowserspecific.Theavailableconstantsare:
window.innerHeight/Width

Providedbymostbrowsers,butnotInternetExplorer8,andeveninInternetExplorer9+,itis
notavailableinquirksmode.
document.body.clientHeight/Width

Providedbymanybrowsers,includingInternetExplorer.
document.documentElement.
clientHeight/Width

ProvidedbymostDOMbrowsers,includingInternetExplorer.
This is a little messy because the clientHeight/Width properties can mean different things in
different browsers, and even different things in the same browser, depending on whether the
document type declaration triggers the browser's strict mode or quirks mode. In some cases, they
refertothedimensionsofthewindow,andsometimestheyrefertothedimensionsofthecontentsof
thedocument.Thetablebelowshowswhatthepropertiesmeanindifferentbrowsers,anddifferent
modes:
Propertiesandwhattheyrelateto
Browser

window.
innerHeight

document.

document.

body.

documentElement.

clientHeight clientHeight

Opera9.5+strict window

document

window

Opera9.5+quirks window

window

document

Opera79.2

window

window

document

Opera6

window

window

N/A

Mozillastrict

window

document

window

Mozillaquirks

window

window

document

NewerKHTML

window

document

window

OlderKHTML

window

document

document

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

88/223

5/30/2015

JavaScripttutorial

Chrome/Safari4+ window

document

window

Safari3

window

document

document

iCab3

window

document

document

iCab2

window

window

N/A

IE9+strict

window

document

window

IE68strict

N/A

document

window

IE5+quirks

N/A

window

IE4

N/A

window

N/A

ICEbrowser

window

window

document

TkhtmlHv3

window

window

document

Netscape4

window

N/A

N/A

Asyoucansee,thebrowsersseemtohavesettledonatleastonereliableproperty innerHeight.
InternetExplorertookalongtimetomakeupitsmind,anditsinfluencemeansthatotherbrowsers
changetheir clientHeight behaviour in different versions in order to match it. For now, almost all
browsersprovide window.innerHeight/Width so that can be used. The other values may swap the
valuesaroundwhenthebrowsersareinstrict/quirksmode.Fortunately,theonlybrowserthatdoes
notprovideinnerHeight,InternetExplorer8(and9+inquirksmode),gives0inquirksmodeforthe
root element's clientHeight. This means that if we see a value on the documentElement's
properties,andthebrowserdoesnotprovidethepropertiesonthe windowobject,wecanassumeit
isInternetExplorer68instrictmode.
ThemostaccuratemethodIcouldcomeupwithusesthefollowingalgorithm:
1. Ifwindow.innerHeight/Widthisprovided,thatisfullytrustworthy,usethat(Hooray!).
2. Elseifdocument.documentElement.clientHeight/Widthisprovidedandeitheroneisgreaterthan
0,usethat.
3. Elseusedocument.body.clientHeight/Width.
ThisalgorithmwillfailwithIE68in'standardscompliantmode'andallversionsinquirksmodeifthe
windowisshrunkto0pxby0px.Thisisonlypossiblewhentheuseractivelyshrinksthewindowto
hidethepagewithinit.Eventhen,itwilljustgivetheheightofthedocumentinstead,soitshouldnot
beaproblem.Thefollowingcodeperformsthealgorithmasdescribed.
functionalertSize(){
varmyWidth=0,myHeight=0;
if(typeof(window.innerWidth)=='number'){
//NonIE
myWidth=window.innerWidth;
myHeight=window.innerHeight;
}elseif(document.documentElement&&(document.documentElement.clientWidth||
document.documentElement.clientHeight)){
//IE6+in'standardscompliantmode'
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

89/223

5/30/2015

JavaScripttutorial

myWidth=document.documentElement.clientWidth;
myHeight=document.documentElement.clientHeight;
}elseif(document.body&&(document.body.clientWidth||document.body.clientHeight))
{
//IE4compatible
myWidth=document.body.clientWidth;
myHeight=document.body.clientHeight;
}
window.alert('Width='+myWidth);
window.alert('Height='+myHeight);
}

Testithere:gettheinnerdimensionsofthiswindow.
Notethatbrowsersmaytakethewidtheitherinsideoroutsidethescrollbar(ifthereisone).Inmost
current browsers, you can ensure that your page triggers standards mode, then use
documentElement.clientHeight to get the height inside any scrollbar. window.innerHeight can be

used to get the height outside any scrollbar, but that is not possible in Internet Explorer 8. It is a
littlemessy,andifyoudoneedtomakethedistinction,youwillneedtodecidewhichbrowsersare
likelytobeimportant.Ifyouneedtoreliablygetthedimensionsinsidethescrollbar,includinginall
currentbrowsers(notIE6),youcancreateafixedpositionelementwithtop,right,bottomandleft
allsetto0,andmeasureitsoffsetHeightandoffsetWidth.

Findinghowfarthewindowhasbeenscrolled
OmniWeb4.2,NetFront3.3andCluebrowserdonotprovideanywaytodothis.
SafariandOmniWeb4.5+havebugsthatdonotaffectthisscriptseebelow.

When trying to produce document effects like falling snow, or more serious things like menus that
remaininthesameplacerelativetothebrowserwindowwhentheuserscrolls,itisessentialtobe
abletoobtainthescrollingoffsetsinboththehorizontalandverticaldirection.
Therearealsothreewaystofindthisout,butitiseasierthanfindingthesizeofthewindow.Most
browsers provide window.pageXOffset/pageYOffset. These are completely reliable. Once again,
Internet Explorer 8 (and 9+ in quirks mode) is the odd one out, as it does not provide these
properties.InternetExplorerandsomeotherbrowserswillprovide document.body.scrollLeft/Top.
Instrictmode,IE6+andafewotherbrowsers,providedocument.documentElement.scrollLeft/Top.
If

the

scrollLeft/Top

properties

are

provided

on

either

the

document.body

or

document.documentElement, they are reliable in everything except older Safari and OmniWeb 4.5+,

which return 8 if the scrolling is 0, but get all other scrolling offsets correct. However, as they
correctlyprovidewindow.pageXOffset/pageYOffset,thisscriptwillnothaveanyproblems.
Thefollowingscriptwillobtainthescrollingoffsets.
functiongetScrollXY(){
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

90/223

5/30/2015

JavaScripttutorial

varscrOfX=0,scrOfY=0;
if(typeof(window.pageYOffset)=='number'){
//Netscapecompliant
scrOfY=window.pageYOffset;
scrOfX=window.pageXOffset;
}elseif(document.body&&(document.body.scrollLeft||document.body.scrollTop)){
//DOMcompliant
scrOfY=document.body.scrollTop;
scrOfX=document.body.scrollLeft;
}elseif(document.documentElement&&(document.documentElement.scrollLeft||
document.documentElement.scrollTop)){
//IE6standardscompliantmode
scrOfY=document.documentElement.scrollTop;
scrOfX=document.documentElement.scrollLeft;
}
return[scrOfX,scrOfY];
}

Testithere:getthescrollingoffsets.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

91/223

5/30/2015

JavaScripttutorial

Eventinformation

As with DHTML, this is always browser specific. When an event is triggered, the browser keeps
someinformationabouttheeventthatwecanuse.Therearetwowaysthatbrowsersusetoallow
ustoaccessthisinformation.DOMcompatiblebrowsers(includingInternetExplorer9+instandards
mode) pass the event information to the event handler function as the first argument. Some older
browsersalsousethisversion.
Internet Explorer and a few other browsers store the event information in an event register, which
wecanaccessbywriting'window.event'.InternetExplorerversionsthatsupporttheDOMapproach
disabletheirsupportforitinquirksmode,soevenifolderIEversionsdonotneedtobecateredfor,
scripts that need to run in quirks mode will still need to allow the IE approach. This tutorial covers
bothapproaches,andwillworknomatterwhichIEversionisused,andnomatterwhichmodethe
documentisrenderedin.Forpracticalcases,Irecommendcontinuingtousethisapproach.
Wealsohavetotellthebrowserwhatobjectsshoulddetectwhateventsandwealsohavetotellit
whattodowhenthatobjectdetectsthatevent.
Althoughitisnolongerused,youmaywantthescripttoworkinNetscape4,sinceitiscapableof
doing this. In practical use, I recommend against adding Netscape 4 support, and include the
Netscape4workaroundheresothatyoucanlearntorecogniseit,andpossiblyremoveitfromolder
scripts.Withpositionedelementsandthedocumentitself,Netscape4andEscape4willneedtobe
toldtocapturetheeventsfirst.Someotherbrowsers(suchasMozilla/Firefox/Netscape6+)mayalso
provide the methods, but they do not actually do anything. Some others provide them but do not
know how to use them, so you should check for the specific Event type as well. For example the
simplestcodeusedtolistenforakeyupeventwouldjustbethis:
document.onkeyup=alertkey;
//wherealertKeyisafunctionthatwillhandletheevent

CodedesignedtoworkwithNetscape4willusethisinstead:
//OnlyNetscape4andEscape4needthisfirstline
if(document.captureEvents&&Event.KEYUP){document.captureEvents(Event.KEYUP);}
document.onkeyup=alertkey;
//wherealertKeyisafunctionthatwillhandletheevent

Problems can arise if one element detects an event where a parent element also detects it. For
example, if the document is told to detect when the user presses a key, and a text box in the
document is also told to detect when the user presses a key, when the user presses a key in the
textbox,shouldthedocumentreactorthetextbox?Orboth?Andinwhatorder?Somebrowsers
willusecapturingtosaywhichelement(s)shoulddetecttheeventandinwhatorder,whilesomewill
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

92/223

5/30/2015

JavaScripttutorial

use bubbling, and many will do neither. I will not describe either of these here as they are far
beyondthescopeofthisstageofthetutorial.IwillcoverthemlaterintheDOMeventspartofthe
tutorial.
For a full list of events that elements can detect crossbrowser, see the section on TheJavaScript
object' subsection 'Standard document components. To see what events can be captured using
captureEvents,seethesamesection,subsection'window.Event.Toseewhatinformationispassed

aboutevents,seethesamesection,subsection'Eventobjects.
Thefollowingexamplesattempttosolveasmanyproblemsaspossible.

Detectingthekeyupeventoverthepageandextractingthekeycode.
Variousbrowsersmayrestrictwhichnonprintingkeysfirewhatevents.Chrome/Safari3.1+inparticularwillnot
fire the keypress event for any nonprinting keys, which in many cases (such as the Esc key) makes it
incompatiblewithallotherbrowsers.
Konqueror3.3,Safari1.0andNetFront3.3canonlydetectkeyeventsontextboxes.
iCab3onlypasseskeycodeinformationininputboxes.
Blazer(aversionofNetFront)detectslimitedkeyevents(duetothekeyboardhandlingonthedevice)andreturns
nonsensekeycodes(suchas1987304).
WebTVandEscape4canonlydetectkeyeventsontextboxes,andmaybealittleunreliable.
OmniWeb4.2andOpera5forMacdonotpasskeycodeinformation.
Netscape4onLinuxdoesnotdetectanykeyeventsproperly.
CluebrowserandTkhtmlHv3cannotdetectkeyevents.
IamunsureofthecapabilitiesofNetBox,iPanelMicroBrowserandOpenTVhere.

Notethatbrowsersmaygivedifferentkeycodenumbersforkeypadkeys.Also,manybrowsersdo
not give key code numbers for control keys (like F1, delete, backspace, alt, arrow keys etc.).
Netscape4givesadifferentkeycodefortheletter'a'toallotherbrowsers.Itmaybemoreusefulto
useString.fromCharCode(key_code)whichconvertsthekeycodebacktoitsrelevantkey(like'G',for
example).
//first,tellthebrowserstoreacttotheevent
if(document.captureEvents&&Event.KEYUP){
//removethispartifyoudonotneedNetscape4towork
document.captureEvents(Event.KEYUP);
}
/*thisnextlinetellsthebrowsertodetectakeyup
eventoverthewholedocumentandwhenitdetectsit,
itshouldruntheeventhandlerfunction'alertkey'*/
document.onkeyup=alertkey;
//nowcreatetheeventhandlerfunctiontoprocesstheevent
functionalertkey(e){
if(!e){
//ifthebrowserdidnotpasstheeventinformationtothe
//function,wewillhavetoobtainitfromtheeventregister
if(window.event){
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

93/223

5/30/2015

JavaScripttutorial

//InternetExplorer8
e=window.event;
}else{
//totalfailure,wehavenowayofreferencingtheevent
return;
}
}
if(typeof(e.keyCode)=='number'){
//DOM
e=e.keyCode;
}elseif(typeof(e.which)=='number'){
//NS4compatible,includingmanyolderbrowsers
e=e.which;
}elseif(typeof(e.charCode)=='number'){
//alsoNS6+,Mozilla0.9+
e=e.charCode;
}else{
//totalfailure,wehavenowayofobtainingthekeycode
return;
}
window.alert('Thekeypressedhaskeycode'+e+
'andiskey'+String.fromCharCode(e));
}

Testithere:Clickthislinktostart/stopkeyupdetectionthenpressanykeytotestthisscript.Note
that some keys give VERY odd responses with String.fromCharCode. The only reliable ones are
letterandnumberkeysonthemainpartofthekeyboard.

Detectingthemousecoordinateswhenitmovesoverapositionedelement
InInternetExplorer8(and9+inquirksmode),themousepositionwillbeoffsetbythethicknessofthewindow
border(whichcandetectmousemovementsasifitwerethepagebody).OnWindowsXP,thiswouldtypicallybe
2pixelsforthedefaultandclassicthemes(meaningwhenthemouseisat0,0itwillbereportedas2,2),and0px
infullscreenmode,butitcanbedifferentforotherthemesoroperatingsystems.Thereisnoknownworkaround
forthisbug.
iCab2cannotdetectmouseeventsoverthepageitself,onlyoverspecificelementswithinit(suchaslinks).
WebTVonlydetectsmouseeventsoverlinks.
OmniWeb4.2doesnotprovideanyinformationaboutevents.
Cluebrowseronlydetectsmousedown/upevents,andonlyoverlinks.
IamunsureofthecapabilitiesofNetBox,iPanelMicroBrowserandOpenTVhere.

Therearethreewaysthatarereliablysupportedwhichgivemousecoordinates.Thereisalsoone
unreliableway.Allaregivenaspropertiesoftheeventobject,suchas eventObject.clientX.These
willbeusedtoobtainthecoordinatesrelativetotheentirepage.
With clientX/Y, the standard was not very well written, so some older browsers made mistakes
when implementing it. The coordinates should be relative to the displayed portion of the page, but
Opera6,Konqueror2andiCab2(noneofwhicharethecurrentversionsofthosebrowsers)give
thecoordinatesrelativetotheentirepage.Thereisnoeasywaytodetectifabrowsersupportsit
correctlyandtheonlywaytowritethispieceofscriptistodetectthebrowsersthatdonotcomply
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

94/223

5/30/2015

JavaScripttutorial

withthestandardandprovideappropriatescripts.ThisistheonlytimeIwilltellyoutodothis.
Clue browser also makes this mistake, but as it cannot detect scrolling, there is no need to
compensate.
NotethatOpera7+,Konqueror3+andiCab3+actuallycomplywiththestandard,butastheyalso
providespageX,thescriptIwillshowyouusesthatinstead,soagain,theproblemisavoided.
Opera6canbedetectedbecausetheproperty'navigator.userAgent'containsthestring'Opera',
even if it is running in IE5 emulation mode. iCab 2 can be detected because its
window.ScriptEngine method contains the string 'InScript', even if it is running in emulation mode.

Konqueror2canbedetectedbecausetheproperty'navigator.vendor'is'KDE',evenifitisrunning
inemulationmode.
1. IfpageX/Yissupplied,pageX/Yisrelativetothewholepage,andiscompletelyreliable.
2. If clientX/Y is supplied, clientX/Y should be relative to displayed portion of page (DOM
compatible).
3. Sometimes clientX/Y is relative to the whole page (in browsers that did not implement the
specificationproperly).
Virtually all current browsers provide both pageX/Y and clientX/Y. Internet Explorer 8 (and 9+ in
quirksmode)istheonlycurrentbrowserthatprovidesclentX/Y,butnotpageX/Y.
Seethelastsection,'Windowsizeandscrolling',forinformationonhowtodetecthowfarthepage
hasbeenscrolled.Seethesectionon'DHTML',forhowtoreferencethepositionedelement.
if(myReference.captureEvents&&Event.MOUSEMOVE){
//removethispartifyoudonotneedNetscape4towork
myReference.captureEvents(Event.MOUSEMOVE);
}
myReference.onmousemove=alertCoord;
functionalertCoord(e){
if(!e){
if(window.event){
//InternetExplorer8
e=window.event;
}else{
//totalfailure,wehavenowayofreferencingtheevent
return;
}
}
if(typeof(e.pageX)=='number'){
//mostbrowsers
varxcoord=e.pageX;
varycoord=e.pageY;
}elseif(typeof(e.clientX)=='number'){
//InternetExplorer8andolderbrowsers
//otherbrowsersprovidethis,butfollowthepageX/Ybranch
varxcoord=e.clientX;
varycoord=e.clientY;
varbadOldBrowser=(window.navigator.userAgent.indexOf('Opera')+1)||
(window.ScriptEngine&&ScriptEngine().indexOf('InScript')+1)||
(navigator.vendor=='KDE');
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

95/223

5/30/2015

JavaScripttutorial

if(!badOldBrowser){
if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){
//IE4,5&6(innonstandardscompliantmode)
xcoord+=document.body.scrollLeft;
ycoord+=document.body.scrollTop;
}elseif(document.documentElement&&(document.documentElement.scrollLeft||
document.documentElement.scrollTop)){
//IE6(instandardscompliantmode)
xcoord+=document.documentElement.scrollLeft;
ycoord+=document.documentElement.scrollTop;
}
}
}else{
//totalfailure,wehavenowayofobtainingthemousecoordinates
return;
}
window.alert('Mousecoordinatesare('+xcoord+','+ycoord+')');
}

Testithere:passyourmouseoverthislinktoobtainitscoordinates.
Todetectmousecoordinatesoverthewholedocument,usedocumentinsteadofmyReference.
Since all the problematic old browser versions have now been replaced with versions that work
correctly,youmaywanttoremovethesniffer,andkeepthecodeclean.Youmaynotwanttodothis
ifthereisachancethatanyofyourvisitorsareusingthoseolderversions(theywon'tbe).Ifthatis
notaproblemforyou,youcouldusethiscodeinstead:
document.onmousemove=alertCoord;
functionalertCoord(e){
varxcoord,ycoord;
if(!e){e=window.event;}
if(!e){return;}
if(typeof(e.pageX)=='number'){
xcoord=e.pageX;
ycoord=e.pageY;
}elseif(typeof(e.clientX)=='number'){
xcoord=e.clientX;
ycoord=e.clientY;
if(document.body&&(document.body.scrollLeft||document.body.scrollTop)){
xcoord+=document.body.scrollLeft;
ycoord+=document.body.scrollTop;
}elseif(document.documentElement&&(document.documentElement.scrollLeft||
document.documentElement.scrollTop)){
xcoord+=document.documentElement.scrollLeft;
ycoord+=document.documentElement.scrollTop;
}
}else{return;}
window.alert('Mousecoordinatesare('+xcoord+','+ycoord+')');
}

Detectingmousebuttons

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

96/223

5/30/2015

JavaScripttutorial

Konqueror,SafarionMac,OmniWeb4.5+,iCab3+,TkhtmlHv3andEscape4donotdetectrightclicksusing
normalmouseevents.
OperauserscanchoosetoallowscriptstodetectrightclicksenabledbydefaultsinceOpera10.
Internet Explorer 4, Safari 1.1, Opera, Konqueror, ICEBrowser, NetFront, Tkhtml Hv3+, Netscape 4, Escape,
OmniWeb4.2,WebTV/MSNTVandCluebrowserdonotsupporttheoncontextmenuevent.
WebTV,iCab2,NetFront3.3andCluebrowserdonotpassinformationaboutmousebuttons.
WebTVcannotdetectmousedownormouseupevents.
OmniWeb4.2doesnotprovideanyinformationaboutevents.
IamunsureofthecapabilitiesofNetBox,iPanelMicroBrowserandOpenTVhere.

This example gives two methods for detecting then handling events with an link element. One is
written using the standard HTML syntax and one of which is written using JavaScript syntax. It will
extractthemousebuttonthattriggeredtheevent.Note:thismaynotworkwith'click'events.
There is also the oncontextmenu event that fires in most current browsers when a user activates
theircontextmenu,butthatisnot the same thing, since it also covers Ctrl+Click on Macs, and the
contextmenukeyonWindowsandLinux/UNIX.
The mouse button is passed using either the which or button properties. With 'which', 1 is left
button,2ismiddlebutton,3isrightbutton.Withbutton,thestandardsaysthat0isleftbutton,1is
middlebutton,2isrightbutton,butinIEcompatiblebrowsers,1isleftbutton,4ismiddlebutton,2is
right button. Escape/Evo 5 uses a totally different numbering system, 1 is left button, 2 is middle
button,0isrightbuttonIsuggestyouignoreEscape/Evo.
Theonlytimeyoushoulddetectabuttoniswhenyouwant,forexample,tocreateadragdroptype
effect, and you want to ensure they are using the left (normal dragging) button. You should never
abuse it to break the user's context menu, as that will only make your site inaccessible, and
annoyingforyourusers,andisnotreliableanyway.Whileitispossibleinmanybrowserstodetect
andreplacetheuser'scontextmenu(forexample,toprovideaDHTMLmenuwithoptionsrelatingto
theitemthattheuserclicked),youshouldavoidapplyingthistotheentiredocument,asmanyusers
usetheircontextmenufornavigation,andwillhaveproblemsusingyourpageifyoupreventthem
fromopeningthebrowser'scontextmenu.
The event registration attribute ( onmouseup="etc.") is equivalent to an event handler function, and
has access to all the usual function information, such as the attributes collection. It can get a bit
messy writing all of the button detection code in there, so I want to pass it to the main handler
function.RememberthatinDOMcompatiblebrowsers,thefirstargumentistheevent,soIneedto
pass that too. I also want the handler to have access to the element that triggered the event so I
mustpassthat.
<scripttype="text/javascript">
//linkandformelementsdonotneedtobetoldtocapture.
//UsingtheJavaScriptsyntax,wehavetowaitfortherelevant
//partofthepagetoloadbeforetellingittodetecttheevent
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

97/223

5/30/2015

JavaScripttutorial

//Thisiseasiestdonewithaloadeventlistener
window.onload=function(){document.links[0].onmousedown=alertBut;}
functionalertBut(e,evElement){
if(!e){
if(window.event){
//InternetExplorer8
e=window.event;
}else{
//totalfailure,wehavenowayofreferencingtheevent
return;
}
}
if(typeof(e.which)=='number'){
//Netscapecompatible
e=e.which;
}elseif(typeof(e.button)=='number'){
//DOM
e=e.button;
}else{
//totalfailure,wehavenowayofobtainingthebutton
return;
}
if(!evElement){evElement=this;}
/*'this'willexistifIhaveusedobject.onEventName=alertBut;
IfIhavepassedevElementfromtheonmouseupattribute,
'this'willrefertowindow*/
window.alert(evElement+'wasclickedwithbutton'+e);
}
</script>
<aonmouseup="alertBut(arguments[0],this);"href="whatever">

Testthishere:clickthislinkandthescriptwilltrytoworkoutwhatbuttonyouused.
NotethatbrowsersmaypreventyoufromusingJavaScriptdialogs(likealert)inrightclickormiddle
clickeventhandlers,topreventyoufrompointlesslybreakingthebrowser'sUIinteraction.
There is also an oncontextmenu event supported by most current browsers (not available in all
browsers most obviously not supported in Opera 9, but supported since Opera 10), that fires
insteadoftheonclickeventwhentheuserrightclicks,orwhentheypressthecontextmenukey,or
otherwisetriggerthecontextmenu.Thiscanbecancelledinordertoreplacethecontextmenuwith
acustomcontextmenu.Note,however,thattheusermaybeabletopreventitbeingdetected,and
disablingitcanmakeyourpageinaccessibleforuserswhousethecontextmenufornavigation.Itis
also entirely possible that a browser may not support it (since it is not part of existing standards),
andbrowsersmaynotalwaystriggeritforallwaysofactivatingthecontextmenu.Useitsparingly,
and only for places where you want to provide a custom context menu that provides additional
functionality relating to the item that was clicked. It should never be relied on as the only way to
providefunctionality.
<scripttype="text/javascript">
functionshowContextMenu(e){
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

98/223

5/30/2015

JavaScripttutorial

if(!e){
//InternetExplorer
e=window.event;
//noneedtocheckforitsexistence;
//nobrowserthatsupportsoncontextmenuwillfailtoprovideeventinformation
}
//...putcodetogetthemousecoordinateshere(shownabove),
//andshowtheDHTMLlayerthatwillbeusedasthemenu(shownintheDHTMLchapter)...
}
</script>
<aoncontextmenu="showContextMenu(arguments[0]);returnfalse;"href="whatever">

Test this here: right click this link and the script will try to replace the context menu with an alert.
(Note that since this attribute is not valid HTML 4, it is set using an event handler property in this
test.)

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

99/223

5/30/2015

JavaScripttutorial

Creatingobjects

Netscape4,IE4onWindowsandMac,andIE5onMacdonotsupporttheinstanceofoperator.

AnyfunctioninJavaScriptcanbeusedtocreatecustomobjectclasses,simplybycallingitusingthe
keyword new. When called in this way, the special variable this inside the function references the
new object that is being constructed (it normally refers to the 'current' object, which is usually
window, except inside methods). The function should not return a value. The following function can

beusedasdemonstratedtocreateanobjectofclassmyobject:
functionmyobject(){
this.containedValue=0;
this.othercontainedValue=0;
this.anothercontainedValue=0;
}
varmything=newmyobject();

Andthereyougo,mythingisnowaninstanceofclass myobject.Itwillhavethefollowingproperties,
allofwhichwillbe0:
mything.containedValue
mything.othercontainedValue
mything.anothercontainedValue

Youcouldalsonowwritethis:
myobject.prototype.newContainedValue=someValue;

This will cause all instances of class myobject will have the property newContainedValuewithvalue
someValue.

Usetheinstanceofoperatortofindoutifyourobjectisaninstanceofagivenobjectclass:
if(myvarinstanceofArray){...}
if(myvarinstanceofmyobject){...}

Creatinganobjectwithmethods
NowIwillgiveyouanexampleshowingyouhowtocreatemethodsforyourobjects.Asanexample,
Iwillcreateacircleasmyobject.Themethodswillbe
nameOfCircle.retArea()
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

100/223

5/30/2015

JavaScripttutorial

Returnstheareaofthecircle(pir 2)
nameOfCircle.retCirc()

Returnsthecircumferenceofthecircle(2pir)
nameOfCircle.mvBy(xDis,yDis)

MovesthecirclebyxDisinthexdirectionandyDisintheydirection
Thefollowinglinespointthemethodstofunctionsthattheobjectwilluseasthemethods:
this.retArea=getTheArea;
this.mvBy=mvCclBy;
this.retCirc=function(){...};

Thethirdofthesedefinesthemethodusingananonymousfunctioninoneline,anddoesnotwork
in some early Netscape 4 releases. Note, it has a semicolon after the '}', and is one of the few
placeswherethisiscorrectpractice.
functionmycircle(x,y,r){
this.xcoord=x;
this.ycoord=y;
this.radius=r;
this.retArea=getTheArea;
//Thisnextlineusesanalternativesyntax
this.retCirc=function(){return(Math.PI*this.radius*2);};
this.mvBy=mvCclBy;
}
functiongetTheArea(){
return(Math.PI*this.radius*this.radius);
}
functionmvCclBy(xDis,yDis){
this.xcoord+=xDis;
this.ycoord+=yDis;
}
/*
createamycirclecalledtestcirclewheretestcircle.xcoordis3
andtestcircle.ycoordis4andtestcircle.radiusis5
*/
vartestcircle=newmycircle(3,4,5);
/*
usethemvBymethodtodisplacethecentreoftestcircle.
moveitby2inthexdirectionand3intheydirection
*/
testcircle.mvBy(2,3);
//testcircle.xcoordisnow5andtestcircle.ycoordisnow7
window.alert('Theareaofthecircleis'+testcircle.retArea());
window.alert('Thecircumferenceis'+testcircle.retCirc());

Thespecial'toString'method
Allobjectshavethe 'toString'method,evenifyoudonotdefineityourself.Themethodreturnsa
string representation of the object, and is automatically called whenever a string representation of
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

101/223

5/30/2015

JavaScripttutorial

anobjectisrequired,suchaswhenyouusealert(myObject);
In most browsers, this returns '[object Object]', although some more useful browsers return a
stringlikethis:
'{property1:value1,property2:value2,method1:function(){...},etc.}'

However, for your own objects, you may wish to provide a special string that may provide more
usefulinformation.Todothis,simplydefinethe'toString'method:
this.toString=function(){
return'Circleobject;xcoord:'+this.xcoord+',ycoord:'+
this.ycoord+',radius:'+this.radius;
};

Advancedobjecttechniques
These deal with concepts that are rarely used in JavaScripting. JavaScript is a more powerful
programminglanguagethanmostpeoplemakeuseof,butthatisbecauseinnormalscripting,these
powerful features are not really necessary. If you are just learning, or if you are interested only in
daytodayscripting,Isuggestyoumoveontothenextchapter.
SomeofthesetechniquesmaynotworkinolderbrowserslikeearlyNetscape4releases.

Addingextraproperties/methodsusingprototype
InternetExplorer5.2,Safari1.3,Konqueror3.3,Netscape4,andWebTVdonotimplementthehasOwnProperty
method.

Take the mycircle example from the top of this section (creating new objects). We have already
created an instance of the mycircle class called 'testcircle'. And we can also assume that we
have created a few other mycircles. Now, let us assume that we want to add another property to
eachcircle.Forexample,wewanteachcircletohavea'texture'property.Wecouldusethis:
testcircle.texture='smooth';

And we could do this for each individual mycircle. But since we want to do this for all of them, it
would be much more easy to give all instances the property at the same time. So we can use the
'prototype'propertyoftheclassconstructor:
mycircle.prototype.texture='smooth';
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

102/223

5/30/2015

JavaScripttutorial

Immediately,allofthemycirclesthatwehavecreatedwillnowinheritthenewproperty:
alert(testcircle.texture);
//alerts'smooth'

Wecanaddnewmethodsthesameway:
mycircle.prototype.setArea=function(oArea){
this.radius=Math.sqrt(oArea/Math.PI);
};
mycircle.setArea(5);

Thisismostusefulwithinstrinsic(fundamentalinbuilt)objects.Forexample,theregularexpression
construct/a[09]b/gisshorthandfor newRegExp('a[09]b','g');andinfactthesameistrueforall
intrinsicobjectclasses,suchasString,NumberandBoolean.Soif,forexample,wewantedtocreate
anewmethodonallstringscalled 'reverse'thatreturnedtheircontentsinreverseorder,wecould
dothis:
String.prototype.reverse=function(){
for(varoStr='',x=this.length1,oTmp;oTmp=this.charAt(x);x){
oStr+=oTmp;
}
returnoStr;
};

Theuseof prototypecouldhavebeenappliedtocreateallofthemethodsofthe mycircleobject,


not just new ones. This gives a mixed response to performance. It will not have to store individual
copies of the methods for each instance of the object, so it may require less memory, but it will
requirethebrowsertosearchthecurrentandparentscopestofindthemethods.Thismaycausea
marginal delay. Generally, you should use what is appropriate for your code, and not base this
decisiononperformance(unlessyouaredealingwithaveryspecificcontrolledenvironment):
functionmycircle(x,y,r){
this.xcoord=x;
this.ycoord=y;
this.radius=r;
}
mycircle.prototype.retArea=function(){
return(Math.PI*this.radius*this.radius);
};
mycircle.prototype.retCirc=function(){
return(Math.PI*this.radius*2);
};
mycircle.prototype.mvBy=function(xDis,yDis){
this.xcoord+=xDis;
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

103/223

5/30/2015

JavaScripttutorial

this.ycoord+=yDis;
};

In some cases, it may be desirable to work out if a property on an object is attached to the object
instanceitself,orsomewhereinitsprototypechain.InJavaScript,allobjectshaveamethodcalled
hasOwnPropertythatreturnstrueifthegivenpropertyisattachedtotheindividualobjectinstance.Of

course, it is also possible to check if the object's constructor also has the same property with the
same value as the object instance itself, but that can give the wrong result if separate properties
existswiththesamevalueonboththeobjectinstanceandtheprototypechain.The hasOwnProperty
methodacceptsasingleparameterthenameofthepropertyasastring.
functionmyclass(){
this.propertytwo=2;
this.propertythree=3;
}
myclass.prototype.propertyone=1;
myclass.prototype.propertytwo=2;
varmyinstance=newmyclass();
myinstance.propertyfour=4;
alert(myinstance.hasOwnProperty('propertyone'));
//alertsfalse
alert(myinstance.hasOwnProperty('propertytwo'));
//alertstrue
alert(myinstance.hasOwnProperty('propertythree'));
//alertstrue
alert(myinstance.hasOwnProperty('propertyfour'));
//alertstrue
alert(myinstance.hasOwnProperty('propertyfive'));
//alertsfalse

Publicandprivateproperties
ThisisaconceptthatisalmostneverusedinJavaScript,andthereisagoodreason.Itsimplyisnot
necessary. Even complicated scripts are almost never complex enough to require this level of
control. However, many programmers familiar with other programming languages (such as Java or
C++) often desire this behavior in JavaScript simply because it is a concept they are familiar with.
Thissortofconceptisonlyreallyusefulwhenputtingtogetherlargeprojectsfrommultiplepiecesof
code.
Say for example that I am producing a public functions library. A set of constructors and methods
thatpeoplecanincludeintheirownprojects(somethingthatJavaprogrammersuseallofthetime).
Say for example that the mycircle constructor is included in it, so that you can create your own
mycircles.Nowsayforexampleyoutrythis:
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

104/223

5/30/2015

JavaScripttutorial

varaCircle=newmycircle(5,6,'about3mm');

That will work now (it's not a valid measurement, but my constructor will not argue), but later on
when you try to use the methods that my class provides, it will fail. So I can check what you have
provided,andmakesureitisavalidnumber,anduseadefaultvalueifitisnot.Butthenyoucan
saysomethinglikethis:
aCircle.radius='sometext';

Again,itwouldbreak(ofcourse,itisyourownfault,butinmorecomplicatedapplications,itwould
be possible to make a mistake where this causes a real problem). So what I want to do is to not
allow you to modify that property directly, and only allow you to change it using a method that I
control:
this.setRadius=function(oRad){
if(typeof(oRad)=='number'&&oRad>=0){
this.radius=oRad;
}else{
this.radius=0;
}
};

An alternative situation where this can be important is if I am storing the information in one set of
properties.Ithenupgrademylibraries,maybeaddingsomeextrafunctionality.Butinordertodoso,
I have to change the properties that I am using. If your script was relying on them existing in a
specific format, and I have now changed that format, your script would fail. If I could protect those
properties, and force you to use only methods, then I could do whatever I needed with the
properties,andaslongasIthenchangethemethodstousethenewproperties,yourscriptwould
keep working, and you would not even need to know what I had changed or why. That way, we
couldeachmanageourownproject,andnotwasteeachother'stime.
Itwouldalsohelpavoidpossibleconflictsbetweenundisclosedproperties,andyourownscripting.
Forexample,ifyoudecidetotemporarilyassignapropertytoanobject,butyouwereunawarethat
internally, my object constructor already used that property name, you would overwrite my object's
property,andcauseproblemswiththeobject.
This is what private properties are for. They do not allow scripts that use the contructor to use or
modify the properties directly. They only allow the methods of the object itself to use and modify
them. Unlike many other languages, JavaScript does not declare each variable type as 'public' or
'private'.Italldependsonhowyoucreatethem.
Saying 'this.propertyname' as I did above will create a public property. Any script can create an
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

105/223

5/30/2015

JavaScripttutorial

objectthenuseandmodifyitspropertiesdirectly.Using 'var'todefineavariableintheconstructor
will create a private property. Note that unlike public properties, the private properties are then
accessed, including from within methods, without the 'this.' prefix just like a normal variable. This
makes heavy use of JavaScript's scope functionality. Private variables can only be accessed from
methods that are declared inline, and not externally referenced or created using the prototype
construct.Methodsofthiskindarealsoknownasprivilegedmethods.Anexampleofitsusemight
be:this.mymethod=function(){alert(propertyname);};
functionmyob(){
this.property1='value1';//thiscreatesapublicproperty
varproperty2='value2';//thiscreatesaprivateproperty
this.method1=function(){alert(property2);};
}
varoneOb=newmyob();
alert(oneOb.property1);//alerts'value1'
alert(oneOb.property2);//alertsundefined(privateproperty)
oneOb.method1();//alerts'value2'

Similarly, you can also create private methods. These are simply a function that you create inside
the constructor function. This may look confusing, but it works. The private function can only be
calledbytheconstructoritself,orbymethodsthataredefinedinline.Privatemethodscanbeused
as public methods, if they are assigned to a public method constructor, and accessed using the
publicmethodconstructor(aswith'method2'below).
functionmyob(){
functioncantBeSeen(){
alert(secretValue);
}
varsecretValue='';
this.method1=function(){
secretValue='nosurprises';
cantBeSeen();
};
this.method2=cantBeSeen;
}
varoneOb=newmyob();
oneOb.method1();//alerts'nosurprises'
oneOb.method2();//alerts'nosurprises'

For more information on private, public and privileged properties and methods in JavaScript, see
DouglasCrockford's'PrivateMembersinJavaScript'page.

Subclassesandclassinheritance
ThisisalsohardlyeverusedinJavaScript,despiteitspopularityinotherlanguages.Takethisasan
example.Iwanttomakeanewtypeofobject,thatwillstorethedatatorepresentasphere(aball
incaseyoudon'tknow).Sinceasphereisjustathreedimensionalcircle,Iwouldprobablywantto
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

106/223

5/30/2015

JavaScripttutorial

includeallthemethodsIcreatedearlierforthecircleobject retAreatogetthecrosssectionarea,
retCirctogetthecircumference, mvBytomoveitbyacertainamount.Aditionally,Iwouldprobably

wantretVoltogetthevolume,andretSurftogetthesurfacearea.Iwouldalsoneedtoprovideaz
coordinatewhencreatingtheobject,andagainwhencallingthemvByproperty.
So, I want to create a new type of object, based on the mycircle, but with a few aditions and
modifications. I will call this new type of object a mysphere. Now, I could just rewrite all the code I
alreadywroteforthe mycircleandchangethebitsIneed.Butinarealworldapplication,thismight
bealotofwastefulduplication,foronlyoneortwomodifications.SowhatIwanttodoismakethe
mysphereinheritallthepropertiesandmethodsofthemycircle,thenoverwriteonlytheonesIwant.

Thiseffectivelymakes mysphereasubclassof mycircle,andmakingthe mysphereclassconstructor


inheritfromthemycircleclassconstructorisassimpleasthis:
functionmysphere(x,y,z,r){...constructorcode...}
mysphere.prototype=newmycircle();

Incaseyouarewondering,thewayitworksistoactuallycreatea mycircle,thenassignthattothe
mysphereconstructorprototype.Asaresult,themysphereconstructorhasthemycircleobjectadded

to its prototype chain. What this means is that each time a mysphere is created, it will inherit the
propertiesandmethodsofthe mycircleobject.Itcanthenoverrideanyofthesepropertiesusingits
own prototype, or with properties and methods created within its own constructor. If any of these
propertiesaresubsequentlyremoved(usingthe 'delete'keyword),theinheritedoneswillbecome
availableagain.Thatalsomeansthatifthe mycircleprototypeischanged(propertiesareaddedor
deleted, etc.), these changes are replicated down the chain, so the mysphere also inherits these
changes.
Notethattheprototypechainisestablishedforeachobjectastheobjectiscreated.Onceanobject
hasbeencreated,itsprototypechaincannotbechanged(thoughnewpropertiesandmethodscan
stillbeaddedtoitsparentclasses,andthosechangeswillbereflectedintheobject).Changestoits
prototypechainwillhavenoeffectitwillstillseetheoldprototypechain.Thenewchainwillonlybe
usedfornewinstancesofthatclass.Thisisalsothecasefortheassignmentofanew mycircleto
the prototype of mysphere (which, as stated, creates a new instance of the mycircle class) any
subsequent changes to the prototype chain of the mycircle class will not be reflected in the
mysphereclass.Forthisreason,itisveryimportanttoensurethattheprototypechainisbuiltinthe

correctorder,withclassconstructorsandtheirprototypessetupbeforeanychildclassismadeto
inheritfromthem.Propertiesandmethodscanstillbeaddedtoanyclassorparentclassatanytime
aftertheirownprototypechainhasbeensetup.
Thelinethatmakes mysphereinheritfrommycirclesoundssimpleenough.Andatleast,itwouldbe,
butyouwillrememberthat mycircleexpectedmetopassitsomeparametersthatitwouldthenuse.
Then I call my new constructor, and these parameters will not automatically be passed to the
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

107/223

5/30/2015

JavaScripttutorial

mycircleconstructorfunction.IneedtodothismyselfforeachmyspherethatIwanttocreate.But

since I am not passing these parameters when assigning the mycircle object to the mysphere
prototype, I also need to ensure that the mycircle contructor stops before attempting to create its
own properties. Instead of defining the public properties immediately, I will define them using a
method (that I have decided to call getready), and if the required parameters have been passed
( arguments.length),Iwillimmediatelycallthemethod.
Iftheparametersarepresent,the mycircleconstructorkeepsworking,andnooneneedstoknow
thatanythingwaschangedatall.Tomakethingseasierlateron,Iwilltakeallofthemethodsoutof
theconstructor,andaddthemlaterusingtheprototype.Thatway,the mycircleprototypemethods
will always be available without me needing to create a new mycircle. Unfortunately, this also
meansthatpublicandprivatepropertiesareveryhard(orimpossible)touse.It'satradeoffone
functionalityforanother.
functionmycircle(x,y,r){
if(arguments.length){this.getready(x,y,r);}
}
mycircle.prototype.getready=function(a,b,c){
this.xcoord=a;
this.ycoord=b;
this.radius=c;
};
mycircle.prototype.retArea=function(){
return(Math.PI*this.radius*this.radius);
};
mycircle.prototype.retCirc=function(){
return(Math.PI*this.radius*2);
};
mycircle.prototype.mvBy=function(xDis,yDis){
this.xcoord+=xDis;this.ycoord+=yDis;
};

Now,backtothemysphereconstructor.Ihavealreadysaidhowtomakeitinherit,butitstillneedsto
runthe mycircle.getreadymethodtoinitialisetheproperties.Todothis,wewillneedtoreference
the parent class prototype, and run the method ourselves. This also ensures that even if each
parent class uses the same method name ( getready), the correct one is always referenced. Since
wecanalmostneverbesurehowmanysubclasseswewillneed,itisusefultodoitthisway,and
simply use the same method name for each, knowing that we will not have problems with name
conflicts.
Whenrunningthemethod,weneedtotellJavaScriptthateventhoughwearereferencingamethod
for a different prototype, we want to run it as if it were a method of the object we are creating (to
make sure that any properties it creates are added to the object we are creating). This could be
done using the 'call' method or 'apply' method, but unfortunately, Internet Explorer 5 does not
understandthese,soIwillassignittoatemporarypropertyofthenewobject,andrunitfromthere.
To reference the method from the parent class prototype, it would be possible to use the
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

108/223

5/30/2015

JavaScripttutorial

constructor's prototype chain to locate it (the property that references the constructor will, at this
point,refertotheparentclassmoreonthatlater):
this.constructor.getready

However,thatwillonlyworkforonelevelofinheritance,duetothewayitisrunasamethodofthe
currentobjectforallchildclasses.Asaresult,itisbesttoreferenceitbyname,whichwillworkno
matterhowmanylevelsofclassinheritanceareused:
mycircle.prototype.getready

Note that when assigning the mycircle object to the mysphere prototype, it also overwrites the
mysphereprototypeconstructorproperty.Thisisnotamajorproblem,butsomescriptsuseit,sowe

willputthereferencebackwherewewantit:
functionmysphere(x,y,z,r){
if(arguments.length){this.getready(x,y,z,r);}
}
//inheritfromthemycircleprototype
mysphere.prototype=newmycircle();
//putthecorrectconstructorreferenceback(notessential)
mysphere.prototype.constructor=mysphere;
mysphere.prototype.getready=function(a,b,c,d){
//referencethegetreadymethodfromtheparentclass
this.tempReady=mycircle.prototype.getready;
//andrunitasifitwerepartofthisobject
this.tempReady(a,b,d);
//nowthatallrequiredpropertieshavebeeninherited
//fromtheparentclass,defineextraonesfromthisclass
this.zcoord=c;
}
mysphere.prototype.mvBy=function(xDis,yDis,zDis){
//overridetheexistingmethod
this.xcoord+=xDis;
this.ycoord+=yDis;
this.zcoord+=zDis;
};
mysphere.prototype.retVol=function(){
return(4/3)*Math.PI*Math.pow(this.radius,3);
};
mysphere.prototype.retSurf=function(){
return4*Math.PI*this.radius*this.radius;
};

Andfinally,touseit:
vartestsphere=newmysphere(3,4,5,6);
alert('Thecrosssectionareais'+testsphere.retArea());
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

109/223

5/30/2015

JavaScripttutorial

alert('Thecircumferenceis'+testsphere.retCirc());
alert('Thevolumeis'+testsphere.retVol());
alert('Thesurfaceareais'+testsphere.retSurf());

Testthisclassinheritancescript.
Thereisnolimittohowmanysubclassescaninheritfromaclass,andthereisalsonolimittohow
manylevelsofsubclassescanbecreated.Asanexample,Iwillcreatea ballclassthatwillinherit
fromthemysphereclass:
functionball(x,y,z,r,m){
if(arguments.length){this.getready(x,y,z,r,m);}
}
ball.prototype=newmysphere();
ball.prototype.constructor=ball;
ball.prototype.getready=function(a,b,c,d,e){
this.tempReady=mysphere.prototype.getready;
this.tempReady(a,b,c,d);
this.mass=e;
}
ball.prototype.retDensity=function(){
returnthis.mass/this.retVol();
};

Testthisclassinheritancescript.
Theinstanceofoperatorreturnstruewhentestinganobjectagainstanyclassinitsprototypechain,
soitwouldsaythataninstanceofthe ballclasswasalsoaninstanceofthe mysphere class, and
alsothemycircleclass.
FormoreinformationonsubclassesandclassinheritanceinJavaScript,seeKevinLindsey'sclass
inheritancepage.

Staticmethodsandproperties
Astaticproperty(ormethod)isapropertyoftheclassconstructor,notanindividualinstanceofthat
class. For example, mycircle.myproperty instead of (new mycircle()).myproperty. While not often
used in JavaScript, they are often encountered in other programming languages, and are covered
hereforthosewhoarefamiliarwiththeminotherlanguages.AswithmostobjectsinJavaScript,the
functions used as class constructors can have properties added to them, and these will be public
staticproperties:
functionmycircle(){...}
mycircle.aStaticProperty=true;
mycircle.aStaticMethod=function(){...};

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

110/223

5/30/2015

JavaScripttutorial

Makingaprivatestaticpropertyissignificantlyharder,asitisaconceptthatJavaScript(atleastin
widelysupportedimplementations)simplydoesnotrecognise.However,itispossibletoprovidean
approximate equivalent to this functionality by using an anonymous wrapper function to create a
scope where the private "properties" are created as normal variables, then having that return
anotherfunctionthatwillbeusedastheconstructor.Aslongastheconstructorfunctionisdeclared
inside the anonymous function, it will have access to the private variables from the anonymous
function's local scope when it is executed. This structure is described in the section on writing
functions.
varmycircle=(function(){
varprivateStaticVariable=true;
functionprivateStaticMethod(){...}
functionpublicConstructor(){
this.normalInstanceProperty=1;
...
alert(privateStaticVariable);
};
publicConstructor.prototype.normalProperty=2;
returnpublicConstructor;
})();
mycircle.publicStaticProperty=true;
mycircle.publicStaticMethod=function(){...};

Singletons
The singleton is one of the design patterns that is commonly seen in other languages, and in a
simplifiedformatwithinJavaScript.Theideaofasingletonistohaveaclassthatcanonlyhaveone
objectcreatedfromit.Everytimeascripttriestocreateanotherinstanceofthatclass,itreturnsthe
samecopyasbefore,soifthepropertiesaremodifiedononeofthem,thentheotherwillalsosee
the modifications. The use of singletons can be controversial, but I will not cover that here. This
tutorialwillonlyshowyouhowtoproducethem.
InJavaScript,thereistheabilitytocreateagenericanonymousobjecttoservethispurpose.Itcan
either be created using newObject() or the shorthand {...} syntax, and can then be given any
propertiesormethodsthatareneeded.However,thisdoeshavelimitationsusingagenericobject
meansthatitisnotpossibletouseprivateproperties.Inmostcases,thisisfunctionalitythatisnot
needed, and the majority of scripts simply use a generic object. Instead of trying to constuct new
instancesoftheobject,scriptswilljustcreateanothervariablethatreferencestheobject:
varmySingleton={foo:'bar',baz:'qux',aMethod:function(){...}};
...
varanotherReference=mySingleton;

If you feel the need for private properties, read on. With other languages, the expectation is to
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

111/223

5/30/2015

JavaScripttutorial

create a class constructor that refuses to be instantiated by other scripts, and provides a public
static method that constructs the object the first time it is called, and returns the same object for
each subsequent call. JavaScript, however, does not provide a way to prevent a class from being
instantiated(atleastinwidelysupportedJavaScript).Ifitexistsasafunction,itcanbecalledasa
constructor.
Itistempting(andsometimesused)tosimplyuseananonymousfunctionastheclassconstructor,
construct it once, and use its scope to keep variables private. This is limited to normal private
properties, and cannot be used for private static properties. The theory is that this enforces the
singleton principle by preventing another attempt to reference and use the class constructor. This
pattern fails to produce a singleton, however, as other code can simply use the singleton's
constructor property to reference it although you could override the singleton's constructor

property, this can cause other problems later on if code needs to be able to use that to add
propertiestotheconstructor.prototype.
varmySingleton=newfunction(){
varprivateStaticVariable=true;
functionprivateStaticMethod(){...}
...
};
varnewInstance=newmySingleton.constructor();

It is, however, possible to adapt the pattern used for private static properties, to create private
properties for the singleton, while at the same time creating a proper singleton. Once again, an
anonymous function is used to contain the private variables and functions. However, instead of
returningaclasscontructorfunction,itjustreturnsthesingleobject:
varmySingleton=(function(){
varprivateStaticVariable=true;
functionprivateStaticMethod(){...}
return{...};
})();

That is, of course, a very simple pattern, but it shows something important by returning a generic
object,itisnotpossibletouse newmySingleton.constructor()tocreateaseparateinstance,asthat
would just produce a generic object. This particular format is quite awkward, however, as the
genericobjectpreventstheprototypefrombeingusedtocleanlyaddmorepropertiesandmethods.
It is very simple to extend it to make that possible, however, just by creating the class contructor
functioninsidetheanonymousfunction:
varmySingleton=(function(){
varprivateStaticVariable=true;
functionprivateStaticMethod(){...}
functionPrivateConstructor(){}
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

112/223

5/30/2015

JavaScripttutorial

PrivateConstructor.prototype.publicProperty=true;
...
returnnewPrivateConstructor();
})();

This now means that new mySingleton.constructor() will create a new instance of a
PrivateConstructorobject.However,theconstructorfunction,whencalledinthisway,ispulledout

oftheinnerscopeduringthatcall,andasaresult,itendsupwitharelativelyuselessobjectthathas
noneoftheprototype'sproperties.Onceagain,thesingletonprincipleisenforced.Newproperties
can be created by modifying the mySingleton.constructor.prototype. The singleton can itself be
usedastheprototypeforanotherconstructor,toallowsubclassestobecreated.
Therearesomereasonswhythisparticularapproachmaynotbefavouredspecificallythatitalways
createsthesingletonevenifitisneverused.Somemayalsoprefertouseafunctioncallinsteadof
having a global variable always created (though a function is still a global variable), as this may
make it possible to change the implementation later to use a different design pattern instead of a
singleton.Itispossibletotakecareofbothoftheseconcerns,byreturningafunctioninsteadofan
object. That function can check if the singleton has been created yet, store it in a private variable,
and return the instance. This has the small limitation that an instance of the object will need to be
created by an external script in order to add properties or methods to the prototype, but this is a
limitationthatisunlikelytobeaproblem:
vargetSingleton=(function(){
varprivateStaticVariable=true;
functionprivateStaticMethod(){...}
functionPrivateConstructor(){}
PrivateConstructor.prototype.publicProperty=true;
...
varonlyInstance;
returnfunction(){
if(!onlyInstance){
onlyInstance=newPrivateConstructor();
}
returnonlyInstance;
};
})();
...
varmySingleton=getSingleton();

Oranequivalentapproachthatassignsthefunctiontoaglobalvariableinsteadofreturningit(this
maybepreferredforclarity,ortoallowyoutoputtheclassinstantiationmethodsatthetopofthe
anonymousfunctioninsteadofthebottomofit):
vargetSingleton;
(function(){
varonlyInstance;
getSingleton=function(){
if(!onlyInstance){
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

113/223

5/30/2015

JavaScripttutorial

onlyInstance=newPrivateConstructor();
}
returnonlyInstance;
};
functionPrivateConstructor(){}
PrivateConstructor.prototype.publicProperty=true;
...
})();

It is, however, possible to make the anonymous function return an object which can be used for
prototypingdirectly,butthisbecomesquitemessy.The PrivateConstructorcanbemadetoinherit
itsprototypefromtheobjectthatwillbereturnedbytheanonymousfunction.Thesingleton(whenit
is created) will then inherit any changes made to that object (in addition, it will inherit the
getInstance method from the returned object, but this is harmless). I recommend that you avoid

gettingintoasituationwhereyouwouldneedthisfunctionalityinascript.
varsingletonMaker=(function(){
varprivateStaticVariable=true;
functionprivateStaticMethod(){...}
varonlyInstance;
varreturnedObject={
getInstance:function(){
if(!onlyInstance){
onlyInstance=newPrivateConstructor();
}
returnonlyInstance;
}
};
functionPrivateConstructor(){}
PrivateConstructor.prototype=returnedObject;
PrivateConstructor.prototype.publicProperty=true;
...
returnreturnedObject;
})();
...
singletonMaker.foo=true;
varmySingleton=singletonMaker.getInstance();
alert(mySingleton.foo);//true

Formoreinformationonthistopic,seeKaiJger'sarticleaboutsingletonsinJavaScript.

ECMAScript5
ECMAScript5 adds several additional methods for custom objects, allowing you to control whether
properties can be added, or obtain information about the object's prototype. ECMAScript 5 is not
currently supported by enough browsers for it to be used in most practical applications. Even the
parts that are supported by Internet Explorer 9+ are not available in quirks mode the browser
intentionallyregressestoIE6'sscriptingsupport.Thismeansthatgenericscriptsthataredesigned
toworkanywhere,willnotbeabletomakeuseofthenewfunctionalityevenonceitbecomeswidely
supported.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

114/223

5/30/2015

JavaScripttutorial

Creatingtimedelays

TherearetwowaysofcreatingtimedelayswithJavaScript.Thefirstismoresimpleandwillsimply
waitforaspecifiedamountoftimebeforeexecutingafunction.Theseconddoesthesamebutwill
repeatedlyexecutethefunction.
Note, many browsers have a minimum delay length of between 25 and 75 ms, with some of the
fastest browsers having a minimum delay of about 3 ms. If a shorter delay is specified, the actual
delaywillbetheminimumdelaylength.Evenwithhighernumbers,thedelayisneverperfect.Most
browsers will take slightly longer than the time you ask for, typically just a few miliseconds error.
Somemaycorrecttheirerrorsovertimewithintervaltimers.Alsonote,settingmanytimerswithshort
delaysononepagewillcausethebrowsertobecomeslowandsomewhatunresponsive.Threeor
fourtimersisusuallythereliablelimit.

setTimeout
InternetExploreronlyallowstwoparameterstobepassedtosetTimeout,additionalparametersareignored.

The first method uses a window method called setTimeout(). The method waits for a specified
numberofmillisecondsthenexecutesthespecifiedcode.Thecodecaneitherbeadirectreference
toafunction,oritcanbeastringthatwillbeevaluatedasifitcontainedsourcecode.
window.setTimeout(referenceToFunction,timeInMilliseconds);

window.setTimeout('runMoreCode()',timeInMilliseconds);

Whereverpossible,youshoulduseadirectfunctionreferenceasitismuchmoreefficient.Usinga
stringrequiresthebrowsertocreateanewscriptenvironmentsoitcanprocessthescript.
Ifyoucreateatimeout,thecodeafterthecallto setTimeoutwillcontinuetorunasnormal.Afterthe
specifieddelay(andoncetheoldthreadhasfinished),thetimeoutwillstartanewthread,andthe
code specified in the call to setTimeout will be run in the new thread, after any code that was still
running in the initial thread. Unlike with many more complex languages, JavaScript does not offer
any way to control when those threads sleep, wake, or yield. The JavaScript engine handles all of
that,andyoumustacceptthatyournewthreadshouldexecuteaftertheendofthecurrentthread.
Althoughintheory,amultithreadedscriptenginecouldexecutethenewthreadatthesametimeas
the old thread, JavaScript engines operate as a singlethreaded application, and will simply allow
onethreadtocompletebeforeallowingtheotherthreadtostart.Thesameappliestoevents,which
runintheirownthreads,andcanbetriggeredatanytimetheywillwaituntilexistingthreadshave
finishedbeforebeingstarted.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

115/223

5/30/2015

JavaScripttutorial

Topassvariablestoatimeout,youcanuseeitherformat.Touseastring,itisnecessarytomake
surethevariablesyouwanttopasscanberepresentedinoneoftheprimitivedatatypes,anddo
notcontainanycharactersthatwillbreakthestringformat(suchasquotes).Ifpossible,youshould
avoidthisformat,butthisisanexample,justincaseyouneedto:
window.setTimeout('runMoreCode(\''+someString+'\','+someNumber+')',10);

Thedirectfunctionreferenceismuchmoreeasy,asyoucanpassvariablesasextraparametersto
thesetTimeoutmethod.Inadditiontobeingmoreeasy,itisalsoabletoacceptanytypeofvariable.
Note, however, that this does not work in Internet Explorer. Be careful with browsers that use the
Mozilla Gecko engine (such as Firefox and Netscape 6+) as they will always pass an extra
parametertothefunctionthenumberofmilisecondserror.Thisexampleusesaninlineanonymous
function,andisequivalenttousingadirectfunctionreference:
window.setTimeout(function(a,b){
//dosomethingwithaandb
},10,someString,someObject);

Thevariablesthatarepassedtothefunctionwillbethevaluesheldbythevariablesatthetimethat
the method was called. For example, assume you had a variable called myVaranditcontainedthe
number 5. You then called a timeout, passing it the variable myVar, and set it for a delay of 1
second. Immediately you change the value of myVar to 7. When the timeout fires, it will run the
function,andpassitthenumber5,sincethatwasthevaluemyVarcontainedwhenyoucalledthe
function.
Unfortunately, since Internet Explorer does not support the functionality to pass additional
parameters to a directly referenced timeout function, the most compatible approach is simply to
make sure that the variables are kept in the current scope, so that the timeout function can
referencethemdirectly.

setInterval
InternetExploreronlyallowstwoparameterstobepassedtosetInterval,additionalparametersareignored.

The setInterval method is identical in syntax to setTimeout(). The difference is that as well as
firingafterthespecifieddelay,itwillfireagainafterthesamedelay,andwillcontinuetofireatthe
specifiedintervaluntilitiscancelled.
window.setInterval(function(a,b){
//dosomethingwithaandb
},10,someString,someObject);
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

116/223

5/30/2015

JavaScripttutorial

Clearingtimeoutsandintervals
Youcancancelatimeoutorintervalbycallingtherelevant clearTimeoutor clearIntervalmethod,
passing it a reference to the interval object. The code specified in the timer will not be run. In this
example, an interval timer will be set to fire once every second (it will perform a useless task of
incrementinganumber,justasanexample),andatimeoutwillbesettocanceltheintervalafter3.5
seconds:
varmyInterval=window.setInterval(function(a,b){
myNumber++;
},1000);
window.setTimeout(function(a,b){
clearInterval(myInterval);
},3500);

You can obtain the timeout object in the same way as shown here for the interval, and you can
cancelitinthesameway,usingclearTimeout.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

117/223

5/30/2015

JavaScripttutorial

Usingcookies

Cookiesarevariablesthatcanbestoredonauser'scomputerandbepickedupbyanyotherweb
pagesinthecorrectdomainandpath.Cookiesaresettoexpireafteracertainlengthoftime.They
arelimitedtostoringstringvaluesonly.
Bewarnedthatmanyusers(includingme)willnotpermitcookiesontheircomputers.Donotmake
yourwebsitesrelyonthem.Thereasonforthisisthatmanywebsitesonlyusecookiesaspartof
adverttracingsystems,whichtheyusetotrackyourmovementaroundtheInternet.Iwouldnotwant
anyone to follow me around a city while I was shopping, taking notes of every shop I visit and
whetherIlookinthelingeriesection,asthatwouldbeaninvasionofmyprivacy.Manypeoplefeel
thesameappliestotheInternet.Youmayfindithelpstofirstlydisplayamessagesayingwhatyou
are going to use the cookie for, for example to store a username and password for the next time
theyvisitthesite.
NotealsothatEuropeanlawrequiressitestogainexplicitpermissionbeforeusingcookies,unless
thosecookiesareessentialtotheoperationofthesite(suchasashoppingbasket).
Somebrowserswillhavealimittohowmanycookiestheycanstore,usually300cookiesormore,of
whichtheremaybe20cookiesperdomainname.Atotalof4KB(afterencoding)ofcookiescanbe
storedforanydomainorpath.
The document.cookie object is a string representation of all cookies available to the current web
page.Thedocument.cookieobjectissomewhatunusualinthatwhenyouassignstringvaluestoit,it
doesnotbecomethevaluethatyouassigntoit.Instead,ittakesapartofthatvalueandappends
itscurrentvaluetothat,somakingastringcontainingseveralpairsofvariableName=variableValue.

Creating/modifyinganddeletingcookies
Ihavealsowrittenacookiescripttohandleallofthisforyou.
Cookiesarecreatedormodifiedbyassigninganame=valuepairtothedocument.cookieobject:
document.cookie=cookieString;

The cookieString is more than just a single value. As well as a value, it can contain other
information,suchaswhenyouwantthecookietoexpire,andwhatfilepathsitshouldapplyto.Any
of these values that you want to specify should be put together in a string as
keyword=value;keyword=value;etc. and assigned as a single string to document.cookie. Only the

cookienameandvaluearerequired,allothervaluesareoptional.Theformatofacompletecookie
stringis:
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

118/223

5/30/2015

JavaScripttutorial

cookieName=cookieValue[;expires=dataAsString[;path=pathAsString[;domain=domainAsString[;secure]]]]

Thisisanexampleofhowtosetacookiecalled mycookie,andassigningitavalueof hello,withan


expirydateof17December2010,at10:00inthemorning:
document.cookie='mycookie=hello;expires=Fri,17Dec201010:00:00GMT';

cookieNameandcookieValue
Thesearestrings,andmustbeURLencoded.Theyandcancontainanycharacters.ToURL
encodea cookie name or value, you can use the escape method. Unfortunately, this cannot
cope with unicode characters. Newer browsers will also provide the encodeURIComponent
method that is able to cope with unicode, but if you use this, you will lose support for older
browsers.
expires
This must be written in full. The Date.toGMTString() method can return dates in the correct
formatforyou.Forexample:
vartheDate=newDate();
varoneYearLater=newDate(theDate.getTime()+31536000000);
varexpiryDate=oneYearLater.toGMTString();

Once the specified date is reached, the cookie expires and is deleted. If expires is not
specified,thecookiewillbedeletedwhenthebrowserisclosed.Ifexpiresissettoadatein
the past, the cookie is deleted immediately. This is how to delete a cookie (some browsers
maytakeafewsecondstoactuallydeletethecookie).Intheory,computersshouldbeableto
accept any future date but in reality, UNIX computers will not currently accept a date after
03:14 on 18 Jan 2038 and many Macintosh computers will not currently accept a date after
06:28 6 Feb 2040 or the same date as that for UNIX. These are the UNIX and Macintosh
equivalentofthemillenniumbug.
path
Thisgivesthepathordirectoriesthatthecookieshouldbeaccessiblefrom.Thedefaultisthe
current path. Alter this using '../' (up one directory), '/' starting at the base directory and
'subdirectoryName/' to start from the 'currentDirectory/subdirectoryName/'. NOTE, if two
cookiesaresetwiththesamenamebutdifferentpaths,bothcookieswillbepermitted.Ifthe
script is in a directory where both those paths are satisfied, both cookies are available, and
may be returned in any order. There is no way to distinguish between them. This can make
scriptsdifficulttowritesobecareful!
domain
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

119/223

5/30/2015

JavaScripttutorial

gives the domain that the cookie is accessible from. The default is the current domain. The
rules reguarding what may be put here were originally written very strictly. Domain names
ending in com, edu, net, org, gov, mil, and int must contain at least 2 '.' characters (eg.
www.google.com). Any other domain names must contain at least 3 '.' characters (eg.
www.howtocreate.co.uk).Thedomainshouldonlybethecurrentdomainorasubdomainofit.

Manybrowserswillnowacceptanyvaliddomainname.
secure
Having this written means the cookie is only accessible on sites with a secure (https)
connection.

Readingcookies
Whendocument.cookieisusedtoretrievecookies,theyarereturnedinthefollowingformat:
cookieName4=value;cookieName3=value;cookieName2=value;cookieName1=value

Notethatthefinalvariablevaluedoesnotendwithasemicolon.Ifthereisnovalueforavariable,
some browsers will give 'cookieName=' but some will only give 'cookieName'. Cookies are only
availablethroughthe document.cookieobjectandcannotbeaccessedbysimplytypingtheirname
(unlessyouretrievethecookieanddefinethatasavariableyourself).
When trying to retrieve values from this string, it is important to ensure that you do not mistake
cookiesforeachother.Forexample,whensearchingfor'myname'itisimportantthatyoudonotfind
a cookie called 'notmyname' or 'mynamehere'. There are many scripts that get this wrong, but the
algorithmIwillshowyoubelowdoesnotmakethesemistakes.
The simple way to do this is to use the split method, to split on the cookie separation value '; '
(including the space). This will return an array of strings, each of which represents a name=value
pair.Youcanthenusea'for'looptocyclethroughallthearraycells,splittingeachofthemonthe'='
string.Thisreturnsanarraycontainingoneortwocells.Thefirstwillbethecookiename,andthe
second(ifitexists)willbethecookievalue.
Use either the unescape or decodeURIComponent methods to decode the contents of the first cell,
containing the cookie name. If that matches the desired name, then you have found the correct
cookie.Useif(!arrayname[1])tocheckifthesecondcellhasavalue.Ifnot,thecookie'svalueisan
empty string. If it does have a value, then you can decode it to work out what it is. You can then
breakoutofthe'for'loop.
Ifyoureachtheendofthefirstarraywithoutdiscoveringtherequiredcookie,thenthecookiedoes
notexist.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

120/223

5/30/2015

JavaScripttutorial

Security

JavaScriptisdesignedasanopenscriptinglanguage.Itisnotintendedtoreplacepropersecurity
measures,andshouldneverbeusedinplaceofproperencryption.Seealsomyarticleaboutcross
sitescripting.
JavaScripthasitsownsecuritymodel,butthisisnotdesignedtoprotecttheWebsiteownerorthe
data passed between the browser and the server. The security model is designed to protect the
user from malicious Web sites, and as a result, it enforces strict limits on what the page author is
allowedtodo.Theymayhavecontrolovertheirownpageinsidethebrowser,butthatiswheretheir
abilitiesend.
JavaScriptscannotreadorwritefilesonusers'computers(FileAPInotcurrentlysupportedby
many browsers allows files to be read by scripts if the user specifically chooses to allow it),
thoughtheycancausethebrowsertoloadremotepagesandresourceslikescriptsorimages,
whichthebrowsermaychoosetocachelocally.Theycannotcreatefilesontheserver(exceptby
communicatingwithaserversidescriptthatcreatesfilesforthem).Theonlythingtheycanstore
on the user's computer are cookies (and WebStorage similar to cookies but with more data
typesinnewerbrowsers).
They are allowed to interact with other pages in a frameset, if those frames originate from the
same Web site, but not if they originate from another Web site (the postMessage method from
HTML5doessafelyextendthiscapability,butIwillnotcoverthathere).Somebrowserswilleven
treatdifferentportnumbersonthesameserverasadifferentWebsite.
JavaScriptcannotbeusedtosetthevalueattributeofafileinput,andwillnotbeallowedtouse
themtouploadfileswithoutpermission.
JavaScript cannot read what locations a user has visited by reading them from the location
object,althoughitcantellthebrowsertojumpbackorforwardanynumberofstepsthroughthe
browserhistory.ItcannotseewhatotherWebpagestheuserhasopen.
JavaScriptcannotaccessthecookiesorvariablesfromothersites.
Itcannotseewhentheuserinteractswithotherprograms,orotherpartsofthebrowserwindow.
It cannot open windows out of sight from the user or too small for the user to see, and in most
browsers,itcannotclosewindowsthatitdidnotopen.
MostpeoplewhowanttoknowaboutsecuritywithJavaScriptareinterestedinproducingpassword
protected pages or sending encrypted data to or from the user's computer. For true security, use
SSL/TLS(HTTPS)andputallofyourchecksontheserver.Youcouldalsouseasecuritylockoutif
too many false attempts are made, preventing brute force cracks. JavaScript cannot replace this
functionality. The problem lies in the fact that if a person can read what you are sending over the
internet, they can also rewrite it. So when you think you are filling in a password to access a
protectedpage,theyhavechangeditsothatyouareactuallyfillinginapasswordthatwillbesentto
them.ThisrequiresSSLtobesurethatyouareprotected.Still,thistutorialisaboutJavaScript,soI
willnowshowyouwhatcanandcannotbedonewithJavaScript.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

121/223

5/30/2015

JavaScripttutorial

Protectingthesourceofyourscripts
Ohdear.Thisisjustnotpossible.Manypeoplemakefutileattemptstodoso,buttobehonest,there
is no point in trying. In fact, in many developers' opinions, there is no such thing as copyright with
JavaScript,althoughitistheoreticallypossible.Thepointwithcopyrightandpatentsisthatyoucan
onlycopyrightorpatentsomethingcompletelynew,anewinnovation,somethingthathasnotbeen
doneorwrittenbefore.YoucanalmostguaranteethatnothingyoudowithJavaScriptwillbeanew
innovationorevennewlywritten.Someonewillhavedoneitbefore,almostcertainlyusingtheexact
same algorithm with just a few variable names changed. JavaScript is just not designed for
innovativeprogrammingsinceitjustusesAPIsdesignedbysomeoneelsetodowhatyouaredoing,
andtheyalreadycameupwithitbeforeyouinordertoinventtheAPI.Evenifyouwritesomethingin
a "new" way, it will still be doing something that has already been done, and if you did attempt to
takethingstoofarandtakethemattertocourt,youwouldjustbelaughedbackoutofitagain.
Asforprotectingwhatyousend,JavaScriptispassedintext,notcompiledtoabinaryfirst,sothe
code is always visible. How can you stop people seeing the source when you are sending the
sourcetoeachviewer?Letmewalkthroughtheproblem.
IfthesourceoftheJavaScriptisheldinthepageyouareviewing,asimple"viewsource"willshow
you the script. Looking in the browser's cache will show the scripts that are in header files. Of
courseyouneedtocheckthesourcefirsttofindthenameoftheheaderfile.
Manydevelopershavespottedthefactthatbothofthesemethodsrequirethe"viewsource"tobe
available, so they prevent the viewer from viewing the source. They do this by preventing the
context menu from appearing when the user right clicks and by removing menus by using
window.openetc.Believeme,bothoftheseareuseless.Youcannotstoprightclicksinallbrowsers

(eveninsomewhereyoucan,theusercanpreventscriptsfromblockingit).Sosomepeopletryto
preventthesebrowsersfromviewingthepagebyusingbrowsersniffing.Thisisequallyuneffective.
Alltheviewerhastodoisswichoffscriptwhentheygettothepage,orviewthesourceofprevious
pages to find the location of the protected page. In adition, Opera, Mozilla/Firefox, Safari and
Internet Explorer are all capable of running user scripts that allow the user to override restrictions
madebythepage.
Some people even try to make sure that the page is only delivered if a referrer header is sent to
make sure that the user came from the right page, and is not attempting to type in a location
manually. So the user can use Curl, a program that allows them to request a page with referrer
header,cookies,formfieldsetc.,andsavethedownloadtoatextfile.
SomepeopletrytoencodethescriptusingcharCodeAtorescape,butasthedecodingtechniqueis
providedinthepage,onlysimplemodificationsarerequiredtomakethescriptappearintext,notas
embedded script. I have seen one set of scripts that have been "protected" by changing their
variable names to completely incomprehensible names, and adding several redundant lines of
incompressiblecodeandremovingallredundantspacesandlinebreaks.Itdoesnottaketoomuch
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

122/223

5/30/2015

JavaScripttutorial

worktoturnthisbackintounderstandablecode.
Youmaywanttoprotectyourcode,butitsimplyisnotpossible.Someonewhoisdeterminedwillbe
abletofinditout.

Passwordprotectingafile
It is best to do this with a server side script, and an encrypted connection. But since this is
JavaScript...
Take the following for example. I want to only allow someone to access my page if they put in the
correctpassword.Iwanttoprovideaboxforthemtowriteit,andthenIwanttotestifitiscorrect.If
it is, I let them view the page. The problem is that in the source of the page, I have to write the
passwordinthescripttotestwhattheyhavewritten.Forexample:
if(document.forms[0].elements[0].value=='mypassword'){
location.href='protectedpage.html';
}

As described in the above section, you cannot protect the source of a page, especially from
someone who is really determined. There is no point in trying. Once a user managed to see the
source,theycouldseethepasswordortheURLinplaintext,orencoded,butagain,thatiseasyto
break.
Forsimplesecurity,trythistechnique.NamethefiletobeprotectedwhateverYourPasswordIs.html
andmakesurethereisanindex.htmlfileinthesamedirectory.Nowusethefollowing:
<formaction=""onsubmit="location.href=this.elements[0].value+'.html';returnfalse;">
<inputtype="text">
<inputtype="submit"value="Submit">
</form>

TheproblemwiththistechniqueisthatthepageisstillpassedinplaintextacrosstheInternet,asis
thenameofthepagethatyousend.IfanyoneissnoopingatdatapacketsontheInternet,theycan
retrievethepage'scontents.Inmanyplaces,packetsnoopingisillegal,butthatdoesnotmeanthat
noonedoesit.
Thisprotectiontechniqueisknownassecuritybyobscurity,inotherwords,itisonlysecurebecause
nooneknowsitisthere.Ifsomeonewasdetermined,theywouldfindit.
Asamorecomplicatedsolution,trycreatingyourownencryptiontechniquethatusesapasswordas
anencryptionkey.Encryptthecontentsofthefile.Asthepageloads,use window.prompttoaskthe
user for a key. Try decrypting the page with their key, using document.write to write the page. If
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

123/223

5/30/2015

JavaScripttutorial

yourtechniqueisgoodenough,wrongpasswordswouldonlyproduceanincomprehensibleoutput.
Withthistechnique,thepasswordisnevertransmittedovertheinternetinplaintext,andneitheris
the content. This technique could be cracked by brute force, trying every possible password until
something works. Better passwords and encryption algorithms will help, but if someone was
determined,theywouldbreakit.OneofmyreadershassubmittedascripttodothisbasedonRC4
andBase64.
I have used both of these techniques, but never for anything really worth protecting. If you have
something worth protecting, it is worth protecting properly serverside, with an encrypted
connection.

Encryptingdatabeforeitissenttoyou
Normally,thiscannotbedonewithJavaScriptusingtheInternetalone,andshouldalwaysbedone
properlyusingaproperSSLconnection.
Youcan,intheory,encrypttextattheuser'sendandunencryptitatyourend.Theproblemisthat
theuserhastoencryptitwithapasswordthatyouknowsothatyoucanunencryptit.Theywould
havetotellyoubytelephoneorpost.Alternatively,youcouldputthepasswordinthesourceofthe
pageandgetthefunctiontoencryptusingthatkey.Butthispasswordwouldhavetobesentover
theinternetinplaintext.Evenifyoudidencodeit,itwouldnotbetoomuchworkforasnooperto
crack it. In fact, the encryption could even be broken with brute force techniques. So what do you
do?
The best possible technique that could be done with JavaScript alone would be to create a
symmetric encryption key using a twin public/private key pair as with techniques such as Diffie
HellmanorSSL,oruseanasymetricpublic/privatekeypairandencryptiontechniqueaswithPGP
orRSA. The problem is that in order to prevent brute force cracking techniques, these require the
browsertohandlenumbersashighas2x10 600orhigher.JavaScriptisjustnotnativelycapableof
working with numbers as high as this. As yet, I have found no solution to this, although on
http://shopjs.sourceforge.net/ there is an algorithm for emulating large number handling, and an
exampleofJavaScriptpoweredRSA.Thetechniqueseemstoworkandtakesonlyafewsecondsto
create keys, by using complex mathematics and algorithms (look at the source of crypto.js) to
emulatelargenumberhandling.
Evenso,ifdoingtheequivalentofRSA(etc.),itisstillnotpossiblefortheusertoverifyyouridentity
as with SSL certificates, so it would be possible for a third party to inject their own code and have
the information sent to them instead, without the user's knowledge. For the best security, stick to
realSSL.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

124/223

5/30/2015

JavaScripttutorial

Protectingyouremailaddress
This is one of the very useful things that JavaScript can do. For those that don't understand the
problem, I will summarise. Search engines "crawl" the Internet, following the links in pages and
requesting other ones so that they can add the pages to their search databases. Using the same
technology,spammerscrawltheInternetlookingforemailaddresses,whetherinmailto:linksorjust
writtenonthepage.Theseemailharvestersareoneofthemostannoyingusesofotherwiseuseful
technologies.
Simplywritingyouremailaddressonanywebpage(throughnewsgrouppostingsetc)canleaveyou
floodedwithunsolicitedemails.Manypeoplefallintothetrapofreplyingtotheseemailsaskingtobe
removed from the mailing list, and succeed only in confirming that their email address is valid. The
problem is that you may actually want your email address on the page, or a link that automatically
opensupanewemailtoyou.Thereareacoupleofstepsyoucantaketopreventtheproblemswith
unsolicitedemails:
Use a throwaway email address like a Gmail, Yahoo or Hotmail account when posting to
newsgroups,signingonlineguestbooks,orwritingyouremailaddressonyourWebpages.That
way, when you start to get too much spam on that email address, you can just dispose of that
emailaccount,andgetanewone.
If you can, tell your email client (program) not to send readconfirmations when you read your
emails.Thiswayyouremailclientdoesnotautomaticallyconfirmyouremailaddress.
Becarefulwhensettingupautoreplies.
When

you

post

your

email

address,

myName@REMOVE_THISmydomain.com

or

change

it

something

to

read
more

something

like

obvious

like

myName(replacewith@symbol)mydomain.comandhopethatanyonewholegitimatelyrepliesto
itworksoutwhattheyneedtodototurnitbackintoaproperemailaddress.Theproblemisthat
not all of them understand this, and don't understand why the email adress does not just work.
So,youcantrythenextpointaswell:
UseJavaScript.How?Readon!

UsingJavaScripttowriteyouremailaddress
I have never heard of an email harvester that is clever enough to interpret JavaScript, though it is
possible. All they usually do is read the text that makes up the page. So if you write your email
address with JavaScript, they will not be able to read it. Remember that if you write the email
addressasasingleword,evenintheJavaScript,theymaystillinterpretitasanemailaddress,soit
helpstobreakitupalittle:
vartheName='myEmailName',theDomain='myEmailDomain.com';
document.write('Myemailaddressis'+theName+'@'+theDomain);
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

125/223

5/30/2015

JavaScripttutorial

Thisoutputs:[email protected]
Youcanalsouseamailtolink:
vartheName='myEmailName',theDomain='myEmailDomain.com';
document.write('<ahref="mailto:'+theName+'@'+theDomain+'">Contactme<\/a>');

Thisoutputs:Contactme
Youcouldevenuseacombinationofboth:
vartheName='myEmailName',theDomain='myEmailDomain.com';
document.write('<ahref="mailto:'+theName+'@'+theDomain+'">'+theName+'@'+
theDomain+'<\/a>');

Thisoutputs:[email protected]
There is, however, a problem with this approach. It relies on your viewers having JavaScript
enabled. Many of your more webaware viewers will not. In my case, these are often likely to be
people who I want to contact me. Fortunately, these viewers are the ones who are likely to
understandwhattochangeifyoutellthemtoasIhaveshowedabove(inthebulletpoints).So,you
canuseacombinationofbothapproaches:
<scripttype="text/javascript">
vartheName='myEmailName',theDomain='myEmailDomain.com';
document.write('<p><ahref="mailto:'+theName+'@'+theDomain+'">'+theName+'@'+
theDomain+'<\/a><\/p>');
</script>
<noscript>
<p><ahref="mailto:myEmailName(replacewith@symbol)myEmailDomain.com">
myEmailName(replacewith@symbol)myEmailDomain.com</a></p>
</noscript>

Inyourbrowser,thisoutputs:
[email protected]

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

126/223

5/30/2015

JavaScripttutorial

Semicolons

Foruseofthesemicoloninthe'for'loop,seethesectiononcontrolstructures.
If you have managed to get through this whole thing and still not worked out where to put
semicolons, here's how to work out where to put them. The basic idea of semicolons is to tell the
browserthatyouhavejustfinishedacommand.Youactuallydon'tneedthematallifyouputeach
instructiononadifferentline(withsomeexceptionsdiscussedbelow)butitisgoodpracticetoput
theminanyway.
It is easier to remember where not to put them. Don't put them immediately after a { or } except
whencreatingobjectswiththe {}syntaxorfunctionswiththe name = function () {}syntax.Don't
putthemonanotherwiseblankline.Donotputtwoinarow.Ifyouwriteacommandorinstruction,
youshouldputasemicolon.
Theseareexamplesofwhereyoushouldputasemicolon:
varmyvariable='sugar';
document.myform.submit();
document['myimage'].src=myStoredImage.src;

Andtheseareexamplesofwhereyoushouldnotputasemicolon:

if(x<5);{
x++;
}

if(x<5;){
x++;
}

if(x<5){;
x++;
}

if(x<5){
x++;
};

if(x<5){
x++;;
}
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

127/223

5/30/2015

JavaScripttutorial

Therearesomesituationswhereitisveryimportanttoincludeasemicolonbeforealinebreak,even
though it may appear to be optional. These occur when the command ends with a variable or
function reference, and the first character in the next command is a left parenthesis or square
bracket:
varb=7
vara=3+b
(otherwindow?otherwindow.document:document).write('complete')

WhatwillhappenisthattheJavaScriptenginewillassumetheparenthesisorsquarebracketrelates
to the previous command instead of being a new command, and will attempt to run the previous
commandasafunction(orreferenceitspropertiesinthecaseofsquarebrackets),andwillpassit
theresultoftheexpressioninsidetheparenthesesasaparametertoit.Thatmakesitequivalentto
this:
varb=7
vara=3+b(otherwindow?otherwindow.document:document).write('complete')

Thatcouldalsobeexpressedasthis:
varb=7
varfoo=otherwindow?otherwindow.document:document
varbar=b(foo)
vara=3+bar.write('complete')

In this case, it will produce errors, but there are some cases where it can, in fact, produce a real
output,thatismeaningless,andtheproblemisveryhardtotrackdown.Therearealsomanyother
less obvious situations where the same effect can occur without even appearing to be a variable
reference on the preceding command (such as where the previous command was assigning an
anonymousfunctiontoavariable).Forthisreason,itisusefultoalwaysusesemicolonswhenthey
areoptional,asitremovestheambiguity:
varb=7;
vara=3+b;
(otherwindow?otherwindow.document:document).write('complete');

The basic way the script interpreter works is that if there is no semicolon, it will continue scanning
thenextline,andifitseessomethingatthestartofitthatcannotpossiblybeapartofthecommand
on the previous line, then it will assume you forgot to insert a semicolon, and it will effectively put
onethereforyou.Ifitcanbepartofthelastcommand,itwillassumeitispartofthelastcommand.
Operatorsandpropertyreferencesareanobviousexampleofwhatwillbeallowedtocontinuethe
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

128/223

5/30/2015

JavaScripttutorial

lastcommand.
Thiscansometimesbeusedtoyouradvantage,tokeepthingsneatandreadable.However,itcan
alsotripyouupifyouareunpreparedforit,asshownabove.Asanexampleofthisbeingtakento
theextreme,takethefollowingcode,whichusesnosemicolonsatall,andletsthescriptinterpreter
attempttoworkoutwherethecommandsstartandend:
<p>I</p>
<scripttype="text/javascript">
var
myP
=
document
.
//comment
getElementsByTagName
/*another
comment*/
(
'p'
)
[
0
]
.
innerHTML
+
'was'
alert
(
myP
+
[
'here'
,
'there'
]
[
0
]
)
</script>

Functionally,thatisidenticaltothis:
<p>I</p>
<scripttype="text/javascript">
varmyP=document.getElementsByTagName('p')[0].innerHTML+'was';
alert(myP+['here','there'][0]);
</script>

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

129/223

5/30/2015

JavaScripttutorial

TheJavaScriptobject

Thispagegivesalistofobjects,properties,collectionsandmethodsfordocumentsandJavaScript
components.Thisviewofallpropertiesavailablefromtherespectiveelementtypesisreferredtoas
theJavaScriptobject.
Some browsers may provide aditional properties or methods but as this stage of the tutorial is
intended to teach you how to program so that your scripts work in all the possible (so called 4 th
generation)browsers,Ihavegiventhosethatareavailableinallpossiblebrowsersorthosewhich
haveanalternative,whichIwillalsohavegiven.ThisisthelastchapterofthistutorialwhereIwill
deal with such a wide range of browsers. In the next few chapters, I will abandon 4 th generation
browsers,andmoveontothemuchmoreadvancedDOMbrowsers(alsoknownas5 thgeneration
browsers).

Contents
Standarddocumentcomponentsalladdressablecomponentsofawebpage.
Positionedelementsalladdressablecomponentsofanabsolutelypositioneddiv.
Eventobjectsallaccessibleinformationaboutanevent.
Intrinsicobjectsvariabletypeswithconstructors.
Array
Boolean
Date
Function
Image
Number
Object
Option
RegularExpression
String

Key
Parentobject
Childobject
Childproperty
Childobjectbeingaccessedthroughacollection[]
Event
Method()
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

130/223

5/30/2015

JavaScripttutorial

Foritemswrittenintheformat:'methodName([someOtherStuff])',someOtherStuffisoptionalanddoes
not need to be written. The [] brackets must be removed. For items written in the format
'methodName(typevarName)','type'givesthetypeofvariableexpectedbythemethodorcollection,

calledvarNameinthiscase.
To use this structure to refer to any object, property, collection or method, treat each new branch
levelasanewchildlevel.Forexample:
window.document.nameOfForm.nameOfInput.defaultValue='Iloveit';

Note,allcollectionsalsohavethe lengthattribute.Alsonote, windowisoftenomittedwhenreferring


tochildobjects.

Standarddocumentcomponents
windoworselfReferstotheglobalobjectofthecurrentWebpagereadonly
ArrayOnlyusefulasaconstructorreadonly
BooleanOnlyusefulasaconstructorreadonly
closedThiswillbetrueifthewindowisclosed(usedwithwindow.open())readonly
DateMostlyusefulasaconstructorreadonly
parse(stringdateAsAString)Date.parse(stringdateAsAString)convertsastringintoaUNIX
timestamp(milli)Acceptsalmostanyvaliddateand/ortimestringformat
defaultStatusReferstothedefaultmessagedisplayedinthestatusbarSomebrowsersallow
userstodisabletheabilitytowritetothistoolbarreadwrite
documentwindowObject.documentreferstothecurrentdocumentInapositionedelement
usinglayerssyntax,positionedElementObject.documentreferstothebodyofthepositioned
elementreadonly
bgColorReferstothedefaultbackgroundcolourofthedocumentreadwriteLayers
browsersonlyForcrossbrowserscripting,seealsodocument.body.style.backgroundColor
document.documentElement.style.backgroundColor
bodyHoldsinformationabouttheBODYelementofthecurrentPageThisobjectmayexist
withoutanyofitspropertiesexistingreadonlyNonlayersbrowsersonly
clientHeightRepresentstheheightoftheinsideofthebrowserwindowinpixelsInmost
browsersinstrictmode,itrepresentstheheightofthedocumentareareadonlyNon
layersbrowsersonlyForcrossbrowserscripting,seealsowindow.innerHeight
document.documentElement.clientHeight
clientWidthRepresentsthewidthoftheinsideofthebrowserwindowinpixelsInmost
browsersinstrictmode,itrepresentsthewidthofthedocumentareareadonlyNon
layersbrowsersonlyForcrossbrowserscripting,seealsowindow.innerWidth
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

131/223

5/30/2015

JavaScripttutorial

document.documentElement.clientWdth
scrollLeftRepresentsthehorizontalscrollingofthedocumentinpixelsSomebrowsers
willgive0iftheyarecurrentlyprovidingthescrollingoffsetvia
document.documentElement.scrollLeftreadonlyNonlayersbrowsersonlyFor
crossbrowserscripting,seealsowindow.pageXOffset
document.documentElement.scrollLeft
scrollTopRepresentstheverticalscrollingofthedocumentinpixelsSomebrowserswill
give0iftheyarecurrentlyprovidingthescrollingoffsetvia
document.documentElement.scrollTopreadonlyNonlayersbrowsersonlyFor
crossbrowserscripting,seealsowindow.pageYOffset
document.documentElement.scrollTop
styleIfavailable,thisreferstothestyleoftheBODYelementreadonly
backgroundReferstothedefaultbackgroundstyleoftheBODYequivalentto
backgroundColorinOpera6NotavailableinOpera5readwriteNonlayers
browsersonlyForcrossbrowserscripting,seealsodocument.bgColor
document.documentElement.style.background
backgroundColorReferstothedefaultbackgroundcolouroftheBODYNotavailablein
Opera5readwriteNonlayersbrowsersonlyForcrossbrowserscripting,see
alsodocument.bgColordocument.documentElement.style.backgroundColor
colorReferstothedefaultcolourofthetextintheBODYreadwriteNonlayers
browsersonlyForcrossbrowserscripting,seealsodocument.fgColor
document.documentElement.style.color
cookieStringrepresentationofallcookiesavailabletothecurrentwebpageThiscanbe
usedtocreateandreadcookiesreadwrite
documentElementHoldsinformationabouttheHTMLelementofthecurrentpagethisobject
mayexistwithoutanyofitspropertiesexistingreadonlyNonlayersbrowsersonly
clientHeightRepresentstheheightofthedocumentareainpixelsInmostbrowsersin
strictmode,itrepresentstheheightoftheinsideofthebrowserwindowreadonly
NonlayersbrowsersonlyForcrossbrowserscripting,seealsowindow.innerHeight
document.body.clientHeight
clientWidthRepresentsthewidthofthedocumentareainpixelsImostbrowsersinstrict
mode,itrepresentsthewidthoftheinsideofthebrowserwindowreadonlyNon
layersbrowsersonlyForcrossbrowserscripting,seealsowindow.innerWidth
document.body.clientwidth
scrollLeftRepresentsthehorizontalscrollingofthedocumentinpixelsSomebrowsers
willgive0iftheyarecurrentlyprovidingthescrollingoffsetviadocument.body.scrollLeft
readonlyNonlayersbrowsersonlyForcrossbrowserscripting,seealso
window.pageXOffsetdocument.body.scrollLeft
scrollTopRepresentstheverticalscrollingofthedocumentinpixelsSomebrowserswill
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

132/223

5/30/2015

JavaScripttutorial

give0iftheyarecurrentlyprovidingthescrollingoffsetviadocument.body.scrollTop
readonlyNonlayersbrowsersonlyForcrossbrowserscripting,seealso
window.pageYOffsetdocument.body.scrollTop
styleIfavailable,thisreferstothestyleoftheHTMLelementreadonly
backgroundReferstothedefaultbackgroundstyleoftheHTMLelementreadwrite
NonlayersbrowsersonlyForcrossbrowserscripting,seealsodocument.bgColor
document.body.style.background
backgroundColorReferstothedefaultbackgroundcolouroftheHTMLelementread
writeNonlayersbrowsersonlyForcrossbrowserscripting,seealso
document.bgColordocument.body.style.backgroundColor
colorReferstothedefaultcolourofthetextintheHTMLelementreadwriteNon
layersbrowsersonlyForcrossbrowserscripting,seealsodocument.fgColor
document.body.style.color
domainStringrepresentationofthedomainnameholdingthedocumentrepresentationsmay
varyreadwriteinsomebrowsers(allowsrelatedsubdomainstocommunicate)
fgColorReferstothedefaultcolourofthetextinthedocumentreadwritebutbecomes
readonlyafterthedocumenthasloadedLayersbrowsersonlyForcrossbrowser
scripting,seealsodocument.body.style.colordocument.documentElement.style.color
IdOfPositionedElementReferstoapositionedelementinalayersalternativecompatible
browserreadonlyLayersbrowsersonlyForcrossbrowserscripting,seealso
document.layersdocument.alldocument.getElementById
lastModifiedStringrepresentationofthelastmodifieddateofthedocumentRepresentations
mayvaryMaybethecurrentdateortheUNIXepochifnotprovidedreadonly
locationAreferencetowindow.location
nameOfFormReferstoaforminthedocumentreadonly
actionReferstotheactionattributeofaformreadwrite
encodingReferstotheenctypeattributeofaformreadwrite
lengthThenumberofinputsreadonly
methodReferstothemethodattributeofaformreadwrite
nameReferstothenameattributeofaformreadwrite
nameOfInput/textarea/selectornameOfInputsSharingName[intindex]Referstoaninput,
textareaorselectnameOfInputwillnotworkifinputsshareacommonname,butthis
branchdoesgivethechildrenoftheseinputsreferredtousingthe
nameOfInputsSharingNamecollectionnameOfInputsSharingName.lengthgivesnumberof
inputssharingthatname,eg.thenumberofradioinputoptionsreadonly
checkedBoolean:saysifacheckboxorradiobuttonischeckedreadwrite
defaultCheckedBoolean:saysifacheckboxorradiobuttonwillbecheckediftheform
isresetreadwrite
defaultValueReferstothedefaultvalueoftheinputThiswillbeusediftheformis
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

133/223

5/30/2015

JavaScripttutorial

resetSomebrowsersdonotgivethisattributeforbuttonsofanykindDifferent
browsersgivedifferentresponsesforselectinputsdonotrelyonitreadwrite
disabledBoolean:saysiftheinputisdisabled,ifthebrowsersupportsitNetscape4
doesnotsupportitandOpera5willnotchangethevalueoftheattributeunlessthe
pageisrefreshedinbetween(thisbugcancauseproblems)readwrite
formRefersbacktotheformcontainingtheinputreadonly
lengthReferstothenumberofoptionsinaselectinputorthenumberofinputssharing
thatnamereadonly
nameReferstothenameattributeofaninputreadwrite
selectedIndexTheoptionnumbercurrentlyselectedinaselectinput1ifnone
readwriteinallexceptInternetExplorer4
typeReferstothetypeattributeofaninputMaybeinupperorlowercasereadonly
exceptforselectwheretypecanspecifyifsingle('selectone')ormultiple('select
multiple')optionscanbeselected
valueThecurrentvalueofaninputDifferentbrowsersgivedifferentresponsesfor
selectinputsdonotrelyonitreadwrite
options[intnumberOfOptionWithSelectInput]Referstoanoptioninaselectinput
readwriteselectObject.options.lengthgivesthecurrentnumberofoptionsread
writeCreateanewoptionusingoptionObject=newOption(stringtext,stringvalue)
Deleteanoptionbysettingittonull
defaultSelectedBoolean:saysiftheinputistheonethatisselectedwhentheformis
resetreadwrite
indexReferstothenumberoftheoptionreadonly
selectedBoolean:saysiftheoptionisselectedreadwrite
textReferstothevisibletextofanoptionreadwrite
valueReferstothevalueofanoptionreadwrite
onblurFireswhentheinputloosesfocusinputObject.onblur=functionNameread
write
onchangeFireswhenthevalueoftheinputchangesoradifferentoptionisselected
inputObject.onchange=functionNamereadwrite
onclickFireswhentheuserdepressesthenreleasesamousebuttonovertheinputor
iftheinputisactivatedusingthekeyboard(whereasmouseeventpropertiesarenot
provided)inputObject.onclick=functionNamereadwrite
ondblclickFireswhentheuserdepressesthenreleasesamousebuttontwiceinquick
successionovertheinputinputObject.ondblclick=functionNameOldMacbrowsers
(aswellasafewothers)generallydonotdetectthiseventItispossibletoemulatethis
event'sresponseusingacombinationofonclickandwindow.setTimeoutreadwrite
onfocusFireswhentheinputreceivesfocusinputObject.onfocus=functionName
readwrite
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

134/223

5/30/2015

JavaScripttutorial

onkeydownFireswhentheuserpressesakeydownwhiletheinputhasthefocus
inputObject.onkeydown=functionNameSomeversionsofNetscape4donotreactbut
theywillreacttodocument.onkeydownwhiletheinputhasthefocusreadwrite
Returningfalsewillpreventthedefaultkeydown/pressactioninmostbrowsers
onkeypressFireswhentheuserpressesandreleasesakeywhiletheinputhasthe
focusinputObject.onkeypress=functionNameSomeversionsofNetscape4donot
reactbuttheywillreacttodocument.onkeypresswhiletheinputhasthefocusread
writeReturningfalsewillpreventthedefaultkeypressactioninmostbrowsers
onkeyupFireswhentheuserreleasesakeywhiletheinputhasthefocus
inputObject.onkeyup=functionNameSomeversionsofNetscape4donotreactbut
theywillreacttodocument.onkeyupwhiletheinputhasthefocusreadwrite
onmousedownFireswhentheuserdepressesamousebuttonovertheinput
inputObject.onmousedown=functionNamereadwriteReturningfalsefromaright
buttonmousedownwillpreventtherightclickmenufromappearinginsomebrowsers
Somemayneedyoutoreturnfalsefromanoncontextmenueventandsomedonot
detectrightclicks
onmouseupFireswhentheuserreleasesamousebuttonovertheinput
inputObject.onmouseup=functionNamereadwrite
blur()Causestheinputtoloosefocus
focus()Causestheinputtoreceivefocus
select()Causesthetextinatextbasedinputtobeselected
targetReferstothetargetattributeofaformreadwrite
elements[intnumberOfInput]Referstoanonimageinputreadonly
formObject.elements.lengthgivesthenumberofinputsreadonly
onresetFireswhentheformisresetIfyoureturnfalse,theresetwillbecancelledandthe
formwillnotberesetinputObject.onreset=functionNamereadwrite
onsubmitFireswhentheformissubmittedIfyoureturnfalse,thesubmitwillbecancelled
andtheformwillnotbesubmittedinputObject.onreset=functionNamereadwrite
reset()Causestheformtoreset
submit()Causestheformtobesubmitted
nameOfImageReferstoanimagereadonlycreateanewimage(storedincache)using
imageObject=newImage()imageObject.src=stringsrc
borderReferstotheborderofanimagereadwrite
completeBoolean:saysifanimagehascompletedloadingreadonly
heightReferstotheheightofanimagereadwrite
lowsrcReferstothelowsrcofanimagereadwrite
nameReferstothenameofanimagereadwrite(readonlyinsomeoldbrowsers)
srcReferstothesrcofanimagereadwrite
widthReferstothewidthofanimagereadwrite
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

135/223

5/30/2015

JavaScripttutorial

onabortFiresiftheuserabortstheloadingofthatimageimageObject.onabort=
functionNamereadwrite
onerrorFiresiftheimagefailstoloadduetoerrorsintheimagesourceoriftheimage
cannotbelocatedimageObject.onerror=functionNamereadwrite
onloadFiresassoonastheimageloadsimageObject.onload=functionNameSome
browsersdonotfirethiseventforcachedimagesreadwrite
onmousedownFireswhentheuserdepressesamousebuttonovertheimage
imageObject.onmousedown=functionNamereadwriteReturningfalsefromaright
buttonmousedownwillpreventtherightclickmenufromappearinginsomebrowsers
Somemayneedyoutoreturnfalsefromanoncontextmenueventandsomedonotdetect
rightclicks
onmouseupFireswhentheuserreleasesamousebuttonovertheimage
imageObject.onmouseup=functionNamereadwrite
referrerTheURLofthepagethatcontainedalinkthattheuserclickedontogettothispage
representationsmayvarySomebrowserallowuserstodisablethispropertyreadonly
titleReferstothedocumenttitlereadonlyinoldbrowsersreadwriteinnewbrowsers
URLThefulltextofthelocationaswindow.location.hrefexceptreadonlyreadonly
all[stringIdOfElement]ReferstoanelementinaproprietaryDOMcompatiblebrowserSee
PositionedElementreadonlyProprietaryDOMbrowsersonlyForcrossbrowser
scripting,seealsodocument.IdOfPositionedElementdocument.layers
document.getElementById
anchors[intnumberOfATagWithNameDefined]Referstoan<a...>tagwherethename
attributehasbeensetreadonlydocumentObject.anchors.lengthgivesthecurrent
numberofanchorelementswhosenameattributehasbeensetreadonly
nameReferstothenameattributeofananchorreadwrite
offsetLeftThedistancebetweentheleftedgeoftheanchorandtheleftedgeofthe
offsetParentnodeSeethesectiononbrowserspecificreferencingforhowtousethis
readonlyNonlayersbrowsersonlyForcrossbrowserscripting,seealso
anchorObject.x
offsetParentTheoffsetParentnodethismaybedifferentindifferentbrowsersSeethe
sectiononbrowserspecificreferencingforhowtousethisreadonlyNonlayers
browsersonly
offsetTopThedistancebetweenthetopedgeoftheanchorandthetopedgeofthe
offsetParentnodeSeethesectiononbrowserspecificreferencingforhowtousethis
readonlyNonlayersbrowsersonlyForcrossbrowserscripting,seealso
anchorObject.y
xThedistancebetweentheleftedgeoftheanchorandtheleftedgeofthepageread
onlyLayersbrowsersonlyForcrossbrowserscripting,seealsolinkObject.offsetLeft
recursivelywithanchorObject.offsetParent
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

136/223

5/30/2015

JavaScripttutorial

yThedistancebetweenthetopedgeoftheanchorandthetopedgeofthepageread
onlyLayersbrowsersonlyForcrossbrowserscripting,seealsolinkObject.offsetTop
recursivelywithanchorObject.offsetParent
applets[intnumberOfAppletTag]Referstoanappletinthedocumentreadonly
nameOfPublicPropertyAllpublicpropertiesoftheappletareavailablereadonly/read
write
nameOfPublicMethod()Allpublicmethodsoftheappletareavailablereadonly/read
write
embeds[nameOrNumberOfEmbeddedObject]Referstoanembedelementinthedocument
Inmanybrowsers,thisarrayrequiresJavatobeenabledIfthebrowserdoesnothaveJava
enabled,thescriptwillproduceanerrorandwillabortifyouattempttoreferencethisarray
Ifthepluginortheembeddedobjectfailstoload,Netscape4willproduceanerrorifyou
attempttoreferencethecorrespondingcelloftheembedsarrayThisarrayisemptyin
IE/WinandiCab3Seealsodocument.pluginsreadonly
heightReferstotheheightoftheembeddedobjectreadonly
hiddenReferstothehiddenattributeoftheembeddedobjectreadonly
nameReferstothenameoftheembeddedobjectreadonly
pluginspageReferstothepluginspageattributeoftheembeddedobjectreadwrite
srcReferstothesrcoftheembeddedobjectreadwrite
typeReferstothedatatypeoftheembeddedobjectreadonly
unitsReferstotheunitsoftheembeddedobject(usu.'pixels'inNetscapecompatibleor
'px'inInternetExplorercompatible)readonly
widthReferstothewidthofantheembeddedobjectreadonly
onloadFiresassoonastheembeddedobjectloadsembeddedObject.onload=
functionNamereadwrite
nameOfPublicMethod()AllpublicmethodsoftheembeddedobjectareavailableThese
willvarywiththeplugintypeSeethepluginprovider'spagereadonly/readwrite
forms[intnumberOfForm]ReferstoaforminthedocumentChildrenas
window.document.nameOfFormreadonly
images[nameOrNumberOfImage]ReferstoanimageinthedocumentChildrenas
window.document.nameOfImagereadonly
layers[stringIdOfPositionedElement]Referstoapositionedelementinalayerscompatible
browserSeePositionedElementreadonlyLayersbrowsersonlyForcrossbrowser
scripting,seealsodocument.IdOfPositionedElementdocument.all
document.getElementById
links[intnumberOfATagWithHrefDefined]Referstoan<a...>or<area...>tagwherethe
HREFattributehasbeensetreadonlydocumentObject.links.lengthgivesthecurrent
numberofanchororareaelementswhosehrefattributehasbeensetreadonly
hashThepartofthehrefafterthe#symbol(ifthereisone)Thehashsymbolisalso
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

137/223

5/30/2015

JavaScripttutorial

returnedwhenreadingthisThehashsymbolshouldnotbeincludedwhensettingthis
InternetExplorer(Win/Mac),GeckoandiCab3returnablankstringifhashisjust'#'
ICEbrowserreturnstheentirehrefwithoutthehashreadwrite
hostThehostnameandportnumber(ifthereisone)ofthehrefreadwrite
hostnameThehostnameofthehrefreadwrite
hrefThefulltextofthehrefreadwrite
innerTextThevisibletextofthelinkreadonlyProprietaryDOMbrowsersonlyFor
crossbrowserscripting,seealsolinkObject.text
offsetLeftThedistancebetweentheleftedgeofthelinkandtheleftedgeofthe
offsetParentnodeSeethesectiononbrowserspecificreferencingforhowtousethis
readonlyNonlayersbrowsersonlyForcrossbrowserscripting,seealsolinkObject.x
offsetParentTheoffsetParentnodeThismaybedifferentindifferentbrowsersSeethe
sectiononbrowserspecificreferencingforhowtousethisreadonly
offsetTopThedistancebetweenthetopedgeofthelinkandthetopedgeofthe
offsetParentnodeSeethesectiononbrowserspecificreferencingforhowtousethis
readonlyNonlayersbrowsersonlyForcrossbrowserscripting,seealsolinkObject.y
pathnameThepartofthehrefafterthehostnameeg.subdir1/subdir2/file.htmlread
write
portTheportnumber(ifthereisone)readwrite
protocolTheprotocolusedeg.http:readwrite
searchThepartofthehrefafter(andcontaining)the?symbol,ifthereisonereadwrite
targetThetargetofthelinkreadwrite
textThevisibletextofthelinkreadonlyAbuginNetscape4makesthisonly
availableifthenameattributeisnotsetLayersbrowsersonlyForcrossbrowser
scripting,seealsolinkObject.innerText
xThedistancebetweentheleftedgeofthelinkandtheleftedgeofthepagereadonly
AbuginNetscape4makesthisonlyavailableifthenameattributeisnotsetIfitis,use
thexpropertyofthecorrespondinganchorobjectLayersbrowsersonlyForcross
browserscripting,seealsolinkObject.offsetLeftrecursivelywithlinkObject.offsetParent
yThedistancebetweenthetopedgeofthelinkandthetopedgeofthepagereadonly
AbuginNetscape4makesthisonlyavailableifthenameattributeisnotsetIfitis,use
theypropertyofthecorrespondinganchorobjectLayersbrowsersonlyForcross
browserscripting,seealsolinkObject.offsetToprecursivelywithlinkObject.offsetParent
onblurFireswhenthelinkloosesfocusanchorObject.onblur=functionNameread
write
onclickFireswhentheuserdepressesthenreleasesamousebuttonoverthelinkorif
thelinkisactivatedusingthekeyboard(whereasmouseeventpropertiesarenot
provided)linkObject.onclick=functionNamereadwriteReturningfalsefromaclick
willpreventthelinkfrombeingfollowed
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

138/223

5/30/2015

JavaScripttutorial

ondblclickFireswhentheuserdepressesthenreleasesamousebuttontwiceinquick
successionoverthelinklinkObject.ondblclick=functionNameOldMacbrowsers(aswell
asafewothers)generallydonotdetectthiseventItispossibletoemulatethisevent's
responseusingacombinationofonclickandwindow.setTimeoutreadwrite
onfocusFireswhenthelinkreceivesfocusanchorObject.onfocus=functionName
readwrite
onmousedownFireswhentheuserdepressesamousebuttonoverthelink
linkObject.onmousedown=functionNamereadwriteReturningfalsefromaright
buttonmousedownwillpreventtherightclickmenufromappearinginsomebrowsers
Somemayneedyoutoreturnfalsefromanoncontextmenueventandsomedonotdetect
rightclicks
onmousemoveFireswhentheusermovesthemousewhileitisoverthelink
linkObject.onmousemove=functionNameNotavailableinNetscape4readwrite
onmouseoutFireswhentheusermovesthemousefromoverthelinktooffthelink
linkObject.onmouseout=functionNamereadwrite
onmouseoverFireswhentheusermovesthemousefromoffthelinktooverthelink
linkObject.onmouseover=functionNamereadwriteIfyousetthestatususingthis
event,youwillneedtoreturntrue
onmouseupFireswhentheuserreleasesamousebuttonoverthelink
linkObject.onmouseup=functionNamereadwrite
blur()CausesthelinktoloosefocusNotavailableinNetscape4Checkifthemethod
existsbeforeyoutrytouseitif(linkObject.blur){linkObject.blur()}
focus()CausesthelinktoreceivefocusNotavailableinNetscape4Checkifthemethod
existsbeforeyoutrytouseitif(linkObject.focus){linkObject.focus()}
plugins[numberOfObject]Referstoanembedorobjectelementinthedocument
(dependingonwhatissupportedbythebrowser)Inmanybrowsers,thisarrayrequiresJava
tobeenabledIfthebrowserdoesnothaveJavaenabled,thescriptwillproduceanerror
andwillabortifyouattempttoreferencethisarrayIfthepluginortheembeddedobjectfails
toload,Netscape4willproduceanerrorifyouattempttoreferencethecorrespondingcell
oftheembedsarrayThisarrayisemptyinIE/WinandiCab3,anddoesnotexistinolder
Konqueror/Safari/OmniWebInOperaitwillreferenceallobjectandembedtagsevenifthey
arenotbeingusedInMozilla/Firefoxitwillonlycontainobjectsorembedsthathaveactually
loadedpluginsChildrenasfordocument.embedsreadonly
onclickFireswhentheuserdepressesthenreleasesamousebuttonoverthedocument
documentObject.onclick=functionNameLayersbrowserswillrequireyoutouse
captureEventsfirstreadwrite
ondblclickFireswhentheuserdepressesthenreleasesamousebuttontwiceinquick
successionoverthedocumentdocumentObject.ondblclick=functionNameOldMac
browsers(aswellasafewothers)generallydonotdetectthiseventItispossibletoemulate
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

139/223

5/30/2015

JavaScripttutorial

thisevent'sresponseusingacombinationofonclickandwindow.setTimeoutLayers
browserswillrequireyoutousecaptureEventsfirstreadwrite
onkeydownFireswhentheuserpressesakeydownwhilethedocument(butnotaninput)
hasthefocusdocumentObject.onkeydown=functionNameLayersbrowserswillrequire
youtousecaptureEventsfirstreadwrite
onkeypressFireswhentheuserpressesandreleasesakeydownwhilethedocument(but
notaninput)hasthefocusdocumentObject.onkeypress=functionNameLayersbrowsers
willrequireyoutousecaptureEventsfirstreadwrite
onkeyupFireswhentheuserreleasesakeywhilethedocument(butnotaninput)hasthe
focusdocumentObject.onkeyup=functionNameLayersbrowserswillrequireyoutouse
captureEventsfirstreadwrite
onmousedownFireswhentheuserdepressesamousebuttonoverthedocument
documentObject.onmousedown=functionNameLayersbrowserswillrequireyoutouse
captureEventsfirstreadwriteReturningfalsefromarightbuttonmousedownwillprevent
therightclickmenufromappearinginsomebrowsersSomemayneedyoutoreturnfalse
fromanoncontextmenueventandsomedonotdetectrightclicks
onmousemoveFireswhentheusermovesthemousewhileitisoverthedocument
documentObject.onmousemove=functionNameLayersbrowserswillrequireyoutouse
captureEventsfirstreadwrite
onmouseoutFireswhentheusermovesthemousefromoverthedocumenttooffthe
documentdocumentObject.onmouseout=functionNameLayersbrowserswillrequireyou
tousecaptureEventsfirstreadwrite
onmouseoverFireswhentheusermovesthemousefromoffthedocumenttooverthe
documentdocumentObject.onmouseover=functionNameLayersbrowserswillrequire
youtousecaptureEventsfirstreadwrite
onmouseupFireswhentheuserreleasesamousebuttonoverthedocument
documentObject.onmouseup=functionNameLayersbrowserswillrequireyoutouse
captureEventsfirstreadwrite
captureEvents(Event.EventType)Causeslayersbrowserstoreacttoeventssee
window.Eventforwhateventscanbecaptured
close()Saysthatyouhavestoppedrewritingthedocumentcontentsandtheyshouldnowbe
displayed
getElementById(stringIdOfElement)ReturnsareferencetoanelementinaDOM
compatiblebrowserSeePositionedElementreadonlyDOMbrowsersonlyForcross
browserscripting,seealsodocument.IdOfPositionedElementdocument.layers
document.all
open()Saysthatyouareabouttostartrewritingthedocumentcontents
write(stringcontent)Writesdocumentcontent
writeln(stringcontent)Writesalineofdocumentcontent
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

140/223

5/30/2015

JavaScripttutorial

eventIfthebrowsersupportsit,thisholdstheinstantaneousdetailsofaneventSeethesection
oneventobjectsbelowreadonlyProprietaryDOMbrowsersonlyForcrossbrowser
scripting,seealsoeventobjectsusingfirstargument
EventTheeventcaptureobjectprovidedbylayersbrowsersForusewithcapturingevents
SomebrowsersthatsupportDOMeventswillprovidethis,butitservesnousefulpurpose
CLICKFireswhentheuserdepressesthenreleasesamousebuttonovertheelement
readonly
DBLCLICKFireswhentheuserdepressesthenreleasesamousebuttontwiceinquick
successionovertheelementOldMacbrowsers(aswellasafewothers)generallydonot
detectthiseventItispossibletoemulatethisevent'sresponseusingacombinationof
onclickandwindow.setTimeoutreadwrite
KEYDOWNFireswhentheuserpressesakeydownwhiletheelementhasthefocusread
only
KEYPRESSFireswhentheuserpressesthenreleasesakeywhiletheelementhasthefocus
readonly
KEYUPFireswhentheuserreleasesakeywhiletheelementhasthefocusreadonly
MOUSEDOWNFireswhentheuserdepressesamousebuttonovertheelementreadonly
MOUSEMOVEFireswhentheusermovesthemousewhileitisovertheelementreadonly
MOUSEOUTFireswhentheusermovesthemousefromovertheelementtoofftheelement
readonly
MOUSEOVERFireswhentheusermovesthemousefromofftheelementtooverthe
elementreadonly
MOUSEUPFireswhentheuserreleasesamousebuttonovertheelementreadonly
FunctionOnlyusefulasaconstructorreadonly
historyReferstothedocumenthistoryofthebrowserreadonly
back()LoadsthelastdocumentinthebrowserhistoryEquivalenttoclickingthebrowser's
backbutton
forward()LoadsthenextdocumentinthebrowserhistoryEquivalenttoclickingthe
browser'sforwardbutton
go(intnumerToJump)Jumpsforwardthroughthebrowserhistorybythespecifiednumberof
entriesUsevenumbersforpreviousdocuments
ImageOnlyusefulasaconstructorreadonly
innerHeightRepresentstheheightofthedocumentareaofthebrowserinpixelsinmost
browsers(notIE8orIE9+inquirksmode)readonlyNetscapecompatiblebrowsersonly
Forcrossbrowserscripting,seealsodocument.body.clientHeight
document.documentElement.clientHeight
innerWidthRepresentsthewidthofthedocumentareaofthebrowserinpixelsinmost
browsers(notIE8orIE9+inquirksmode)readonlyNetscapecompatiblebrowsersonly
Forcrossbrowserscripting,seealsodocument.body.clientWidth
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

141/223

5/30/2015

JavaScripttutorial

document.documentElement.clientWidth
lengthNumberofframesheldbythecurrentdocumentEquivalenttowindow.frames.length
readonly
locationHoldsinformationaboutthecurrentlocationreadwriteWritingisequivalentto
writinglocation.href
hashThepartofthelocationafterthe#symbol(ifthereisone)Thehashsymbolisalso
returnedwhenreadingthisThehashsymbolshouldnotbeincludedwhensettingthis
InternetExplorer(Win/Mac),GeckoandiCab3returnablankstringifhashisjust'#'
ICEbrowserreturnstheentirehrefwithoutthehashreadwrite
hostThehostnameandportnumber(ifthereisone)ofthelocationInternetExplorer7on
windowsalwaysshowsaportnumber,evenifoneisnotspecifiedinthehref(itdoesnotdo
thiswithlinks)readwrite
hostnameThehostnameofthelocationreadwrite
hrefThefulltextofthelocationreadwrite
pathnameThepartofthelocationafterthehostnameeg./subdir1/subdir2/file.htmlread
write
portTheportnumber(ifthereisone)readwrite
protocolTheprotocolusedeg.http:readwrite
searchThepartofthelocationafter(andcontaining)the?symbol,ifthereisoneread
write
reload([boolforceFullReload])ReloadsthecurrentdocumentifforceFullReloadistrue,the
documentwillbereloadedfromtheserver,notfromcache
replace(stringlocation)LoadsthespecifiedURLreplacingthecurrenthistoryentrytheURL
canberelativeorabsolute
MathAnobjectcontainingmathematicalconstantsandmethodsreadonly
EConstante~=2.718readonly
LN2Constantln(2)~=0.693readonly
LN10Constantln(10)~=2.303readonly
LOG2EConstantlog2(e)~=1.442readonly
LOG10EConstantlog10(e)~=0.434readonly
PIConstantPi~=3.142readonly
SQRT1_2Constant1/sqrt(2)orsqrt(1/2)~=0.707readonly
SQRT2Constantsqrt(2)~=1.414readonly
abs(numbern)Returnstheabsolutevalueofn
acos(numbern)Returns(rads)cos^1ofn
asin(numbern)Returns(rads)sin^1ofn
atan(numbern)Returns(rads)tan^1ofn
atan2(numbern,numberk)Returnstheangle(rads)fromcartesiancoordinates0,0ton,k
ceil(numbern)Returnsnroundeduptothenearestwholenumber
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

142/223

5/30/2015

JavaScripttutorial

cos(numbern)Returnscosn(wherenisinradians)
exp(numbern)Returnsetothepowerofn
floor(numbern)Returnsnroundeddowntothenearestwholenumber
log(numbern)Returnsln(n)
max(numbera,numberb,numberc,.....)Returnsthelargestnumber
min(numbera,numberb,numberc,.....)Rreturnsthesmallestnumber
pow(numbern,numberk)Rturnsntothepowerofk
random()Returnsarandomnumberbetween0and1
round(numbern)Returnsnroundedupordowntothenearestwholenumber
sin(numbern)Returnssinn(wherenisinradians)
sqrt(numbern)Returnsthesquarerootofn
tan(numbern)Returnstann(wherenisinradians)
nameReferstothenameofthecurrentwindowusedby<atarget=...>readwrite
navigatorHoldsinformationabouttheuser'sbrowserreadonly
appCodeNameThecodenameofthebrowserManybrowsersspoofthis,neveruseit
readonly
appNameTheshortnameofthebrowserManybrowsersspoofthis,neveruseitread
only
appVersionTheversionnumberofthebrowserManybrowsersspoofthis,neveruseit
readonly
languageTheuser'schoiceoflanguagefortheirbrowserreadonlyNetscape
compatiblebrowsersonly
platformTheoperatingsystemthebrowserisrunningonManybrowsersspoofthis,never
useitreadonly
userAgentThefullnameofthebrowserManybrowsersspoofthis,neveruseitreadonly
userLanguageTheuser'schoiceoflanguagefortheiroperatingsystemreadonlyIE
compatiblebrowsersonly
mimeTypes[nameOrNumberOfMIMEType]ContainsinformationaboutaMIMEtypesupported
bythebrowserInternetExploreronWindowsjustgivesa0lengtharraysoJustputthe
objectonthepageandtheuserwillbepromptedtodownloadtherelevantpluginiftheydo
notsupportityetreadonly
descriptionThefulldescriptionoftheMIMEtypereadonly
enabledPluginReferstothepluginthatsupportstheMIMEtypechildrenasfor
window.navigator.plugins[nameOrNumberOfPlugin]readonly
suffixesGivesa'commaspace'separatedlistofthefileextensionscoveredbytheMIME
typereadonly
typeGivestheofficialtypenameoftheMIMEtypeeg.image/gifreadonly
plugins[nameOrNumberOfPlugin]ContainsinformationaboutapluginInternetExploreron
Windowsjustgivesa0lengtharraysoJustputtheobjectonthepageandtheuserwillbe
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

143/223

5/30/2015

JavaScripttutorial

promptedtodownloadthepluginiftheydonotsupportityetreadonly
descriptionThefullnameofthepluginreadonly
filenameThefullnameofthepluginfilereadonly
lengthThenumberofMIMEtypessupportedbythepluginreadonly
nameTheshortnameofthepluginreadonly
nameOrNumberOfMIMETypeAreferencetotheassociatedentryinthe
navigator.mimeTypescollectionreadonly
javaEnabled()ReturnsifthebrowsersupportsJava
taintEnabled()ReturnsifthebrowsersupportsdatataintingTaintingisnotsupportedbyany
'4thgeneration'browserssothismethodnolongerservesanypurpose,althoughbrowsers
stillprovideit
NumberContainsunusualconstantsandinformationaboutthebrowser'snumberhandlingCan
alsobeusedasaconstructorreadonly
MAX_VALUENumber.MAX_VALUEisthehighestnumberthatthatbrowseronthatoperating
systemcanrepresentreadonly
MIN_VALUENumber.MIN_VALUEisthesmallestpositivenumberthatthatbrowseronthat
operatingsystemcanrepresentreadonly
NaNNumber.NaNisanonnumberequivalenttoeg.Math.sqrt(1)readonly
NEGATIVE_INFINITYNumber.NEGATIVE_INFINITYisaspecialnumberrepresentingnegative
infinityreadonly
POSITIVE_INFINITYNumber.POSITIVE_INFINITYisaspecialnumberrepresentingpositive
infinityreadonly
ObjectOnlyusefulasaconstructorreadonly
openerReferstothewindowthatusedthewindow.openmethodtoopenthiswindowread
write
OptionOnlyusefulasaconstructorreadonly
outerHeightRepresentstheheightofthebrowserwindowinpixelsinmostbrowsers(notIE8
orIE9+inquirksmode)readonlyThereisnocrossbrowserequivalentItisbesttouse
thisonlytocombatresizeToinconsistencies
outerWidthRepresentsthewidthofthebrowserwindowinpixelsinmostbrowsers(notIE8or
IE9+inquirksmode)readonlyThereisnocrossbrowserequivalentItisbesttousethis
onlytocombatresizeToinconsistencies
pageXOffsetRepresentsthehorizontalscrollingofthedocumentinpixelsinmostbrowsers
(notIE8orIE9+inquirksmode)readwriteNetscapecompatiblebrowsersonlyFor
crossbrowserscripting,seealsodocument.body.scrollLeft
document.documentElement.scrollLeft
pageYOffsetRepresentstheverticalscrollingofthedocumentinpixelsinmostbrowsers(not
IE8orIE9+inquirksmode)readwriteNetscapecompatiblebrowsersonlyForcross
browserscripting,seealsodocument.body.scrollTopdocument.documentElement.scrollTop
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

144/223

5/30/2015

JavaScripttutorial

parentReferstotheparentwindowintheframesetreadonly
RegExpHoldsinformationaboutregularexpressionsearchesSomebrowsersfailtoimplement
thiscorrectly(eg.Opera6andiCab2)readonly
$1...$9RegExp.$1RegExp.$9storethelast9capturematchesfoundduringaregular
expressionsearchreadonly
inputRegExp.inputisthelaststringthataregularexpressionsearchwasperformedagainst
readonly
lastMatchor$&RegExp.lastMatchisthelastsubstringthatfullymatchedaregular
expressionduringamatch,execortestreadonly
lastParenor$+RegExp.lastParenisthelastinstanceofanycaptureduringamatch,execor
testreadonly
leftContextor$`RegExp.leftContextistheleadingsubstringbeforethelastsubstringthat
fullymatchedaregularexpressionduringamatch,execortestreadonly
rightContextor$'RegExp.rightContextisthetrailingsubstringafterthelastsubstringthat
fullymatchedaregularexpressionduringamatch,execortestreadonly
screenHoldsinformationabouttheuser'smonitorreadonly
availHeightTheavailableheightofthemonitorinpixelswhenThesizeofthetaskbaris
takenintoaccountreadonly
availWidthTheavailablewidthofthemonitorinpixelswhenThesizeofthetaskbaristaken
intoaccountreadonly
colorDepthThenumberofbitsperpixelifpixelDepthisnotprovidedreadonlyFor
crossbrowserscripting,seealsopixelDepth
heightTheheightofthemonitorinpixelsreadonly
pixelDepthThenumberofbitsperpixel,ifprovidedreadonlyForcrossbrowser
scripting,seealsocolorDepth
widthThewidthofthemonitorinpixelsreadonly
statusReferstothetextwritteninthestatusbarofthebrowserSomebrowsersallowusersto
disabletheabilitytowritetothistoolbarreadwrite
StringMostlyusefulasaconstructorContainsausefulcharactermethodreadonly
fromCharCode(numberasciiCharacterValue)Returnsthecharacterrepresentedbythe
numerical(ascii)valuereadonly
frames[nameOrNumberOfFrame]Referstoaniframeelementorthewindowobjectofapage
heldintheframesetheldbythispage(youwillneedtouse
window.frames[nameOrNumberOfFrame].windowtoaccessthewindowobjectofthedocument
heldinaniframe)readonlywindowObject.frames.lengthgivesthenumberofframesinthe
framesetheldbythispageNOTE:attemptingtoaccessaframethatdoesnotcontainanHTML
documentorisfromadifferentdomainoraniframethathasnotloadedwillcauseerrorsinmost
browsersreadonly
nameReferstothenameofaframereadwrite
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

145/223

5/30/2015

JavaScripttutorial

onblurFireswhenthewindowloosesfocuswindowObject.onblur=functionNamereadwrite
onerrorFireswhenthescriptproducesanerror.Settingthispreventstheerrordialogbeing
displayedwindowObject.onerror=functionNameorwindowObject.onerror=nullReturning
truewillpreventtheerrorbeingloggedNotavailableinsomebrowsers(likeOpera),souse
try{}catch(e){}insteadreadwrite
onfocusFireswhenthewindowreceivesfocuswindowObject.onfocus=functionNameread
write
onloadFiresassoonasthepageloadswindowObject.onload=functionNameIE4willget
self.onloadwrong(usewindow.onload)readwrite
onunloadFiresjustbeforethepageunloadswindowObject.onunload=functionNameread
write
alert(object)Displaysamessageboxwithatextualrepresentationoftheobject.Iftheobjectis
astring,thestringwillbedisplayed
blur()Causesthewindowtoloosefocus
clearInterval(intervalobject)Stopstheintervalfromfiringagain
clearTimeout(timeoutobject)Stopsthetimeoutfromfiring
close()CausesthewindowtocloseIfthewindowwasnotopenedbyscript,theuserwillbe
askediftheywantthewindowtoclose
confirm(stringmessage)Displaysthemessageandoffers'OK'and'Cancel'buttonsReturns
trueiftheuserchoosesOKandfalseiftheuserchoosesCancel
escape(stringtextToURLEncode)ReturnsthestringURLencodedNotunicodesafe
eval(stringscriptToEvaluate)Evaluatesthetextasascript
focus()Causesthewindowtoreceivefocus
isFinite(numbernumberToCheck)Returnsifthenumberisapropernumberwithafinitevalue
notNaNorInfinityorInfinity
isNaN(numbernumberToCheck)ReturnsifthenumberisNaN(eg.Math.sqrt(1))
moveBy(intxOffset,intyOffset)Movesthebrowserwindowbythespecifiedamount
moveTo(intxPos,intyPos)Movesthebrowserwindowtothespecifiedcoordinate
open(stringurl[,stringtargetName[,stringoptions[,boolreplaceHistoryEntry]]])Opensthe
URLspecifiedwiththesettingsprovidedReturnsareferencetothewindowThetargetNameis
usedby<atarget=...>Optionsisastringcontainingacommaseparatedlistofoption=value
wherevalueisanintegergivingasizeoryesor1toenabletheoptionornoor0todisableit
availableoptionsare:height=intheightofwindowleft=intdistancebetweenleftsideofwindow
andleftsideofscreenlocation=enable/disablemenubar=enable/disable
resizable=enable/disablescrollbars=enable/disablestatus=enable/disable
toolbar=enable/disabletop=intdistancebetweentopofwindowandtopofscreenwidth=int
widthofwindowSomebrowsersmayoffermoreLeaveanyouttoresorttotheirdefaults
parseInt(stringtextContainingAnInteger[,intradix])ReturnstheintegerpartofastringIf
radixisprovided,thenumberwillbeinterpretedinthebaseofthatradix(typically8,10or16)
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

146/223

5/30/2015

JavaScripttutorial

Ifradixisnotprovided,olderbrowserswillautodetectleading'0x'asHex,leading'0'asoctal,
andallothersasdecimal.
parseFloat(stringtextContainingAFloat)Returnsthefloatpartofastring
print()DisplaystheprintdialogboxallowingtheusertoprintthecurrentdocumentNotavailable
insomeolderbrowsers
prompt(stringmessage,stringdefaultValue)Displaysapromptallowingtheusertoinputa
variablevalueReturnstheuserinputtedvalueasastringReturnsnullorundefinediftheuser
choosescancel
resizeBy(intxOffset,intyOffset)Resizesthebrowserwindowbythespecifiedamount
resizeTo(intxWidth,intyWidth)Resizesthebrowserwindowtothespecifiedamount
scrollBy(intxOffset,intyOffset)Scrollsthedocumentbythespecifiedamount
scrollorscrollTo(intxPos,intyPos)Scrollsthedocumenttothespecifiedcoordinate
setInterval(stringorfunctionscriptToEvaluate,inttimeInMilliseconds)Repeatedlywaitsfor
thespecifiedamountoftimebeforeevaluatingthecodespecifiedReturnsanintegerreference
totheintervalobject
setTimeout(stringorfunctionscriptToEvaluate,inttimeInMilliseconds)Waitsforthespecified
amountoftimebeforeevaluatingthecodespecifiedReturnsanintegerreferencetothe
timeoutobject
unescape(stringtextToURLUnEncode)ReturnsthestringURLunencodedNotunicodesafe

Positionedelements
In DOM and proprietary DOM browsers, this could actually be any element, not just one that is
positioned.However,atthisstageofthetutorial,only4 thgenerationDHTMLisbeingdiscussed,and
thereforethisisreferredtoasapositionedelement.Thenextchapterwillshowhowthisappliesto
allelements,notjustthosethatarepositioned.
PositionedElementAdiv(orspan)elementthathasbeenabsolutelypositionedusingstylesheets
Referredtousinganyofdocument.getElementByIddocument.IdOfElementdocument.all
document.layersasabovereadonly
bgColorReferstothedefaultbackgroundcolouroftheelementreadwriteLayersbrowsers
onlyForcrossbrowserscripting,seealsopositionedElement.style.background
positionedElement.style.backgroundColor
clipIfavailable,thisreferstothevisibleareaoftheelementreadonlyLayersbrowsers
onlyForcrossbrowserscripting,seealsopositionedElement.style.clip
bottomThedistancebetweenthetopedgeoftheelementandthestartofthebottomportion
oftheelementthatisnotvisibleinpixels(integer)readwriteLayersbrowsersonly
Forcrossbrowserscripting,seealsopositionedElement.style.clip
leftThesizeoftheleftportionoftheelementthatisnotvisibleinpixels(integer)read
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

147/223

5/30/2015

JavaScripttutorial

writeLayersbrowsersonlyForcrossbrowserscripting,seealso
positionedElement.style.clip
rightThedistancebetweentheleftedgeoftheelementandthestartoftherightportionof
theelementthatisnotvisibleinpixels(integer)readwriteLayersbrowsersonlyFor
crossbrowserscripting,seealsopositionedElement.style.clip
topThesizeofthetopportionoftheelementthatisnotvisibleinpixels(integer)read
writeLayersbrowsersonlyForcrossbrowserscripting,seealso
positionedElement.style.clip
documentInlayersbrowsers,thisreferstothecontentsoftheelement,equivalenttoawhole
newdocument(seewindow.documentforwhatpropertieswillbeavailable)Inmanyother
browsers(suchasOpera),thisisareferencetowindow.documentreadonly
idReferstotheidoftheelementInlayersbrowsers,ifthenameattributeisset,thiswillbethe
nameattributeandthenameattributemustbeusedinsteadwhenreferringtotheelementFor
thisreason,itisbestnottosetthenameattributereadwrite
innerHTMLReferstothecontentsoftheelementaspartofthemaindocumentreadwrite
NonlayersbrowsersonlyForcrossbrowserscripting,seealso
positionedElement.document.open,write,writelnandclose
leftIfavailable,thisisanintegerspecifyingtheleftcoordinateoftheelementreadwrite
LayersbrowsersonlyForcrossbrowserscripting,seealsopositionedElement.style.left
positionedElement.style.pixelLeft(notrequired)
nameReferstothenameoftheelementInlayersbrowsers,ifthenameattributeisset,the
positionedElement.idwillbethenameattributeandthenameattributemustbeusedinstead
whenreferringtotheelementForthisreason,itisbestnottosetthenameattributeread
only
styleIfavailable,thisreferstothestyleoftheelementreadonly
backgroundReferstothedefaultbackgroundcolouroftheelementBrowsersotherthan
Opera5.xmayalsogiveotherinformation,eg.backgroundimagesetc.readwriteNon
layersbrowsersonlyForcrossbrowserscripting,seealsopositionedElement.bgColor
positionedElement.style.backgroundColor
backgroundColorReferstothedefaultbackgroundcolouroftheelementreadwrite
Nonlayersbrowsersonly(notavailableinOpera5.x)Forcrossbrowserscripting,seealso
positionedElement.bgColorpositionedElement.style.background
clipReferstothecoordinatesofthevisibleareaoftheelementinstringformat:
rect(topPos,rightPos,bottomPos,leftPos)Allvaluesshouldbeinpixels(forcompatibility
reasons)readwriteNonlayersbrowsersonlyForcrossbrowserscripting,seealso
childrenofpositionedElement.clip
colorReferstothedefaultcolourofthetextintheelementreadwriteNonlayers
browsersonlyForcrossbrowserscripting,seealsopositionedElement.document.fgColor
heightReferstotheheightoftheelementIntheformat'100px'readwriteNonlayers
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

148/223

5/30/2015

JavaScripttutorial

browsersonlyForcrossbrowserscripting,seealsopositionedElement.resizeTo
positionedElement.pixelHeight
leftReferstotheleftcoordinateoftheelementIntheformat'100px'readwriteNon
layersbrowsersonlyForcrossbrowserscripting,seealsopositionedElement.left
positionedElement.style.pixelLeft(notrequired)
pixelHeightReferstotheheightoftheelementInpixelsasanintegerreadwrite
InternetExplorercompatibleonlyForcrossbrowserscripting,seealso
positionedElement.resizeTopositionedElement.style.height
pixelLeftReferstotheleftcoordinateoftheelementInpixelsasanintegerreadwrite
InternetExplorercompatibleonlyForcrossbrowserscripting,seealso
positionedElement.leftpositionedElement.style.left
pixelTopReferstothetopcoordinateoftheelementInpixelsasanintegerreadwrite
InternetExplorercompatibleonlyForcrossbrowserscripting,seealso
positionedElement.toppositionedElement.style.top
pixelWidthReferstothewidthoftheelementInpixelsasanintegerreadwriteInternet
ExplorercompatibleonlyForcrossbrowserscripting,seealsopositionedElement.resizeTo
positionedElement.style.width
topReferstothetopcoordinateoftheelementIntheformat'100px'readwriteNon
layersbrowsersonlyForcrossbrowserscripting,seealsopositionedElement.top
positionedElement.style.pixelTop(notrequired)
visibilityReferstothevisibilityoftheelementAvailablevaluesare'visible'and'hidden'
readwriteNonlayersbrowsersonlyForcrossbrowserscripting,seealso
positionedElement.visibility
widthReferstothewidthoftheelementIntheformat'100px'readwriteNonlayers
browsersonlyForcrossbrowserscripting,seealsopositionedElement.resizeTo
positionedElement.pixelWidth
zIndexReferstothezindex(stackingorder)oftheelementMustbeapositiveinteger
readwriteNonlayersbrowsersonlyForcrossbrowserscripting,seealso
positionedElement.zIndex
topIfavailable,thisisanintegerspecifyingthetopcoordinateoftheelementreadwrite
LayersbrowsersonlyForcrossbrowserscripting,seealsopositionedElement.style.top
positionedElement.style.pixelTop(notrequired)
visibilityReferstothevisibilityoftheelementAvailablevaluesare'show'and'hide'read
writeforcrossbrowserscripting,seealsopositionedElement.style.visibility
zIndexReferstothezindex(stackingorder)oftheelementMustbeapositiveintegerread
writeLayersbrowsersonlyForcrossbrowserscripting,seealso
positionedElement.style.zIndex
onclickFireswhentheuserdepressesthenreleasesamousebuttonoverthepositioned
elementpositionedElement.onclick=functionNameLayersbrowserswillrequireyoutouse
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

149/223

5/30/2015

JavaScripttutorial

captureEventsfirstreadwrite
ondblclickFireswhentheuserdepressesthenreleasesamousebuttontwiceinquick
successionoverthepositionedelementpositionedElement.ondblclick=functionNameOld
Macbrowsers(aswellasafewothers)generallydonotdetectthiseventItispossibleto
emulatethisevent'sresponseusingacombinationofonclickandwindow.setTimeoutLayers
browserswillrequireyoutousecaptureEventsfirstreadwrite
onkeydownFireswhentheuserpressesakeydownwhilethepositionedelement(butnotan
input)hasthefocuspositionedElement.onkeydown=functionNameLayersbrowserswill
requireyoutousecaptureEventsfirstreadwrite
onkeypressFireswhentheuserpressesandreleasesakeydownwhilethepositionedelement
(butnotaninput)hasthefocuspositionedElement.onkeypress=functionNameLayers
browserswillrequireyoutousecaptureEventsfirstreadwrite
onkeyupFireswhentheuserreleasesakeywhilethepositionedelement(butnotaninput)has
thefocuspositionedElement.onkeyup=functionNameLayersbrowserswillrequireyouto
usecaptureEventsfirstreadwrite
onmousedownFireswhentheuserdepressesamousebuttonoverthepositionedelement
positionedElement.onmousedown=functionNameLayersbrowserswillrequireyoutouse
captureEventsfirstreadwriteReturningfalsefromarightbuttonmousedownwillprevent
therightclickmenufromappearinginsomebrowsersSomemayneedyoutoreturnfalsefrom
anoncontextmenueventandsomedonotdetectrightclicks
onmousemoveFireswhentheusermovesthemousewhileitisoverthepositionedelement
positionedElement.onmousemove=functionNameLayersbrowserswillrequireyoutouse
captureEventsfirstreadwrite
onmouseoutFireswhentheusermovesthemousefromoverthepositionedelementtooffthe
positionedelementpositionedElement.onmouseout=functionNameLayersbrowserswill
requireyoutousecaptureEventsfirstreadwrite
onmouseoverFireswhentheusermovesthemousefromoffthepositionedelementtooverthe
positionedelementpositionedElement.onmouseover=functionNameLayersbrowserswill
requireyoutousecaptureEventsfirstreadwrite
onmouseupFireswhentheuserreleasesamousebuttonoverthepositionedelement
positionedElement.onmouseup=functionNameLayersbrowserswillrequireyoutouse
captureEventsfirstreadwrite
captureEvents(Event.EventType)CauseslayersbrowserstoreacttoeventsSee
window.Eventforwhateventscanbecaptured
resizeTo(intwidth,intheight)Resizesthelayerbychangingthevaluesofclip.bottomand
clip.rightLayersbrowsersonlyForcrossbrowserscripting,seealso
positionedElement.style.widthandpositionedElement.style.height
positionedElement.style.pixelWidthandpositionedElement.style.pixelHeight

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

150/223

5/30/2015

JavaScripttutorial

Eventobjects
window.eventorfirstargumentpassedtohandlerfunctionHoldsrecordsofmousebuttonsor
keysthattriggeredtheeventAvailableiftriggeredby:object.onEventName=
handlerFunctionNameor<elementonEventName="thisIsEquivalentToAHandlerFunction">
readwrite
altKeyBoolean:saysiftheAltkeywaspressedduringtheeventNote:somebrowsersdonot
providethisorthelayerscompatiblemethodofcheckingthesekeysreadonlyNonlayers
browsersonlyForcrossbrowserscripting,seealsoeventObject.modifiers
buttonIfaleftmousebuttontriggeredtheevent,thiswillbe0or1Ifarightmousebutton
triggeredtheevent,thiswillbe2SomebrowsersdonotdetectrightclicksreadonlyNon
layersbrowsersonlyForcrossbrowserscripting,seealsoeventObject.which
clientXIfthemousetriggeredtheevent,thisholdsthehorizontalpositionofthemousePosition
isrelativetothedisplayedportionofthepageThreeoldbrowsersprovidethisisrelativetothe
wholepageCurrentreleasesofthesebrowserssupportitcorrectlySeethechapteron'Event
information'formoredetailsreadonlyNonlayersbrowsersonlyForcrossbrowser
scripting,seealsoeventObject.pageX
clientYIfthemousetriggeredtheevent,thisholdstheverticalpositionofthemousePositionis
relativetothedisplayedportionofthepageThreeoldbrowsersprovidethisisrelativetothe
wholepageCurrentreleasesofthesebrowserssupportitcorrectlySeethechapteron'Event
information'formoredetailsreadonlyNonlayersbrowsersonlyForcrossbrowser
scripting,seealsoeventObject.pageY
ctrlKeyBoolean:saysiftheCtrlkeywaspressedduringtheeventNote:somebrowsersdonot
providethisorthelayerscompatiblemethodofcheckingthesekeysreadonlyNonlayers
browsersonlyForcrossbrowserscripting,seealsoeventObject.modifiers
keyCodeAnumberthatrepresentsthekeypressedKeypadcodesmayvaryreadonly
NonlayersbrowsersonlyForcrossbrowserscripting,seealsoeventObject.which
modifiersAnumberthatrepresentsthecombinationofspecialkeyspressedduringtheevent1
=Alt,2=Ctrl,4=Shift,8=Command(MAC)Canbeaddedtogetherifcombinationsare
pressedNote:somebrowsersdonotprovidethisorthealternativemethodofcheckingthese
keysreadonlyLayersbrowsersonlyForcrossbrowserscripting,seealso
eventObject.altKeyeventObject.ctrlKeyeventObject.shiftKey
pageXIfthemousetriggeredtheevent,thisholdsthehorizontalpositionofthemouserelative
tothewholepagereadonlyNetscapeandDOMcompatiblebrowsersonlyForcross
browserscripting,seealsoeventObject.clientX
pageYIfthemousetriggeredtheevent,thisholdstheverticalpositionofthemouserelativeto
thewholepagereadonlyNetscapeandDOMcompatiblebrowsersonlyForcross
browserscripting,seealsoeventObject.clientY
screenXIfthemousetriggeredtheevent,thisholdsthehorizontalpositionofthemouse
relativetothescreenreadonly
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

151/223

5/30/2015

JavaScripttutorial

screenYIfthemousetriggeredtheevent,thisholdstheverticalpositionofthemouserelativeto
thescreenreadonly
shiftKeyBoolean:saysiftheShiftkeywaspressedduringtheeventNote:somebrowsersdo
notprovidethisorthelayerscompatiblemethodofcheckingthesekeysreadonlyNon
layerscompatiblebrowsersonlyForcrossbrowserscripting,seealsoeventObject.modifiers
targetReferstotheobjectthattriggeredtheeventirrespectiveofcapturingorbubblingread
onlyNetscapeandDOMcompatiblebrowsersonlyForcrossbrowserscripting,seealso
eventObject.srcElement
thisTheword'this'whenwrittenaspartofthehandlerfunctioncodereferstotheobjectthat
triggeredtheeventWithcapturingorbubbling,'this'willrefertoeachelementinturnNetscape
andDOMcompatiblebrowsersonlyreadonly
typeAstringgivingthetypeofeventthatwastriggeredthiswillbeinlowercase,withoutthe
'on'eg.mouseoverInKHTML2browsers,thiswillbeprefixedwith'khtml_'forkeyevents
readonly
srcElementReferstotheobjectthattriggeredtheeventirrespectiveofcapturingorbubbling
readonlyInternetExplorercompatiblebrowsersonlyForcrossbrowserscripting,seealso
eventObject.target
whichIfaleftmousebuttontriggeredtheevent,thiswillbe1Ifarightmousebuttontriggered
theevent,thiswillbe3SomebrowsersdonotdetectrightclicksIfakeytriggeredtheevent,
thiswillbethekeycode(keypadcodesmayvary)readonlyNetscapecompatiblebrowsers
onlyForcrossbrowserscripting,seealsoeventObject.keyCodeeventObject.button

Intrinsicobjectsshowingconstructors
The constructors are all properties of the window object but they are almost always used without
'window.'.Syntax:
varvariableName=newintrinsicObjectConstructor(options);

Forexample:
varmyArray=newArray('here','there','everywhere');

Array
Array([intlength])(notinJavaScript1.2)
Array([element0[,element1[,element...n]]])
[element0,element1,element...n]Avariablecontaininganynumberofvariableswithinit
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

152/223

5/30/2015

JavaScripttutorial

Reversesandsortsworkonlyonnumericallyindexedarraysreadwrite
lengthThenumberofcellsinanumericallyindexedarrayreadwrite
concat(elementToAdd[,elementToAdd[,elementToAdd[,etc.]]])Addscellstotheendofthe
arraycontainingthespecifiedvaluesIfelementToAddisanarray,itscellsareconcatenated
separatelyascellsofthearrayReturnsthenewarraywiththecellsaddedtoit
join([stringseparatorToReplaceComma])Returnsastringrepresentationofthearraywiththe
cellcontentsseparatedbythespecifiedstring(defaultis',')
pop()ReturnsthecontentsofthelastcellfromthearrayThearrayisthenshortenedsothatit
nolongercontainsthatcellNotsupportedinIE5.2Win/Mac
push(elementToAppend)AddselementToAppendtotheendofthearrayNotsupportedinIE
5.2Win/MacItismoreefficientandcompatibletouse:Array[Array.length]=
elementToAppend
reverse()Reversestheorderofthecellsinthearray
shift()ReturnsthecontentsofthefirstcellfromthearrayThearrayisthenshortenedsothatit
nolongercontainsthatcellTheindexesofallothercellsaredecrementedaccordinglyNot
supportedinIE5.2Win/Mac
slice(intoffsetFromStart[,intoffsetToEnd])Returnsanarraywiththecellstakenawayfromthe
specifiedportionofthearrayIfindexToEndisnegative,itistakenasanoffsetfromtheendIfit
isomitted,thenitisassumedtobeArray.length
sort([functionsortFunction])Sortsthearrayinorderofthevaluesofitscellsunless
sortFunctionisspecifiedsortFunctionmustaccepttwoargumentsIfthefunctionreturns>0,
thesecondargumentwillbesortedhigherthanthefirstIfthefunctionreturns<0,thesecond
argumentwillbesortedlowerthanthefirstIfthefunctionreturns0,theentrieswillremainas
theyarewithrespecttoeachother
splice(intoffsetFromStart,intnumberToRemove[,elementToAdd[,elementToAdd[,etc.]]])
Removesthespecifiednumberofcellsfromthearray,startingatthespecifiedoffsetOptionally
addsthenewelementsascellsinthepositionwheretheearliercellswereremovedfromThe
numberofcellsaddeddoesnothavetomatchthenumberofcellsremoved(butitisgenerally
moreefficientiftheyarethesame)Returnsanarraycontainingthecellsthatwereremoved
NotsupportedinIE5.2Win/Mac
toString()orvalueOf()Returnsastringrepresentationofthearray
unshift(elementToAppend)AddselementToAppendtothestartofthearray,andincrements
theindexesofallothercellsaccordinglyNotsupportedinIE5.2Win/Mac

Boolean
Boolean([boolvalue])
trueorfalseAtrueorfalsevaluereadwrite
toString()Returnsthewordtrueorfalse
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

153/223

5/30/2015

JavaScripttutorial

valueOf()Returnsthebooleanvalue

Date
Note, a UNIX timestamp (milli) is the number of milliseconds since 00:00:00.000 01/01/1970,
currently1432999397300.
NotealsothatUTCisthetimeasitwouldbeintheGMTtimezone,soGMTandUTCareequivalent.
Date()
Date(intUNIXTimestampMilli)
Date(year,month,date[,hours[,minutes[,seconds[,ms]]]])Avariablecontainingadatein
severalrepresentationsreadwrite
getDate()Returnsthedayofthemonthrepresentedbythedateobject
getDay()Returnsthedayoftheweekrepresentedbythedateobject
getFullYear()Returnstheyearrepresentedbythedateobjectin4digitformatNotsupported
byoldbrowsersSeegetYear()
getHours()Returnsthehourrepresentedbythedateobjectin24hourformat
getMilliseconds()Returnsthemillisecondrepresentedbythedateobject
getMinutes()Returnstheminuterepresentedbythedateobject
getMonth()Returnsthemonthrepresentedbythedateobject(011)
getSeconds()Returnsthesecondrepresentedbythedateobject
getTime()ReturnstheUNIXtimestamp(inmilliseconds)representedbythedateobject
getTimezoneOffset()Returnsthenumberofhourstheuser'scomputerisawayfromGMT
getUTCDate()ReturnsthedayofthemonthrepresentedbythedateobjectconvertedtoGMT
getUTCDay()ReturnsthedayoftheweekrepresentedbythedateobjectconvertedtoGMT
getUTCFullYear()Returnstheyearrepresentedbythedateobjectin4digitformatconvertedto
GMT
getUTCHours()Returnsthehourrepresentedbythedateobjectin24hourformatconvertedto
GMT
getUTCMilliseconds()ReturnsthemillisecondrepresentedbythedateobjectconvertedtoGMT
getUTCMinutes()ReturnstheminuterepresentedbythedateobjectconvertedtoGMT
getUTCMonth()ReturnsthemonthrepresentedbythedateobjectconvertedtoGMT
getUTCSeconds()ReturnsthesecondrepresentedbythedateobjectconvertedtoGMT
getYear()ReturnstheyearrepresentedbythedateobjectThiscouldbeinavarietyofformats
dependingonthebrowserAsJavaScriptdoesnotsupportdatesbefore1970orbeyond2038
anyway,thefollowingalgorithmsolvesallproblemstheYear=dateObject.getYear()%100//0
38or7099theYear+=(theYear<39)?2000:1900//19702038ortheYear=(
dateObject.getYear()%100)+(((dateObject.getYear()%100)<39)?2000:1900)
setDate(intdayOfMonth)Setsthedayofthemonthrepresentedbythedateobject(011)
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

154/223

5/30/2015

JavaScripttutorial

setFullYear(intyearIn4DigitFormat[,intmonth[,intdayOfMonth]])Setstheyearrepresentedby
thedateobjectin4digitformat
setHours(inthours[,intminutes[,intseconds[,intmilliseconds]]])Setsthehourrepresentedby
thedateobjectin24hourformat
setMilliseconds(intmilliseconds)Setsthemillisecondrepresentedbythedateobject
setMinutes(intminutes[,intseconds[,intmilliseconds]])Setstheminuterepresentedbythe
dateobject
setMonth(intmonth[,intdayOfMonth])Setsthemonthrepresentedbythedateobject
setSeconds(intseconds[,intmilliseconds])Setsthesecondrepresentedbythedateobject
setTime(intUNITXTimestampMilli)etstheUNIXtimestamp(inmilliseconds)representedbythe
dateobject
setUTCDate(intUNITXTimestampMilli)Setsthedayofthemonthrepresentedbythedate
objectconvertedtoGMT
setUTCFullYear(intyearIn4DigitFormat[,intmonth[,intdayOfMonth]])Setstheyear
representedbythedateobjectin4digitformatconvertedtoGMT
setUTCHours(inthours[,intminutes[,intseconds[,intmilliseconds]]])Setsthehour
representedbythedateobjectin24hourformatconvertedtoGMT
setUTCMilliseconds(intmilliseconds)Setsthemillisecondrepresentedbythedateobject
convertedtoGMT
setUTCMinutes(intminutes[,intseconds[,intmilliseconds]])Setstheminuterepresentedby
thedateobjectconvertedtoGMT
setUTCMonth(intmonth[,intdayOfMonth])Setsthemonthrepresentedbythedateobject
convertedtoGMT
setUTCSeconds(intseconds[,intmilliseconds])Setsthesecondrepresentedbythedate
objectconvertedtoGMT
setYear(intnumberOfYearsSince1900)Setsthedifferencebetween1900andtheyear
representedbythedateobject
toUTCStringortoGMTString()Returnsthedateasastring,convertedtoGMT
toStringortoLocaleString()Returnsthedateasastring
valueOf()ReturnstheUNIXtimestamp(inmilliseconds)representedbythedateobject

Function
Function([stringvarName,[stringvarName2,[etc.]]]stringscriptToEvaluate)
functionfunctionName(listOfVariables){functioncode}
functionName=function(listOfVariables){functioncode}Aseriesofinstructionsthatcanbe
activatedasandwhennecessaryCanreturnvaluesreadwrite
callerReferstothefunctionthatcalledthisfunction(ornullifnone)Note,itisapropertyofthe
individualfunctionandmustbewrittenasfunctionObject.callerWarning,thispropertyisnon
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

155/223

5/30/2015

JavaScripttutorial

standardandisnotavailableinmanybrowsers,includingOpera,Safari2,Konqueror3.5.6,
NetFront,ICEbrowser,EscapeandClueDonotusethispropertyreadwritebutunusableif
writtento
prototypeIfthefunctionisusedasanobjectconstructor
functionObject.prototype.newPropertyNamecreatesnewpropertiesforallobjectsofthatclass
readwritebutunusableifwrittento
this'this'writtenaspartofthefunctioncodereferstothecurrentobjectIfactivateddirectlyby
anevent,thiswillbetheobjectthattriggeredtheeventIfbeingusedtoconstructanobject,this
willrefertotheconstructobject(thatistheinstantaneousobjectbeingconstructed,whichis
storedtemporarilyuntilitisreturned)Ifneitherofthesearesatisfied,thisreferstowindow
'this'isaninstantaneousvariable,andisnotapropertyofthefunctionreadonly
arguments[]Theargumentscollectionwhenwrittenaspartofthefunctioncodereferstothe
collectionofvariablespassedtothefunctionNote,itisapropertyoftheindividualfunctionbut
canbewrittenaseitherfunctionObject.argumentsorjustargumentsreadwritebutunusable
ifwrittento
calleeAreferencetothefunctionthatthiscodeisrunninginsideNotsupportedby
WebTV/MSNTVreadwritebutunusableifwrittento
apply(object:thisObject[,array:arguments])Runsthefunctionasifitwereamethodofthe
thisObjectpassingittheargumentsfromtheargumentsparameterNotsupportedinIE5.2
Win/Mac,WebTV/MSNTV,orearlyNetscape4versions
call(object:thisObject[,argument[,argument[,etc.]]])Runsthefunctionasifitwereamethodof
thethisObjectpassingittheseparateargumentsfromthesubsequentparametersNot
supportedinIE5.2Win/Mac,WebTV/MSNTV,orearlyNetscape4versions
toString()ReturnsastringrepresentationofthefunctionIntheory,foruserdefinedfunctions,
thestringshouldbevalidfunctioncode(withanonymousfunctionbraces)However,most
browserswillhaveproblemswithcertainconstructs,andbrowsersondeviceswithlimited
memorymaynotprovideanythingatall
valueOf()Returnsthefunction

Image
Image([intwidth,intheight])Createsanimagethatisnotdisplayedbutisstoredincache
Childrenasforwindow.document.nameOfImageTheimagewillnotbeloadeduntilthesrcisset
readwrite

Number
Number(numberOrStringvalue)
numberinhex,octalordecimalAvariablewithanumericalvalueCanbenegativeorpositiveor
NaNorInfinityandcanhaveE+orEreadwrite
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

156/223

5/30/2015

JavaScripttutorial

toFixed(precision)Returnsthenumberasastring,roundedandformattedwiththegiven
numberofdecimalplacesNotsupportedinmostoldbrowsers,includingIE5.0MostnonIE
browsersreturnlargenumbersinscientificnotation
toPrecision(precision)Returnsthenumberasastring,reducedtoaprecisionofthegiven
numberofdecimalplacesMaybereturnedinscientificnotationNotsupportedinmostold
browsers,includingIE5.0
toExponential(precision)Returnsthenumberasastring,roundedandformattedinscientific
notationwiththegivennumberofdigitsafterthedecimalpointNotsupportedinmostold
browsers,includingIE5.0
toLocaleString()Returnsthenumberasastring,formattedaccordingtotheuser'slocaleNot
supportedinmostoldbrowsers
toString()Returnsthenumberasastring
valueOf()Returnsthenumber

Object
Object()
{propertyName1:value1[,propertyName2:value2[,etc.]]}Createsavariablethatcanhave
propertiesorchildobjectsreadwrite
constructorReturnsareferencetothefunctionthatisusedasaconstructorforthisclassof
object
hasOwnProperty(stringpropertyName)Returnstrueifthegivenpropertyisattacheddirectlyto
theobjectinstance
toString()Returnsastringrepresentationoftheobject(typically[objectObject])
valueOf()Returnsastringrepresentationoftheobject(typically[objectObject])

Option
Option([stringtext,stringvalue[,boolselected]])Createsanselectinputoptionthatcanbestored
untilitisinsertedintoaselectinputusing:
window.document.nameOfForm.nameOfSelect.options[intoptionNum]=optionObjectChildrenas
forwindow.document.nameOfForm.nameOfSelect.options[intoptionNum]readwrite

RegularExpression
RegExp(stringpattern,stringoptions)
/pattern/optionsAtextpatternmatchingseriesofmetaandnormalcharactersSomeoldbrowsers
failtoimplementthiscorrectly(eg.Opera6andiCab2)readwrite
compile(stringpattern,stringoptions)Redefinestheregularexpressionandcompilesitfor
fasterusethannormalOnlyusefulifusingthesameregularexpressionmultipletimes
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

157/223

5/30/2015

JavaScripttutorial

Redundantincurrentbrowsersdonotuseit
exec(stringstringToMatch)Attemptstomatchtheregularexpressionagainstthestring
Returnsanarrayofthedetailsofthelastmatchornullifnone:[lastsubstringthatfully
matchedtheregularexpression,lastinstanceoffirstcapture,...,lastinstanceofninth
capture]Returnedarrayhastwootherproperties:indexthepositionwithinthestring
wherethepatternbegantomatch(readonly)inputor$_theoriginalstring(readonly)
globalBoolean:saysifthe'g'optionwasusedforaglobalmatchreadonly
ignoreCaseBoolean:saysifthe'i'optionwasusedtoignorecasereadonly
lastIndexTheindexwherethelastmatchoccurredduringexecortest(read)ORTheindexat
whichtostartthenextmatch(write)
sourceThetextofthepatternreadonly
test(stringstringToMatch)AttemptstomatchtheregularexpressionagainstthestringReturns
booleanifamatchisfound

String
String([stringOrObjectToBeRepresentedAsString])
'content'
"content"AvariableconsistingonlyofcharactersThesecancomefromanycharacterset
supportedbythecurrentdocumentreadwrite
lengthThenumberofcharactersinthestringreadwrite
anchor(stringnameOfAnchor)Surroundsthestringwith<aname="nameOfAnchor">tagsFor
usewhendynamicallygeneratingpagecontentUseIDattributesinstead
big()Surroundsthestringwith<big>tagsForusewhendynamicallygeneratingpagecontent
Thereisalmostalwaysamoreappropriateelementyoucanuse
blink()Surroundsthestringwith<blink>tagsForusewhendynamicallygeneratingpage
contentThiselementisnonstandard(andannoying),donotuseit
bold()Surroundsthestringwith<b>tagsForusewhendynamicallygeneratingpagecontent
Youmaywanttouse<strong>instead
charAt(intindex)Returnsthecharacteratthespecifiedindex
charCodeAt(intindex)Returnsthenumericalvalueofthecharacteratthespecifiedindex
concat(stringstringToAppend[,stringstringToAppend[,stringstringToAppendetc.]])Returns
thestringsappendedtoeachotherandthestringobjectinorder
fixed()Surroundsthestringwith<tt>tagsForusewhendynamicallygeneratingpagecontent
Thereisalmostalwaysamoreappropriateelementyoucanuse(<code>,<samp>or<var>)
fontcolor(stringcolorValue)Surroundsthestringwith<fontcolor="colorValue">tagsForuse
whendynamicallygeneratingpagecontentThiselementisdeprecated,donotuseit
fontsize(intsize)Surroundsthestringwith<fontsize="size">tagsForusewhendynamically
generatingpagecontentThiselementisdeprecated,donotuseit
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

158/223

5/30/2015

JavaScripttutorial

indexOf(stringsearchString[,intoffset])ReturnsthefirstpositionofthesearchStringwithinthe
stringobjectReturns1ifnone
italics()Surroundsthestringwith<i>tagsForusewhendynamicallygeneratingpagecontent
Youmaywanttouse<em>instead
lastIndexOf(stringsearchString[,intoffset])ReturnsthelastpositionofthesearchStringwithin
thestringobjectReturns1ifnone
link(stringhrefToLinkTo)Surroundsthestringwith<ahref="hrefToLinkTo">tagsForuse
whendynamicallygeneratingpagecontent
match(RegExpsearchExpression)Iftheregularexpressiondoesnothavetheglobalflag,it
returnsanarraycontainingthepartofthestringthatmatchedtheexpression,followedbyevery
capturefromtheregularexpressioninsequence,fromthefirstmatchwithinthestringIfthe
regularexpressiondoeshavetheglobalflag,itreturnsanarraycontainingeverymatchofthe
entireregularexpressionagainstthestringIftherearenomatches,itreturnsnullThefirst
9captures/matchesoftheregularexpressionarealsostoredintheglobalRegExpobject
replace(RegExpsearchExpression,stringreplacementText)Replacesthefirstoccurrenceof
thespecifiedregularexpressionwithinthestringwiththereplacementtext
search(RegExpsearchExpression)Returnsthefirstpositionoftheregularexpressionwithinthe
stringobjectReturns1ifnone
slice(intoffsetFromStart[,intoffsetFromEnd])Returnsthesubstringstartingatthespecified
indexandendingatthespecifiedoffsetfromtheendIftheoffsetisnotspecified,theoffsetis
takenas0
small()Surroundsthestringwith<small>tagsForusewhendynamicallygeneratingpage
contentThereisalmostalwaysamoreappropriateelementyoucanuse
split(RegExpseparator[,intmaxArrayLength])Splitsastringontheoccurrenceofaspecified
substringResultsarereturnedasanarrayIfamaximumlengthisspecifed,thefinalcellwill
containanyamountsnotsplitafterthatpoint
strike()Surroundsthestringwith<s>tagsForusewhendynamicallygeneratingpagecontent
Thiselementisdeprecated,donotuseitUsually,the<del>elementiswhatyouwanttouse
sub()Surroundsthestringwith<sub>tagsForusewhendynamicallygeneratingpagecontent
substr(intstartIndex[,intlength])Returnsthesubstringstartingatthespecifiedindexandthe
specifiedlengthlongIfnolengthisspecified,thelengthistotheendofthestring
substring(intstartIndex,intendIndex)Returnsthesubstringstartingatthespecifiedindexand
endingatthespecifiedindex
sup()Surroundsthestringwith<sup>tagsForusewhendynamicallygeneratingpagecontent
toLowerCase()Returnsthestringinlowercase
toUpperCase()Returnsthestringinuppercase
valueOf()Returnsthestring

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

159/223

5/30/2015

JavaScripttutorial

W3CDOMintroduction

Thispartofthetutorialstepsbeyondthelimitsoftheolderbrowsers,andwillcoverthemuchmore
advancedabilitiesofthecurrentbrowsers.
ThankstoPP:KforlinkingtothispagefromhisDigitalWebarticleabouttheW3CDOM.Herefersto
this as a 'less technical introduction' to the W3C DOM. I am happy with that description, not only
becausethe'technicalintroduction'isa239pagePDFofincredibledetail,butbecauseIdon'tsee
whytheDOMshouldbethattechnical.Itisdesignedtobeintuitiveandeasytouse,sothatishowI
willteachit.Ofcoursetherearesomeincrediblyadvancedandcomplexthingsyoucandowiththe
DOM,butwithwebpages,thereisalmostnevertheneedtodothem.So,insteadofgoinginto239
pages of information on how to convert the planet Earth into a DOM tree, I will give you a gentle
introduction to the fundamentals of the DOM, and show you how to achieve the results you need,
withtheminimumoffuss.
TheW3CDOM,commonlyknownas'TheDOM'orthe'DOMlevel1(/2/3)',providesamorerealistic
and more versatile way of looking at the structure of HTML documents (as well as XML and other
document formats). It views HTML documents as a tree structure of elements and text embedded
withinotherelements.AllHTMLelements,aswellasthetexttheycontainandtheirattributescanbe
referenced by walking through the DOM tree, their contents can be modified or deleted, and new
elementscanbecreatedforsubsequentinsertionintotheDOMtree.HTMLelements,thetextthey
contain,andtheirattributesareallknownasnodes.
TheDOMisdesignedtointeractwithmoreprogramminglanguagesthanjustJavaScript,butasthis
isaJavaScripttutorial(incaseyoudidn'tnotice...),andmostbrowsersonlysupportJavaScript,Iwill
onlydescribehowtouseJavaScripttointeractwithit.
The DOM is the present and future of browsers, and no doubt it will become the only supported
techniqueforbothbasicandadvancedDHTMLinthefuture.
TheW3CDOMissupportedby5 thgenerationbrowsers.Thesecurrentlyinclude:
Opera7+
MozillaGecko(Mozilla,Firefox,Netscape6+)
KHTML/WebKit(Konqueror2+,Safari,Chrome,OmniWeb4.5+)
InternetExplorer5+
iCab3+(2ispassiveonly)
ICEbrowser
Escape/Evo5(partialonly[andbroken])
TkhtmlHv3(partialonly[andbroken])
NetFront3+(partialonly)
Netgem4browser(NetBox)nottested
OpenTVnottested
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

160/223

5/30/2015

JavaScripttutorial

iPanelMicroBrowserwithadvancedmodulesnottested
For more details of these browsers, and to download them, please see my list of '4 th+generation'
browsers.
ThislistmakesitclearthatInternetExplorer4,Netscape4,Escape4,Opera4,5and6,Omniweb
4.2 and WebTV all do not support the W3C DOM. These browsers are no longer in common use,
and can be safely ignored. You may want to check that a browser supports the W3C DOM before
you attempt to use it. Note that Opera 46 also supports many of the basic functions of the W3C
DOM,butcannotactuallyusemostofthem.iCab2cannotperformadvancedW3CDOMfunctions.
Therefore,thebesttestforW3CDOMsupportthatIcanfindisthis:
if(document.getElementById&&document.childNodes&&document.createElement){
//dosomethingthatrequiresit
}

Ofallthecurrentmajorbrowsers,InternetExplorer'sDOMsupportisbyfartheworstofall.IE8for
WindowssupportshalfoftheDOM1modules,andpartsofafewDOM2modules.TheMacversion
supports slightly more of DOM 1. IE 9+ supports most of DOM 1 and 2, and a few basic DOM 3
modules,butonlyifthedocumenttriggersstandardsrenderingmode.Inquirksmode,IE9+reverts
toitscrippledoldversionofDOM,andsincemanyscriptswillneedtoworkinbothmodes,theywill
needtoallowforthis,andrestrictthemselvestousingonlythepartsIEsupports,orhasalternatives
for.
Opera, Mozilla/Firefox and Safari/Chrome are competing for first place, with complete DOM 1
support,completeoralmostcompleteDOM2support,andasmallamountofDOM3support.iCab3
haspartialDOM1andDOM2.Opera9+isthefirstandcurrentlyonlybrowsertosupportallDOM1
and2featureswellenoughtoclaimsupportforallofthem(aswellasanumberofDOM3modules).
Safari/Chrome also claims support for all DOM 1 and 2 features, but its DOM 2 Style Sheets and
CSSimplementationissobaditshouldnotbeallowedtoclaimsupportforthematall.
This tutorial will concentrate on things that will work in all these browsers, since they are the most
commonbrowserscurrentlyinuse,andwillshowhowtobridgethegaptoallowInternetExplorer's
nonstandard features to be used as a partial replacement for missing parts of important DOM
features.
ICEbrowser has largely complete DOM 1 and partial DOM 2 (it also claims some DOM 3, but my
tests cannot support its claims, especially since it is missing large parts of DOM 2 that it claims to
support).ItwillcopewithmostofthethingsIwillcoverinthistutorial.
Escape 5 can handle enough DOM to reference elements and their styles, and can move them
throughthedocument.However,assoonasyoutryanythingmorethanthat(walkingtheDOMtree,
creating new elements, changing their contents, checking for the existence of a childNodes
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

161/223

5/30/2015

JavaScripttutorial

collection,etc.),itproducesscripterrors,andfailstousetry...catchcorrectly,sotheerrorscannot
beavoided.Inthisstate,itisunusable,anditcan'tevenhandlemanybasicDHTMLscriptseither.
Justignoreit.Itishardlyusedbyanyone,andhasbeenabandonedbythevendor.
NetFront has recently added DOM support and it is still very immature. Generally versions earlier
than3.4willproduceerrorsorcrash,andasaresult,shouldbeignoredasDOMbrowsers.Version
3.4usuallyperformsbetter.
PP:KmaintainsmanyDOM1tutorialsaswellastheeverhelpfulDOMcompatibilitytables.Although
theDOMprovidesmanymoremethods,propertiesandcollectionsthanIhaveshownhere,mostare
notreliableenoughtouse,soIwillonlytalkyouthroughthosethatare.Ifyouintendtouseother
propertiesormethods,youshouldcheckifthebrowsersupportsthemfirstusing:
if(node.propertyCollectionOrMethodName){
//dosomethingthatrequiresit
}

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

162/223

5/30/2015

JavaScripttutorial

DOMnodesandtree

TheDOMtree
ThefollowingtextisasnippetofHTMLtakenfromaregularHTMLdocument.
<ptitle="Thetestparagraph">Thisisasampleofsome<b>HTMLyoumight<br>have</b>in
yourdocument</p>

In your browser, this renders as this (hold your mouse over the paragraph to see the title most
browsersdisplayitasatooltip,somedisplayitinthestatusbar):
ThisisasampleofsomeHTMLyoumight
haveinyourdocument
TheDOMtreeviewsthis(simplified)asfollows:
P
_______________|______________
||
childNodesattributes
______________|___________|
|||title='Thetestparagraph'
'Thisisasampleofsome'B'inyourdocument'
|
childNodes
__________|_______
|||
'HTMLyoumight'BR'have'

Of course, the tree also extends above the 'P' from window.document, through the HTML element,
downthroughthebodyelement,thenthroughanyothercontainerelementstotheparagraph.
The parts of the DOM tree are known as nodes. The 'P', 'B' and 'BR' nodes are element nodes,
childNodesandattributesarecollections,thetitle='Thetestparagraph'pairisanattributenode,

andthetextstringsaretextnodes.

Referencingtheelementnodes
Konqueror incorrectly requires the getElementsByTagName parameter to be in lower case when using XHTML
strictdoctypes,butservedastext/html.
iCab3failstokeeptheobjectreturnedbygetElementsByTagNameupdated.
TkhtmlHv3addsalltextnodesthatappearbeforetheopening<body>tag,asseparatetextnodesintothebody's
childNodescollection.

Escape/Evo5failstousethechildNodescollections,andwillabortthescript.Ignorethisbrowser.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

163/223

5/30/2015

JavaScripttutorial

EarlyIE5Macdidnotprovidethe childNodes.lengthproperty.Thiswasfixedautomatically.Ifyouareworried,
usesomethinglikethis:for(varx=0;node.childNodes[x];x++)

Using the DOM, there are several ways that we could reference the paragraph. We can use
getElementsByTagNametoreferenceallparagraphs,thenchoosetheonewewant.Iftheparagraph

weretobegivenanid,wecouldalsousegetElementById:
document.getElementById('idofparagraph')
document.getElementsByTagName('p')[indexOfParagraph]

If we assigned the paragraph an id so that we could use getElementById, the id='elementID'pair


would appear in the attributes collection, along side title='The test paragraph' in the tree
diagram above. Note that if the document is served with an XML based contenttype header,
getElementsByTagNamebecomescasesensitive.

NOTE: getElementsByTagName does not return a true collection, it returns an object with element
index and 'length' properties. This object keeps itself up to date, so if an element it references is
deletedoradded,itwillautomaticallychangeitsitemreferencestoreflectthatchange.
WecouldevenwalktheentireDOMtreefromthedocumentobject,forexample:
window.document.childNodes[0].childNodes[1].childNodes[4]

Inthiscase,window.document.childNodes[0]shouldbetheHTMLelement,asitisthefirsttaginthe
document(assumingthereisnodoctypetag),and window.document.childNodes[0].childNodes[1]
shouldbethebodytag,astheheadelementwillbethefirstchildoftheHTMLelement.Alternatively,
thereisashortcuttotheHTMLelement:document.documentElementsowecouldusethis:
window.document.documentElement.childNodes[1].childNodes[4]

ThereisalsoashortcuttotheBODYelement:document.bodysowecouldusethis:
window.document.body.childNodes[4]

Those last three examples are based on a simple page structure, where the paragraph is a direct
child of the body element. Neither of these would be correct in the current document as the
documentstructureisfarmorecomplex,alsousingDIVelementsasparentsoftheparagraph.
The techniques used in those examples can be unreliable. Most browsers will correctly view the
blank space between tags as a text node containing only white space characters (such as space,
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

164/223

5/30/2015

JavaScripttutorial

linebreakortab),eveniftheblankspaceisnotrendered,suchasagapinbetweena<tr>tagand
a<td>tagorablankgapinbetween<p>tags.However,somebrowsers(mainlyInternetExplorer
8,and9+inquirksmode)willnotviewthisemptyspaceasatextnodeatall.
Thismeansthatthe childNodescollectionwillbedifferentlengthsinthesedifferentbrowsers.Ifyou
are trying to walk the DOM tree to the next element node, for example, it may be worth checking
each entry in the childNodes collection to see if its nodeType is 1, or to use
node.getElementsByTagName.

Becauseofthis,andthefactthatthestructureoftheDOMtreeisdesignedtochangeaselements
aremoved,addedorremoved,theonlyreliablewaytoreferenceanelementisusingitsID:
vartheParagraph=document.getElementById('idofelement')

Thefirstentryofthe childNodescollectioncanbeaccessedusingtheshortcut firstChild,andthe


last can be accessed using lastChild. node.nextSibling references the next entry in the parent
node'schildNodescollectionand node.previousSiblingreferencesthepreviousone.Toreference
the parent node, we use node.parentNode. Note also that all element nodes have the
getElementsByTagName method to help reference elements within them. This means that from any

node,itispossibletoreferenceanyoftheothernotesaroundit.

Referencingtheattributenode
TkhtmlHv3doesnotsupporttheattributescollection.

To reference the title='The test paragraph' attribute pair, we use the attributes collection.
Dependingonthebrowser,thiscollectionmaybefilledupinavarietyofdifferentways,andmany
emptyattributepairsmayexistinthecollection.Tofindthecorrectattribute,wesearchthroughthe
attributescollectionforanattributewhosenodeNamematcheswhatwewant.ThenodeNamemaybein
any case in HTML documents (typically upper case) and should be case sensitive in XHTML and
XMLifservedusinganXMLbasedMIMEtype.
for(varx=0;x<theParagraph.attributes.length;x++){
if(theParagraph.attributes[x].nodeName.toLowerCase()=='title'){
window.alert('Thevalueofthe\'title\'attributeis:'+
theParagraph.attributes[x].nodeValue);
}
}

Testithere:gettheattributevalue.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

165/223

5/30/2015

JavaScripttutorial

Aneasywaytochecktheattributenode
NetFrontgetsthecasewrongwhenretrievingattributevalues(alignisreturnedas'Center'insteadof'center').
Opera78willretrieveresolvedvaluesinsteadofspecifiedvaluesforattributeslike'href'and'src'.
Manybrowsers(particularlyInternetExplorer7)willhavetroubleretrievingvaluesforstyleandclass,aswellas
eventhandlers.

Ifallyouwanttodoistocheckthevalueofanattribute,notmanuallyedititsentry,itiseasiertojust
usegetAttribute.
window.alert('Thevalueofthe\'title\'attributeis:'+
theParagraph.getAttribute('title'));

Attributenamesarecasesensitive.Forexample,bgcolormustbewrittenasbgColor.
Testithere:gettheattributevalue.
Notethataccordingtothespecification, getAttribute should always return a string. However, this
makes it impossible to differentiate between empty attributes and unspecified attributes. For this
reason, browsers will return null for unspecified attributes, even though this is wrong. Opera 78
returns an empty string this was changed to null in Opera 9. As a result, code that checks for
attributes and incorrectly tests against null will fail in Opera 7 and 8, because a string will never
equate to null. There is no need to test against null, just check if get attribute failed to retrieve a
value:
if(!element.getAttribute('attribute_name'))

Changingtheattribute
InternetExplorer7(andsomeminorbrowsers)cannotsetvaluesforstyle,classoreventhandlers.
InternetExplorer8,and9+inquirksmodecannotsetvaluesforeventhandlers.
Opera7.07.1,couldnotsetthealignattribute.

TheattributesofanelementcanbesetorchangedusingsetAttribute:
element.setAttribute('attributeName','attributeValue')
theParagraph.setAttribute('align','center')

Attributenamesarecasesensitive.Forexample,bgcolormustbewrittenasbgColor.
Youcanalsoremoveattributes,withafewexceptions,usingremoveAttribute:

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

166/223

5/30/2015

JavaScripttutorial

theParagraph.removeAttribute('attributeName')

Movetheparagraphheresoyoucanseewhatyouaredoingthen:
ChangethetitleattributeandChangeitback(holdyourmouseovertheparagraphtoseeifthetitle
haschanged).
NetFront3.2cannotmovetheexistingparagraphtoanewlocation(version3.3mayalsofail,ifthedevicedoes
nothavemuchmemory),butitgetstherestoftheexampleright.

Readingandwritingproblematicattributes
Internet Explorer 7 (and some minor browsers) cannot set values for style, class or event
handlers,using setAttribute.InternetExplorer8hasfixedmostofthese,butstillcannotsetevent
handlers.InternetExplorer9cannowsettheseattributesinstandardsmode.Afewmorebrowsers
also have trouble reading these attributes using getAttribute. Internet Explorer generally returns
thewrongtypeofresult,suchasanobjectinsteadofastring,whenusing getAttribute for these
attributes.TheDOMdoesprovideafewalternativestoallowthefunctionalitytobeapproximatedin
thesebrowsers.
The class is available as a read/write string called className this is discussed in the DOM CSS
chapterofthistutorial.
Theeventhandlerattributesareavailableasreferencedfunctions(thisisnotthecaseforhandlers
addedusingDOMevents), with their names matching the attribute name element.onclick.These
areread/writebutmustbewrittenasareferencetoafunction,notasadirectstring.Theycanalso
bewrittenasastringusingtheFunctionconstructor:
element.onclick=newFunction(codeAsAString);

They may also be read as a string using the toString method of the function, but note that it will
normally contain the anonymous function wrapper, and may not be available at all in browsers
running on devices with limited capabilities, such as mobile phones. Note also that it will not be
availableatalliftheattributeisnotpresent:
varfunctioncode=element.onclick.toString();

The string value of the style attribute is available as a read/write string called cssText, which is a
propertyofthe style object, which itself is a property of the element. Note, however, that it is not
supported very well Safari does not support it up to version 1.1 (reading it produced the value
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

167/223

5/30/2015

JavaScripttutorial

null),Mozillaversionspriorto1.0couldnotwritetoit,andiCab3,NetFrontandEscape/Evodonot

support it at all. To avoid problems with its use, a combination of cssText and
getAttribute/setAttributecanbeused.Toreadit:
varcssString;
cssString=element.style.cssText;
if(typeof(cssString)!='string'){
cssString=element.getAttribute('style');
}

Towriteit,simplysetbothversions,andthebrowserwillusewhicheveroneworks:
varcssString='color:lime;fontweight:bold;';
element.style.cssText=cssString;
element.setAttribute('style',cssString);

Notethatthiswillthenpreventitfrombeingreadcorrectlyifotherstylesarechangedindividually.If
thiswillcauseaproblem,checkifcssTextissupportedfirst:
varcssString='color:lime;fontweight:bold;';
if(typeof(element.style.cssText)=='string'){
element.style.cssText=cssString;
}
element.setAttribute('style',cssString);

Referencingthetextnodes
Mozilla/Firefox/Netscape6+andOpera9.2xwillsplitverylongtextnodesintomultiplesmallertextnodes.

To give a full example, I will try to reference the text node 'HTML you might'. To do this, I will go
throughthesecondentryofthe childNodesarrayofthe'P'.Thiswillbeareferencetothe'B'.Iwill
then look at the firstChild (equivalent to the first entry in the childNodes collection) of the 'B' to
referencethetextnode.
window.alert('Thevalueofthetextnodeis:\n'+
theParagraph.childNodes[1].firstChild.nodeValue);

Testithere:getthevalueofthetextnode.
Also important to note is that although the specifications say that no matter how much text exists
betweentags,itshouldallbeinonetextnode,inpracticethisisnotalwaysthecase.InOpera7
9.2xandMozilla/Netscape6+,ifthetextislargerthanaspecificmaximumsize,itissplitintomultiple
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

168/223

5/30/2015

JavaScripttutorial

text nodes. These text nodes will be next to each other in the childNodes collection of the parent
element.
In Opera 79.2x, this maximum text node size is 32 KB. In Mozilla/Firefox/Netscape 6+, it is 4 KB.
Althoughthe normalize()methodoftheparentnode(s)shouldbeabletoreplacethemultipletext
nodeswithasingletextnodecontainingallthetext,thisonlyworksinMozilla/Firefox/Netscape6+.
InOpera79.2xitputsallofthetextintoasinglenodeandthentruncatesthatnodeto32KB,so
thecontentsofallexceptthefirstnodearelost.Runningthe normalizemethodcancrashInternet
Explorer6anddoesnotexistinInternetExplorer5onWindows.
For this reason, I do not recommend trying to normalize. It is better to manipulate the contents of
textnodesseparately.Infact,youcancreateyourowntextnodesandaddthemtothe childNodes
collection.AlthoughtotheDOM,theywillstillappearasseparatenodes,theywillappearasasingle
piece of text in the document. Basically, you need to be aware that your text may be split into
severalnodes,ifitis4KBorover,orifyouhaveaddedextratextnodesinyourself.Inordertoget
that text in a single variable, you may need to look through every child node, and if they are
consecutivetextnodesappendthemtogethertogetthetotalstring.

Changingthetextoftextnodes
KHTML/WebKitKonqueror3.4,Safari1.2andOmniWeb4.55.0donotalwaysreflowthepagewhenchanging
thetextoftextnodes.
TkhtmlHv3versionsbeforeSeptember2007cannotchangethevalueofexistingtextnodes.

Onceyouhaveareferencetothetextnode,youcanreadorwriteitscontentsusingitsnodeValue.
theParagraph.childNodes[1].lastChild.nodeValue='wanttochange';

Movetheparagraphheresoyoucanseewhatyouaredoingthen:
Changethetextnode|Changeitback.
NetFront3.2cannotmovetheexistingparagraphtoanewlocation(version3.3mayalsofail,ifthedevicedoes
nothavemuchmemory),butitgetstherestoftheexampleright.

Creatingnewnodesandremovingexistingones
NetFront3.2cannotcreateorinsertnewnodes(version3.3oftencrasheswithscriptsthatusethis,ifitisrunning
onalowermemorydevice).

This is what the DOM was truly created for. In order to create new nodes, we use a couple of
methods of the document object to create the node. We then insert the node into the main DOM
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

169/223

5/30/2015

JavaScripttutorial

tree, at which point the browser will display it. We can also move existing nodes (like the test
paragraph)simplybyinsertingthemintotheDOMtreesomewhereelse.
Notethatwhencreatingelementnodes,theelementnamemustbeinlowercase.Althoughintheory
itshouldnotbecasesensitivewithHTML,IhavenoticedsomeproblemsinKonquerorwhenusing
uppercasewithstrictdoctypesseethetopofthispage.ItwillbecasesensitivewithXHTML(inall
compliantbrowsers,notjustKonqueror),andmustbeinlowercase.
vartheNewParagraph=document.createElement('p');
vartheTextOfTheParagraph=document.createTextNode('Somecontent.');
theNewParagraph.appendChild(theTextOfTheParagraph);
document.getElementById('someElementId').appendChild(theNewParagraph);

Wecouldalsouse insertBeforeinsteadof appendChild,orevenmanuallyaddthenewelementto


the end of the end of the childNodes collection. Using replaceChild, we could also overwrite
existingnodes.Itisalsopossibletocopyanodeusing cloneNode(true).Thisreturnsacopyofthe
node

but

does

not

automatically

add

it

into

the

childNodes

collection.

Using

element.removeChild(referenceToChildNode),wecanremoveexistingnodes.

Testithere:createanewparagraph.
How about something even more complicated. What about adding HTML elements within the new
element,insteadofjustplaintext.Here,Iwillrecreatethetestsentencefromabove,onepieceata
time.
//threeelementsarerequired:p,b,br
vartheNewParagraph=document.createElement('p');
vartheBoldBit=document.createElement('b');
vartheBR=document.createElement('br');
//setuptheNewParagraph
theNewParagraph.setAttribute('title','Thetestparagraph');
//preparethetextnodes
vartheText1=document.createTextNode('Thisisasampleofsome');
vartheText2=document.createTextNode('HTMLyoumight');
vartheText3=document.createTextNode('have');
vartheText4=document.createTextNode('inyourdocument');
//puttogethertheboldbit
theBoldBit.appendChild(theText2);
theBoldBit.appendChild(theBR);
theBoldBit.appendChild(theText3);
//puttogetherthewholeparagraph
theNewParagraph.appendChild(theText1);
theNewParagraph.appendChild(theBoldBit);
theNewParagraph.appendChild(theText4);
//insertitintothedocumentsomewhere
document.getElementById('someElementId').appendChild(theNewParagraph);
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

170/223

5/30/2015

JavaScripttutorial

Testithere:recreatethetestparagraph.
IncaseyouwerewonderinghowImanagedtomakethosenewparagraphsendupjustabovethe
linksyouclickedon,thisishow.
Thelinkyouclickedonisinaparagraph.Theparagraphisinadiv(althoughthistechniquewould
workanywhere).Thescriptisrunintheeventhandlerforthelink.Therefore,inthehandlerfunction,
'this' refers to the link. The parentNode of the link is the paragraph this.parentNode and the
parentNodeoftheparagraphisthedivthis.parentNode.parentNode.Iwanttogetthedivtoimport

thenewparagraphnodeIhavecreatedabovetheparagraphthelinkisin,soIwanttosaythis:
theDIV.insertBefore(theNewParagraph,theCurrentParagraph);

InJavaScript,thiswouldbe:
this.parentNode.parentNode.insertBefore(theNewParagraph,this.parentNode);

As for making them disappear when you click on them, when creating these paragraphs, I also
assignanonclickeventhandlerfunctionthatuses this.parentNode to reference the div, and then
usesremoveChildtodeletetheparagraph:
theNewParagraph.onclick=function(){this.parentNode.removeChild(this);};

Note that nodes belong to the document they were created in. So for example, if your page uses
frames, and you create a paragraph node in one frame then attempt to add it to the document in
anotherframe,itwillnotwork.Intheoryyoucanusethe document.importNodemethodtocreatea
copyofitinthenewdocument,butthatmethoddoesnotexistinInternetExplorer.Ifascriptinone
frame needs to create a node and append it to a document in another frame, it must use the
documentobjectforthedestinationframewhencreatingthenode:
varnewP=parent.frames['leftfr'].document.createElement('p');
parent.frames['leftfr'].document.body.appendChild(newP);

Usingdocumentfragments
InternetExplorer5.xonWindows,NetFront3.3andTkhtmlHv3donotsupportdocumentfragments.
Internet Explorer 5 on Mac cannot add text nodes to document fragments, and cannot append the fragment's
contentstoadocument.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

171/223

5/30/2015

JavaScripttutorial

It is also possible to deal with multiple nodes at the same time. Say for example that you want to
create10paragraphs,andaddthemalltothedocumentatthesametimeaseachother,insteadof
one at a time. This can be done using a document fragment. The benefit of using this is that it
createsfewerdocumentreflows,andasaresultitcanimproveperformanceforbigchanges.
Adocumentfragmentislikeanormalelement(suchasadiv),exceptthatitcannotbecomeapartof
thedocumentitself.Ifyoutrytoappendadocumentfragmenttoanypartofadocument,insteadof
appending the fragment, the browser will add the child nodes of the fragment. For example, you
create10paragraphs,appendthemtoadocumentfragment,thenappendthedocumentfragment
to the body of a document. Instead of appending the fragment to the body, it will add the 10
paragraphsaschildrenofthebody.
varfrag=document.createDocumentFragment();
for(vari=0,p;i<10;i++){
p=document.createElement('p');
p.appendChild(document.createTextNode('Paragraph'+(i+1)));
frag.appendChild(p);
}
document.body.appendChild(frag);

Testithere:createandappendanewdocumentfragment.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

172/223

5/30/2015

JavaScripttutorial

DOMtables

TkhtmlHv3onlysupportstable.tBodies,tBodies[].rows,rows[].cellsandchildNodes,butnoneoftheother
propertiesshownhere.
PrealphaversionsofTkhtmlHv3onlysupporttable.tBodiesandchildNodes,butnoneoftheotherproperties
shownhere.

Assuming that you have a reference to the table element (see the last section), you can do some
fairlyindepthmanipulationofthetable'sstructure.Inordertodothis,youhavetoviewtablesasin
thefullHTML4specification.Atablecontainsacaption,athead,anynumberoftbodies,andatfoot.
Ifyoudidnotspecifyatbody,theDOMwillstillhaveonetbodyinthe tBodiescollection,whichwill
containalloftherows.Therearemanymethodsassociatedwiththese.Mostofthosedesignedto
createpartsoftables,aswellastheonetodeletetablecaptions,arenotimplementedproperlyin
someolderbrowsers,soIwillconcentrateonthosethatarethemostreliable.
table
caption
childNodes[]
tHead
rows[]
cells[]
childNodes[]
tFoot
rows[]
cells[]
childNodes[]
tBodies[]
rows[]
cells[]
childNodes[]
AswellasbeingabletowalkthroughtheDOMtreeasbefore,youcanalsowalkthroughtheDOM
tabletree.EachtablehasfourextrapropertiesthatreferencethevariouschildNodes:
caption

Referencesthecaptionofthetable
thead

Referencesthetheadofthetable,ifthereisone
tfoot

Referencesthetfootofthetable,ifthereisone
tbodies

Acollectionwithoneentryforeachtbody(usuallyjusttable.tbodies[0])
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

173/223

5/30/2015

JavaScripttutorial

Eachthead,tbodyandtfootalsohasarowscollectionwithanentryforeachrowinthatthead,tbody
or tfoot. Each row has a cells collection containing every td or th cell in that row. Each cell then
containstheusualDOMreferencestoitscontents.
Eachtablealsohasthe createTHead()andcreateTFoot()methodstocreateorreturnthetheador
tfootrespectively,aswellasthe deleteTHead()and deleteTFoot() methods to delete them. There
arealsothecreateCaption()anddeleteCaption()methodstocreate/returnanddeletethecaption.
ThesemethodsdonotworkcorrectlyinInternetExploreronMac.Addingtbodiescanonlybedone
withbasicDOMmethodsthereisnodedicatedmethod.

Addingarowtoatable
InternetExploreronMachasverypoorsupportforcreatingtableelementsusingthededicatedmethodsasa
result,thistutorialavoidsthose,andusesnormalDOMcoreinstead.

The DOM provides dedicated methods for creating and adding rows, but these fail in Internet
ExploreronMac.ItiseasiertojustusenormalDOMmethods,sincetheseworkineverything:
vartheTable=document.getElementById('tableId');
theTable.tBodies[0].appendChild(document.createElement('tr'));

Rows have the rowIndex property, giving their index within their table, and the sectionRowIndex
property,givingtheirindexwithintheirthead/tfoot/tbody.
Thethead,tfootandtbodieseachhavethededicatedmethod insertRowwhichcanbeusedtoadd
rowsinallcurrentbrowsers.Thisacceptsaparameterthe0basedindexofwheretoaddthenew
row(or1toappenditattheend).Theyhavethe deleteRowmethodtodeletethem,whichaccepts
the same index parameter, with 1 deleting the last row. These methods do not work correctly in
InternetExploreronMac.

Addingonecelltoeveryrowinatable
InternetExploreronMachasverypoorsupportforcreatingtableelementsusingthededicatedmethodsasa
result,thistutorialavoidsthose,andusesnormalDOMcoreinstead.
OlderKonqueror,SafariandOmiWebgetthecellIndexpropertywrong.

Thisexampleaddsanewcellontheendofeveryrowinatable.Itassumesthattablehasbotha
thead,andatfoot.Again,therearededicatedmethodsforthis,butthesefailinInternetExploreron
Mac,sotheyarenotusedhere:
vartheTable=document.getElementById('tableId');
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

174/223

5/30/2015

JavaScripttutorial

for(varx=0;x<theTable.tHead.rows.length;x++){
vary=document.createElement('td');
y.appendChild(document.createTextNode('Theadcelltext'));
theTable.tHead.rows[x].appendChild(y);
}
for(varz=0;z<theTable.tBodies.length;z++){
for(varx=0;x<theTable.tBodies[z].rows.length;x++){
vary=document.createElement('td');
y.appendChild(document.createTextNode('Tbodycelltext'));
theTable.tBodies[z].rows[x].appendChild(y);
}
}
for(varx=0;x<theTable.tFoot.rows.length;x++){
vary=document.createElement('td');
y.appendChild(document.createTextNode('Tfootcelltext'));
theTable.tFoot.rows[x].appendChild(y);
}

Cells have the cellIndex property (except in early Konqueror versions), giving their index within
theirrow.
RowshavethededicatedmethodinsertCellwhichcanbeusedtoaddcellsinallcurrentbrowsers.
Thisacceptsaparameterthe0basedindexofwheretoaddthenewrow(or1toappenditatthe
end). The added cell will always be a td, not a th. Rows have the deleteCell method to delete
them,whichacceptsthesameindexparameter,with1deletingthelastrow.Thesemethodsdonot
workcorrectlyinInternetExploreronMac.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

175/223

5/30/2015

JavaScripttutorial

DOMCSS

Individualelementstyles
ICEbrowserandEscape/Evocannotreadorwritethefloatstyle.
NetFront3.5betafailsthrowserrorswhensettingclassName.

AsdescribedinthesectiononDHTML,DOMcompatiblebrowserssupportthestyleobject.Thestyle
objectwascreatedbyMicrosoftandalthoughonlybecameastandardinDOMLevel2CSS,there
was nothing to replace it in browsers supporting earlier DOM implementations, so it has been
universally adopted by all DOM browsers. Through the style object, DOM browsers allow allstyles
the element accepts to be changed, not just those I described in the section on DHTML. It is
equivalenttoreadingandwritingthevalueofthe styleattribute,sostylescanonlybereadifthey
weresetusingthatattribute.Stylesarealmostallread/write.
The syntax is simple. Simply write element.style.styleName. If the style name consists of two or
morewordsseparatedbyhyphens'',removethehyphenandcapitalisethefirstletteroftheword
following it. For example, backgroundcolor becomes backgroundColor. When setting a value, it
should be set as a string. Other data types will be converted to strings before setting the value to
that string. Although most browsers will allow you to delete a style by setting it to null, a browser
could legitimately set it to the string value 'null', and that would have an unwanted effect. If you
wanttodeleteastyle,setittoanemptystring,andneversetittonull.
Theonlyoddstyleis float,whichisareservedwordinmanylanguages,includingJavaScript.Asa
result,the floatstylemustbesetusing cssFloatinstandardscompliantbrowsers,and styleFloat
inInternetExplorer8and9+inquirksmode(somestandardscompliantbrowsersalsoprovidethis
as well). Simply set both of them. It will not cause any problems, and will work in all possible
browsers.
The W3C DOM does provide an alternative way to change the styles on individual elements. The
classattributeoftheelementcanberemovedusingthis:
element.className='';

Anditcanbechangedusing:
element.className='newClassName';

Readingappliedelementstyles
getComputedStyleandcurrentStylearenotsupportedbySafari2,Konqueror3.4orTkhtmlHv3.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

176/223

5/30/2015

JavaScripttutorial

WhenCSSstylesheetsareappliedtoapage,elementsmaybetargettedbyseveralstylerules,and
inherit various styles from their ancestors. They will also receive some default styling from the
browser's internal stylesheet. The DOM specification offers a way to work out what the result of
those styles was, using the window.getComputedStyle method. This is supported by Opera 7+,
Mozilla, iCab 3+, Konqueror 3.5+, and Chrome/Safari 3+, as well as Internet Explorer 9+ in
standards mode. Internet Explorer also offers an alternative that also works in quirks mode the
currentStylepropertyofanelement.ThisissupportedbyInternetExploreronWindowsandMac,

Opera9+andiCab3.
getComputedStyle requires two parameters. The first is a reference to the element. The second is

eitherthenameofapseudoelement(':before',':after',':firstline'),ornulljustfortheelementitself.
Since currentStyle only allows you to obtain the style for the element itself, that is all I will show
here. In most cases, the values returned by these are the same, but there are a few cases where
theymaybedifferent.Forexample,atablemayhaveawidthsetbytheCSS,butmaybestretched
widertofititscontents.Inthiscase currentStylewillstillreturnthewidthspecifiedbytheCSS,but
getComputedStylewillreturnthenewstretchedwidth.
varoElement=document.getElementById('mydiv'),oColor;
if(window.getComputedStyle){
oColor=window.getComputedStyle(oElement,null).color;
}elseif(oElement.currentStyle){
oColor=oElement.currentStyle.color;
}

As well as being an actual usable value, the returned value for several styles may be their default
values, such as 'auto', 'normal', or 'inherit'. The browser may also choose to return values in any
available unit. For example, even if the CSS specifies a length in 'em' units, the browser may still
returntheequivalentvaluein'px'units.
In cases where currentStyle gives a different result to getComputedStyle, Internet Explorer offers
an alternative runtimeStyle. This is an object almost exactly like currentStyle, but it gives a
computedvalueinsteadofacascadedvalue.However,itdoesnotalwaysgiveausablevalue,and
often gives a different kind of result to what would be expected from getComputedStyle, if it gives
any value at all. It often computes a blank string for unspecified values, instead of their default
values.Usethiswithcareandonlyifyouaresureitgivestheresultyouneed.
It is also possible to obtain some details of an element using its offset, client, and scroll values.
These are all available as properties of the element, and give its current dimensions in pixels, not
thestylesthatapplytoit.Thismeansthattheyalsogiverealdimensions,eveniftheCSSvalueis
'auto'. These are not reliable for inline elements, and should only be used for elements that have
block or equivalent display. Note that these properties were not standardised for a long time (they
willbepartoffutureDOMstandards),buttheyworkfairlyreliablycrossbrowser.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

177/223

5/30/2015

JavaScripttutorial

offsetWidthandoffsetHeight

Thedimensionsoftheelementtakenoutsideitsborder.(ThewidthinsidethepaddinginIE's
quirksmode.)
clientWidthandclientHeight

Thedimensionsoftheelementtakeninsideitsborder,andminusanyscrollbarsize.
scrollWidthandscrollHeight

The dimensions the element would be using if it did not have a scrollbar and was not
constrained in size (in other words, the dimensions of its contents, plus its padding). Only
usableandreliableiftheelementactuallyhasascrollbar.
scrollLeftandscrollTop

Thedistancetheelementhasbeenscrolled.

Rewritingstylesheets
TheDOMallowsthestylesheetsthemselvestobechanged.Somebrowsersallowstylesheetstobe
modified,somealsoallowrulestobecreatedorremoved.Thiswillbecoveredinthenextchapterof
thistutorial.

Changingthehrefofalinkedstylesheet
Thehrefofthestylesheetcanbereadinsomebrowsersusingthehrefproperty.Opera7+,Mozilla,
Konqueror, Safari/Chrome and Internet Explorer 5+ can set the href of the link element using
setAttribute on the link tag, and Internet Explorer 4+ can also set the href of the
styleSheets[index].

Switchingstylesheets
ThisissupportedcorrectlybyIE4+Win,IE5+Mac,Gecko(Mozilla/Firefox/Netscape6+),andOpera9+.
ThisissupportedincorrectlybyKHTML/WebKit(Konqueror3+/Safari/Chrome/OmniWeb4.5+)andICEbrowser.
ThisissupportedalmostcorrectlybyIE4Mac.
ThisissupportedcorrectlyusingadifferentsyntaxbyOpera7+andiCab3.
ThisissupportedcorrectlyusingadifferentsyntaxbyKHTML/WebKit.
iCab3failstostopapplyinggeneratedcontentandHTMLelementcolorfromthepreferredstylesheetwhenitis
disabled.

Thestylesheetcanbedisabled/enabledinsomebrowsersusingthebooleandisabledproperty,but
some browsers will only allow you to change the disabled property if the title attribute is set. To
create the most reliable cross browser effect, the function I have written (below) will only try to
enable/disableastylesheetifitstitleattributehasbeenset.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

178/223

5/30/2015

JavaScripttutorial

Thebestuseofthedisabledpropertyistoallowyourreaderstochangethelookofthesitetosuit
theirpersonaltastesoraccessibilityrequirements.Thisrequiresthemtobeabletoswitchbetween
the different stylesheets that you provide. Most often, this technique is used along with cookies,
storingtheuser'spreferenceofstylesheetastheyleavethepage(viatheonunloadevent)andthen
usingitagainnexttimetheyviewthepage(usingtheonloadevent).

SettinguptheHTML
Todothis,setoutyourdocumentasfollows:
Firstly,ifyouneedone,createapersistentstylesheetwithallglobalstyles,usingthis:
<linkrel="stylesheet"type="text/css"href="all.css">

Asithasnotitleattribute,itwillneverbedisabled.Youdonothavetodefinethisstylesheetifyou
do not want to, but if you do, remember that all styles you define in it will be used in all stylesheet
modes,andwillbeusedalongwithanystylesheetyoulaterusebystylesheetswitching.
Thedefaultswitchable(preferred)stylesheetissetupusingthis:
<linkrel="stylesheet"type="text/css"href="default.css"title="Default">

This will also be used by browsers that cannot disable/enable stylesheets and ensures that the
defaultviewwilllookgood.Youcanthensetupallalternativestylesheetsusingthis:
<linkrel="alternatestylesheet"type="text/css"href="extraPretty.css"title="Pretty">
<linkrel="alternatestylesheet"type="text/css"href="bigFont.css"title="BigFont">
<linkrel="alternatestylesheet"type="text/css"href="contrast.css"title="HighContrast">

Because these stylesheets are set up using 'alternate stylesheet' for the 'rel' attribute, lesser
browsers will not use these stylesheets at all, and in browsers that can switch stylesheets, these
stylesheetswillbedisabledbydefault.

Changingthestylesheetswiththebrowsers'viewmenu
Opera7+,Mozilla,InternetExplorer8+,Konqueror3+andiCab3+willallowuserstochoosefrom
these alternative stylesheets in the 'view' menu. However, this setting is not remembered by the
browser (except by Konqueror), so the user will have to choose this for every page they view on
yoursite.Also,other'good'browsers,likeInternetExplorer7andSafari/Chromedonotallowthe
user to choose stylesheets in any menus, so you will have to use the DOM to change them
manually. Note that when using the view menu or the DOM technique, stylesheets that share the
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

179/223

5/30/2015

JavaScripttutorial

sametitlewillbetreatedasiftheywerethesamestylesheetandwillbeswitchedtogether.
Usingtheviewmenuonlyallowsyoutoselectstylesheetswhosetitlesareidentical.Ifyouwantto
enable combinations, you would either have to produce combined stylesheets or include the same
sheet multiple times with different titles to allow all combinations. This is also a problem with most
basicstylesheetswitchingscripts.ThescriptIwillshowyouallowsyoutochooseacombinationof
stylesheettitles,makingitsuperiortomostotherscripts.

Referencingthestylesheet'sdisabledpropertyandtitleproperty
document.stylesheets

Microsoftfirstcameupwiththe document.styleSheetscollection.TheW3Cdecidedthiswasagood
ideaandintroduceditinDOMLevel2CSS.Allstylesheetsareavailableinthiscollection,evenifthe
rel attribute is set to 'alternate stylesheet'. Setting the disabled property of the collection entry
disablesandenablesthestylesheet,andthetitleattributeisavailablehereasaJavaScriptproperty.
InternetExplorer4+Winand5+Maccorrectlysupportdocument.styleSheets.
Internet Explorer 4 Mac supports document.styleSheets but does not provide the title attribute.
Instead,

the

title

of

the

style

or

link

element

must

be

used:

document.styleSheets[0].owningElement.title.

Gecko(Mozilla/Firefox/Netscape6+)correctlysupportsdocument.styleSheets.
Opera9+correctlysupportsdocument.styleSheets.
Konqueror

and

Safari/Chrome

[KHTML/WebKit]

incorrectly

only

populate

the

document.styleSheetscollectionwithstylesheetsthatareenabledatanyparticularinstant.The

stylesheetscannotbedisabledfromhere,anddonothavethetitleproperty.
ICEbrowserpopulatesthecollectionandallowsthestylesheettobeenabled/disabledbutonlyif
the rel attribute is set to 'stylesheet' and not 'alternate stylesheet' this defies the purpose of
switchingstylesheets,andgoesagainsttheW3C'sHTMLspecificationsoIjustacceptthatitwill
nothandlethescriptcorrectly.ICEbrowseruserswillhavetojuststicktothedefaultstylesheet,
atteptingtochangeitwillleavethemonlywiththepersistentstylesheet.
NetFrontprovidesthecollectionbutitisalwaysempty...
Opera78andiCab3donotprovidethecollectionatall.
Referencingthetags

The equivalent to document.styleSheets can be produced by referencing the relevant LINK and
STYLEtags.Thedisabledpropertycanbereadandmodified,andthetitleattributeisavailable.You
willneedtomakesurethatthelinktagsarebeingusedtoimportstylesheetsbycheckingtheir'rel'
attributeaslinktagshavemanyuses.
Internet Explorer 4+ Win supports this technique, but until the disabled property has been set
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

180/223

5/30/2015

JavaScripttutorial

withJavaScript,itwillshowasfalse,evenifthe'rel'attributeissetto'alternatestylesheet'and
hencethestylesheetisdisabled.
InternetExplorer4+Maccorrectlysupportsthistechnique.
Gecko(Netscape6+,Mozillaetc.)correctlysupportsthistechnique.
Opera9+correctlysupportsthistechnique.
Konqueror and Safari/Chrome [KHTML/WebKit] support this technique, but until the disabled
property has been set with JavaScript, it will show as false, even if the 'rel' attribute is set to
'alternatestylesheet'andhencethestylesheetisdisabled.
Opera78andiCab3+supportthistechnique,butuntilthedisabledpropertyhasbeensetwith
JavaScript,itwillshowasfalse,evenifthe'rel'attributeissetto'alternatestylesheet'andhence
thestylesheetisdisabled.Also,changesmadeusingtheviewmenuwillnotbereflected.
ICEbrowserdoesnotsupportthistechnique.
Youcanseethatfromthesepoints,thefollowingisrequired:
UsethelinkandstyletagtechniqueinOpera78andiCab3andmakesurethatyoudonottry
tostoretheuser'spreferenceuntiltheyhavechosenastylesheet.
Eitherof:
UsethelinkandstyletagtechniqueinOpera9+.
Usethedocument.stylesheetscollectioninOpera9+.
UsethelinkandstyletagtechniqueinKHTML/WebKitandmakesurethatyoudonottrytostore
theuser'spreferenceuntiltheyhavechosenastylesheet.
Eitherof:
UsethelinkandstyletagtechniqueinGecko.
Usethedocument.stylesheetscollectioninGecko.
Eitherof:
Use the link and style tag technique in IE using document.all.tags to reference them in IE 4
and make sure that you do not try to store the user's preference until they have chosen a
stylesheet.
Usethedocument.stylesheetscollectioninIE,asthismakesiteasiertoincludeIE4aswell
makesureyouusethetitlefromtheowningElementifthetitleisnotimmediatelyavailable.
Use the document.stylesheets collection in ICEbrowser, but only bother if you are not using
alternatestylesheets.
The W3C says the correct method is to use the styleSheets collection, but since that would only
workinthreebrowsers,andcauseproblemsforothers,Iwillusethelinkandstyletagtechnique.I
will add support for ICEbrowser, just in case they ever fix its handling, or in case you only want to
switchpreferredstylesheets.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

181/223

5/30/2015

JavaScripttutorial

Thebestwaytocheckiftheuserhasusedtheviewmenuistocheckwhatstylesheetsareenabled
onload and onunload. If they are different, the user has chosen something from their view menu
(this is not possible in Opera 78, as the disabled property does not reflect changes made in the
viewmenu).Ofcourse,youshouldalsocheckifthechangeStylefunctionhasbeenrunbymakingit
storeavariabletosayso.
Youmaywanttousethecorrecttechnique,butifyoudo,youwillstillneedtodothelinkandstyle
tagtechniqueforOpera78andiCab(using if(!document.styleSheets) etc.), and you will need to
do a browser detect to make KHTML/WebKit use the link and style tag technique, and you will still
needtomakesureyoudonotstorethepreferenceinKHTML/WebKit,iCabandOpera78untilthe
userhaschosen,andyouwillneedtocompensateforthelackoftitleinIE4Mac.

Thescript
Note, because getElementsByTagName returns an object with element 'index' and 'length'
properties,andnotatruecollection,wecannotusethe array.concatmethodtoappendthe'arrays'
oflinktagsandstyletags.Instead,wemustcyclethroughthecollectionsandaddeachelementin
turn.
functiongetAllSheets(){
//ifyouwantICEbrowser'slimitedsupport,doitthisway
if(!window.ScriptEngine&&navigator.__ice_version){

//IEerrorsifitseesnavigator.__ice_versionwhenawindowisclosing

//window.ScriptEnginehidesitfromthat
returndocument.styleSheets;}
if(document.getElementsByTagName){
//DOMbrowsersgetlinkandstyletags
varLt=document.getElementsByTagName('link');
varSt=document.getElementsByTagName('style');
}elseif(document.styleSheets&&document.all){
//notallbrowsersthatsupplydocument.allsupplydocument.all.tags
//butthosethatdoandcanswitchstylesheetswillalsoprovide
//document.styleSheets(checkingfordocument.all.tagsproduceserrors
//inIE[WHY?!],eventhoughitdoesactuallysupportit)
varLt=document.all.tags('LINK'),St=document.all.tags('STYLE');
}else{return[];}//lesserbrowserreturnablankarray
//foralllinktags...
for(varx=0,os=[];Lt[x];x++){
//checkfortherelattributetoseeifitcontains'style'
if(Lt[x].rel){varrel=Lt[x].rel;
}elseif(Lt[x].getAttribute){varrel=Lt[x].getAttribute('rel');
}else{varrel='';}
if(typeof(rel)=='string'&&rel.toLowerCase().indexOf('style')+1){
//filloswithlinkedstylesheets
os[os.length]=Lt[x];
}
}
//includeallstyletagstooandreturnthearray
for(varx=0;St[x];x++){os[os.length]=St[x];}returnos;
}
functionchangeStyle(){
for(varx=0,ss=getAllSheets();ss[x];x++){
//foreachstylesheet...
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

182/223

5/30/2015

JavaScripttutorial

if(ss[x].title){
//disablethestylesheetifitisswitchable
ss[x].disabled=true;
}
for(vary=0;y<arguments.length;y++){
//checkeachtitle...
if(ss[x].title==arguments[y]){
//andreenablethestylesheetifithasachosentitle
ss[x].disabled=false;
}
}
}
if(!ss.length){alert('Yourbrowsercannotchangestylesheets');}
}
...
eg.
<bodyonload="changeStyle('HighContrast','BigFont');">

Reduced,thatbecomesthis:
functiongetAllSheets(){
if(!window.ScriptEngine&&navigator.__ice_version){returndocument.styleSheets;}
if(document.getElementsByTagName){varLt=document.getElementsByTagName('link'),St
=document.getElementsByTagName('style');
}elseif(document.styleSheets&&document.all){varLt=document.all.tags('LINK'),
St=document.all.tags('STYLE');
}else{return[];}for(varx=0,os=[];Lt[x];x++){
varrel=Lt[x].rel?Lt[x].rel:Lt[x].getAttribute?Lt[x].getAttribute('rel'):'';
if(typeof(rel)=='string'&&rel.toLowerCase().indexOf('style')+1){
os[os.length]=Lt[x];}
}for(varx=0;St[x];x++){os[os.length]=St[x];}returnos;
}
functionchangeStyle(){
for(varx=0,ss=getAllSheets();ss[x];x++){
if(ss[x].title){ss[x].disabled=true;}
for(vary=0;y<arguments.length;y++){
if(ss[x].title==arguments[y]){ss[x].disabled=false;}
}}}

Testitusingthestylesheetswitcherdemopage.
See my stylesheet switching header file for a working example that can store the user's choice of
stylesheet,eveniftheyusetheviewmenuinGecko.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

183/223

5/30/2015

JavaScripttutorial

DOMStyleSheets

DOMStyleSheetsallowyoutostepthroughtherulesofeachstylesheet,changetheselectors,read
and write styles, and add new rules. This allows you to create or change CSS that affects several
elements at the same time, instead of just one element as with traditional DHTML. It allows you to
take advantage of CSS selectors to target the desired elements, and enter rules into the CSS
cascade.
CurrentlythisissupportedaccordingtotheDOMstandardbyOpera9+,Mozilla/FirefoxandInternet
Explorer 9+ (in standards mode). It is partially supported by Safari, Chrome, Konqueror and
ICEbrowser,buttheirsupportissobaditislargelyunusable.Iwillgivedetailsofwhatfailsinthese
browsersforeachoperation.SupposedlyyoucanusethehasFeaturemethodtocheckifabrowser
supportsDOM2StyleSheetswellenough,butunfortunatelySafari/ChromeandICEbrowserreturn
truefortheStyleSheetsandCSSfeatures.Theirsupportissopoorthatthisisaninsulttothespec.
I suggest you ignore Safari/Chrome, Konqueror and ICEbrowser for now, and hope that their
supportimprovesinthefuture.
IfyouneedcompatibilitywithSafari/Chrome,Konqueror,ICEbrowser,oranybrowserthatdoesnot
supportDOMStyleSheets(likeiCaborOpera8orbelow),thenyoushouldensurethatyourscript
does not requre document.styleSheets to be supported, and that if it uses it, it does not produce
errorswhensomethingfailsinoneofthesebrowsers.
Internet Explorer 8 does not comply with the standard here, so if you are testing, use a browser
thatsupportsthestandardcorrectly,suchasOpera9+orMozilla.Iwillgivedetailslateronhowto
get support for Internet Explorer 8 as well. Internet Explorer 9+ only adds support for DOM Style
Sheets in standards mode. In quirks mode or IE 7 compatibility mode, only the Internet Explorer
model is provided, along with its limitations. Internet Explorer on Mac supports large parts of the
InternetExplorermodel,butitalsoprovidesthe cssRulescollection,eventhoughitdoesnotuseit
according to the spec. I recommend you ignore IE Mac, but I will include it in the Internet Explorer
sectionlateroninthischapter.
DOM stylesheets does not provide an exact copy of what you put in your stylesheet. It produces
what the browser sees, and what it interprets. Rules that it does not understand are not included,
whitespacemaybeaddedorremoved,combinedstylesmaybesplitintotheircomponents,andsplit
styles may be combined. Styles that are not understood will be ignored. Comments will not be
included.Donotexpecttobeabletorecogniseyourownstylesheet.
NotethatyoushouldnottryusingDOM2StyleSheetsuntilyouarecertainthatthestylesheethas
completed loading (typically this means waiting for the document's onload event to fire). If you
attempttoaccessitbeforethen,thecssRulescollectionmaybetooshortormaynotexist.

ThestyleSheetslist
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

184/223

5/30/2015

JavaScripttutorial

MozillagivesSTYLEelementstylesheetstheaddressofthecurrentpageastheirhrefproperty,insteadofnull.
InternetExplorer9+incorrectlyclaimsthatstylesheetsarenotdisabled,evenwhentheir mediaattributecauses
themtobedisabled.
Opera9.2doesnotprovidethehrefpropertyforstylesheetsaddedusingXMLprocessinginstructions,andthey
cannotbedisabled.
SafariandKonqueroronlypopulatethelistwithstylesheetsthatareenabledatthespecifictime,meaningthatif
youusealternatestylesheets,mostofthemwillbemissingfromthelist.Safari2andKonquerordonotprovide
thetitleproperty,andtheydonotletyoumodifythedisabledproperty.
Safari 3, Konqueror and ICEbrowser do not include stylesheets added using XML processing instructions
(ICEbrowserdoesnotunderstandXML).
SafariandKonquerorwillpopulatethelistwithstylesheetsthatareaddedtothe BODYwithDOM,butthesewill
havenostylingeffectsonthedocument(stylesheetsareonlyallowedinthedocumentHEAD).
ICEbrowser only populates the list with persistent/preferred stylesheets, meaning that if you use alternate
stylesheets,theywillbemissingfromthelist.
ICEbrowserdoesnotadddynamicallygeneratedstylesheetsintothecollection.
NetFrontprovidesthecollectionbutitisalwaysempty.

Allstylesheetsareavailablethroughthe document.styleSheetscollection.Thisincludesstylesheets
addedusing <style> and <link> tags, including persistent, preferred and alternate stylesheets, no
matteriftheyareenabledornot.Evenstylesheetsaddedusingstylesheetprocessinginstructions
in XML based documents should be included. They are available in the collection in the order that
they appear in the document source. Imported stylesheets are not included in the list (as they are
includedthroughtheirparentstylesheet),andwillbedealtwithlater.Thecollectiondoesnotinclude
thecontentsof <divstyle="etc">attributestheymustbeaccessedthroughthe style property of
theelement(seethesectiononDHTMLformoredetails).
This provides an easy way to check if a browser supports some amount of DOM Style Sheets, by
checkingfortheexistenceofthedocument.styleSheetscollection:
if(document.styleSheets){
//DOMstylesheetsareavailable
}

Each stylesheet has a number of properties that give details of the stylesheet, such as its URL
( href),itstitle( title),itstype( type,usually'text/css'),themediatypesitappliesto( media),andif
it is disabled or not ( disabled). The disabled property can be set to true or false to disable or
enablethestylesheet,buttheotherpropertiesareallreadonly.Thepropertieswillonlybeavailable
iftheyactuallyapplytothestylesheetinquestion.Forexample,ifalinkelementdoesnothavethe
titleattributeset,thenitsassociatedStyleSheetobjectwillnothaveatitle.
Testithere:seethepropertiesofthefirststylesheetinthisdocument.

RelationshipsbetweentheStyleSheetobjectandtheHTMLtagsthatcreatethem

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

185/223

5/30/2015

JavaScripttutorial

Safari2andKonquerordonotprovidethesheetpropertyforlinkedstylesheets.
ICEbrowserdoesnotprovidethesheetpropertyforanystylesheets.

IfyouhaveareferencetotheLINKorSTYLEelement,youcanreferencetheassociatedStyleSheet
objectusingthesheetpropertyoftheelement.
vartheSheet=document.getElementsByTagName('style')[0].sheet;

Similarly,ifyouhaveareferencetotheStyleSheetobject,youcanreferencetheassociatedLINKor
STYLEelementbyusingtheownerNodepropertyoftheStyleSheetobject.
vartheElement=document.styleSheets[0].ownerNode;

Testithere:checkfortheseproperties.

Stylesheetmedia
InternetExplorer9+sometimesfailstoredrawthepagewhenmediatypesarechangedonlinkedstylesheets,but
willupdateeachpartofthepageasitreflows.
InternetExplorer9+failstorecognisewhenmediaTextischangedonstylesheetsaddedwithstyletags,unless
thetagoriginallyhadamediaattribute.
InternetExplorer9+incorrectlyallowsscriptstosetinvalidmediatypes.
Internet Explorer 9+ incorrectly returns an empty string when reading media.item(index) for outofbounds
indexes.
Opera11+failstorecognisewhenachangeinmediaTextcausesthestylesheetnottoapplyanymore.
Safari2andKonquerorsometimesputanextracommaontheendofthemediaText(makingitinvalid).
Safari3,KonquerorandICEbrowserdonotallowmediatypestobeaddedorremoved.
ICEbrowserignoresmediaattributes,andtreatsmediaTextasablankstring.

ThemediapropertyofthestylesheetreferencesaMediaListobject.Thisallowsaddingandremoving
of media types. It has a property mediaText that gives the full contents of the LINK or STYLE
element's media attribute. Note that browsers are free to add or remove spaces, as they decide is
appropriate.Theymayalsoremoveanymediatypestheydonotunderstand,ormayrenamethem
(typicallyto'unknown').Ifthetextcontainsthesamemediatypemorethanonce,thebrowsermay
removetheextracopies.Itispossibletosetthistexttoanewstringifdesired:
document.styleSheets[0].media.mediaText='print,handheld';

Modifying the media types that the stylesheet applies to is mostly useful if the browser supports
multiplemediatypes.OfthebrowsersthatsupportDOMstylesheets,onlyOperasupportsmorethan
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

186/223

5/30/2015

JavaScripttutorial

justscreenandprint(Operaalsosupportsprojection,handheld,speech,andonsomedevices,tv).
This means that currently, this feature is most useful in Opera, but can also be useful in other
browsersifyouwishtochangebetween'all','screen',and'print'.Notethatthebrowsermaysupport
media queries, and the specification never took these into account. Currently this affects Opera.
Opera normalizes media queries (removing spaces and reformatting), to make sure that only one
copyofeachequivalentquery(withparametersinthesameorder)exists.
If you set the mediaText to a value containing media types the browser does not recognise, it will
allow that, and simply ignore unknown media types. Setting the media text to a value that the
browserdoesnotrecogniseasvalidsyntaxwillthrowanerror,sobrowsersthatdonotunderstand
mediaquerieswillnotallowyoutosetmediaTextcontainingamediaquery.Youwillneedtousea
try...catchstatementaroundtheassignment.

Themediaobjectalsoprovidesthe appendMediummethodtoallowyoutoappendonemediatypeat
a time, and the deleteMedium method to delete one at a time. Deleting a medium that is not in the
list,orthatthebrowserdoesnotunderstand,willcauseittothrowanerror.Notethatastylesheet
withnomediaisappliedtoallmediatypes.Addingamediumtoastylesheetthathasnospecified
media will cause it to be applied only to that media type. Deleting all media types from the list will
causethemediatexttobeempty,soitwillbeappliedtoallmediatypes.
document.styleSheets[0].media.appendMedium('handheld');
document.styleSheets[0].media.deleteMedium('print');

You can also step through all the listed media types using the item method, and check how many
areinthelistbycheckingthelengthparameter.
for(vari=0;i<document.styleSheets[0].media.length;i++){
alert(document.styleSheets[0].media.item[i]);
}

Testithere:
Appendtheprintmediatypetoallstylesheetsonthispage.
Thepageshouldappeartohavelostallitsstylinginformation.
Youcanthentestifitworkedbyusingyourbrowser'sprintpreviewfeature.
IfyouareusingOpera,youcanalsoappendthehandheldmediatypetoallstylesheetsonthis
page,andtestitusingViewSmallscreen.
Checkwhatmediatypesthefirststylesheetisusing.
Youcanthendeletetheprintmediatypeanddeletethehandheldmediatype.

StylesheetcssRulescollection

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

187/223

5/30/2015

JavaScripttutorial

Mozilladoesnotprovidethiscollectionforalternatestylesheetsthatdonothaveatitleattribute.
Safari2andKonquerorcannotaddorremoverules.
Safari/Chrome,Konqueror,InternetExplorer9+andICEbrowserignoresome@rulesthattheydounderstand,
suchas@charsetrules.
ICEbrowsercannotaddrules.

Stylesheets all have the cssRules collection, that contains all the rules of the stylesheet. This only
includesrulesthatareintherootofthestylesheet,andnot,forexampleina @mediablock(thesewill
bedealtwithlater).Browsersmaychoosenottoinclude@rulesthattheydonotrecognise(initially
the spec said to include them, but the authors of the spec have now said not to). They will not
include any rules that they do not understand, such as rules using a selector that they do not
recogniseasbeinginavalidformat.Thismeansthatthe cssRulescollectionwillalmostcertainlybe
a different length in different browsers, and you cannot rely on it being a certain size if you use
features that are not supported by all the browsers. Note that although most browsers understand
@namespace rules, they are not part of the specification. Only Mozilla adds these to the cssRules

collection,asanunknownrule.
Rulescanbeaddedtothecollectionusingthe insertRulemethodofthestylesheet,specifyingthe
texttointerpretasanewrule,andtheindexspecifyingtherulenumberthatthenewruleshouldbe
added before. To add a rule at the end, the index should be the number of rules currently in the
stylesheet. Rules can be removed using the deleteRule method of the stylesheet, specifying the
indexoftheruletoremove.Asalways,theindexstartsat0forthefirstrule.
document.styleSheets[0].deleteRule(1);//deletethesecondrule
document.styleSheets[0].insertRule('html{color:lime;}',0);//addanewruleatthe
start
varoLength=document.styleSheets[0].cssRules.length;
document.styleSheets[0].insertRule('body{background:#779;}',oLength);//addanewrule
attheend
varoRule=document.styleSheets[0].cssRules[oLength];//referencethenewrulewejust
added

ThispartofDOM2StyleSheetsisoneofthemostusefulandimportant.Sinceaddingandremoving
rules is not supported by Safari 2 and Konqueror, and only removing rules is supported by
ICEbrowser,theyaregenerallyuselessforDOM2StyleSheets.
Testithere:addthenewrule'p{color:lime;}',andthendeleteitagain.
For security reasons, Opera and Mozilla will not allow you to access the cssRules collection of a
stylesheet from another domain or protocol. Attempting to access it will throw a security violation
error. If your script is likely to encounter a stylesheet like this, you should use a try...catch
structuretopreventyourscriptfromhalting.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

188/223

5/30/2015

JavaScripttutorial

TheCSSrule
Mozilla,Safari/Chrome,Konqueror,InternetExplorer9+andICEbrowsercannotrewriterulesusingcssText.
InternetExplorer9+retainsunrecognisedstylesinthecssText,insteadofremovingthem.
SettingrulecssTextwillcauseOpera99.2toapplytheoldversionoftheruleaswellasthenewone.
Safari2andKonquerordonotprovidecssTextfortheCSSruleobject.
Safari2,KonquerorandICEbrowserremoveanynamespaceprefixfromtheselectorpartoftherule,meaning
thatitappearstotargetelementsthatitdoesnot.
Safari 2 and ICEbrowser make the selector part of the rule upper case, so it is not valid for XML based
documents.
Safari2corruptsID,attribute,andclassselectorsbeyondrecognition,makingtheminvalidanduseless.
ICEbrowseraddswildcardstotheselectorpartoftherulewherewildcardsareassumed.
ICEbrowserchangesclassselectorsto[class~=attribute]selectors.
TheselectorpartoftheruleonlyincludeseverythinguptothefirstcommainICEbrowser.

This is the most fundamental part of DOM 2 Style Sheets viewing or changing the styles of each
rule. Each entry in the stylesheet's cssRules object is a CSS rule. There are several types of rule
thatmayexistinastylesheet,andthepropertiestheyprovidewilldependonwhattypeofrulethey
are.
Eachrulehasatypeproperty,sayingwhattypeofruleitis.Thiswillbe1fornormalstylerules,2for
@charsetrules,3for @importrules,4for @mediarules,5for @fontfacerules,and6for @pagerules.If

the browser does not ignore unknown @ rules, their type will be 0. CSS rules will also have the
parentStyleSheet property, which is a reference to the stylesheet they are inside. Typically, you

wouldneedtousethetypepropertytoworkoutwhatotherpropertiesyouwillbeabletoaccess.
The rule also has a cssText property that gives a text representation of the rule. This may have
whitespaceaddedorremoved,andstylesmaybesplitorcombinedintocomponentstyles.Multiple
copiesofthesamestylemaybereplacedwithasinglecopyoftheonethatisactuallyused.Inmost
cases,itnolongerlooksliketherulethatwasintheoriginalstylesheet,butitshouldhavethesame
effectinthatbrowser(thoughnotnecessarilyinotherbrowsers)astheoriginalrule.
vartheRule=document.styleSheets[0].cssRules[0];
alert('Type:'+theRule.type+'\nRule:'+theRule.cssText);

Testithere:alertthefirstruleinthefirststylesheetofthispage.
In theory it is possible to set the cssText to a new value, as long as the new value can be
interpretedasthesametypeofruleastheoriginalrule(soitisnotpossibletoconverta@importrule
intoa@mediarule,forexample).Unfortunately,browsersupportisnotgoodenoughtousethisatthe
moment.
document.styleSheets[0].cssRules[0].cssText='body{background:#779;}';
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

189/223

5/30/2015

JavaScripttutorial

Iftheruleisa @charsetrule,itwillhavean encodingproperty,givingtheencodingstring,whichcan


be rewritten if desired. Unknown @ rules will have no other properties. All other rule types will be
coveredbelow:

Normalstyle,@page,and@fontfacerules
MozilladoesnotallowsettingofruleselectorText.
Mozillasplitssomevalidstyles(suchas'padding')intoseveralinvalidstyles(suchas'paddingleftvalue'and
'paddingleftltrsource:physical;').

Mozillaaddsastrange'*|'namespaceprefixtoelementselectors,butonlyifthereisatleastone@importrulein
oneofthedocument'sstylesheets,andifthereareatleasttwoLINKelementsinthedocument(atleastoneof
whichmustbeastylesheet).
Opera10+doesnotlikehavingexistingstylevaluessettoanemptystring,andmaynotupdatetherendering
setthemtoanactualvalueinstead.
Safari2corruptsID,attribute,andclassselectorsintheselectorTextbeyondrecognition,makingitinvalidand
useless.
Safari2alwaysreturnsnullwhenusingtheitemmethodonarule.
Safari2andKonquerorcannotadd,removeorchangestylesfromaruleusingthemethodsofthestyleobject.
Safari2,KonquerorandICEbrowsercannotrewriterulesusingstyle.cssText.
Safari 2, Konqueror and ICEbrowser remove any namespace prefix from the selectorText, meaning that it
appearstotargetelementsthatitdoesnot.
Safari2andICEbrowsermakeselectorTextuppercase,soitisnotvalidforXMLbaseddocuments.
ICEbrowsercannotchangerulestylesusing.style.colorsyntax.
selectorTextonlyincludeseverythinguptothefirstcommainICEbrowser.

ICEbrowseraddswildcardstotheselectorTextwherewildcardsareassumed.
ICEbrowserchangesclassselectorsto[class~=attribute]selectors.
ICEbrowsercannotretrievevaluesofshortformstyleslike'margin'andcanonlyretrievevaluesfortheexpanded
form'marginleft'.
ICEbrowserreturnsallpixelvalueswithadecimalpoint'0.0px'.
ICEbrowserignoresprioritieswhensettingstyles.

These are the most common rule types, and the majority of stylesheets contain only normal style
rules. The normal style rule and the @page rule have the selectorText property, which gives the
selector text for the rule. This may have whitespace added or removed. In theory, this can be
rewritten if desired, but unfortunately, browser support is not good enough to use this at the
moment.
document.styleSheets[0].cssRules[7].selectorText='div>p';

All three rule types also have a style property. This is the same in functionality as the style
propertyofelementsthatisnormallyusedforDHTML.However,browsersthatsupportDOM2Style
Sheetsusuallyimplementmoreofthelesswellknownmethodsassociatedwiththe styleobject.As
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

190/223

5/30/2015

JavaScripttutorial

wellastheusual .style.colorsyntaxthatiswellknown(andevenworksinSafariandKonqueror),
thereareseveralotherwaystoaccessandmodifythestylesoftherule:
ThecssTextpropertygivesthetextrepresentationofallthestylesthattherulecontains.Thismay
be reformatted with altered whitespace, may or may not have a final semicolon, and styles may or
maynotbesplitorcombined.Itispossibletosetthistoanewvalue,replacingalltheoriginalstyles
withanewsetofstyles.
document.styleSheets[0].cssRules[7].style.cssText='color:lime;fontweight:bold;';

The length property can be used to find how many styles the browser sees, and the itemmethod
canbeusedtoretrievethestylenamesoneatatime.The getPropertyValuemethodretrievesthe
value of a named style. The getPropertyPriority method retrieves the priority of a named style
(typically 'important'). The removeProperty method removes a named style (it will do nothing if the
styleisnotbeingused).Lastly,the setPropertymethodcreatesorrewritesastyle.Itrequiresthree
parametersthestylename,thevalue,andthepriority.
varoStyle=document.styleSheets[0].cssRules[0].style;
oStyle.setProperty('color','lime','');
oStyle.setProperty('fontweight','bold','important');
for(vari=0,j,s='';i<oStyle.length;i++){
j=oStyle.item(i);
s+=j+'='+oStyle.getPropertyValue(j)+''+oStyle.getPropertyPriority(j)+'\n';
}
alert(s);
oStyle.removeProperty('color');
oStyle.removeProperty('fontweight');
alert('Newcontent:'+oStyle.cssText);

Test it here: the last rule in the demo stylesheet is currently 'p{}'.Try running the script shown
aboveonit.

@importrulesandimportedstylesheets
InternetExplorer9+throwsanerrorifyouattempttoaccessthemediaattributeofanimportrule.
Safari/Chrome, Konqueror and ICEbrowser actually get this one right. I felt it an important enough event to
mentionit.
@import rules are similar to a HTML LINK element, in that they reference a new stylesheet. They

havesomeextrapropertiesthatreflectthatrole.
The href property gives the URL referred to by the import rule. This may be a complete address
(typically beginning with 'http://'), or may be the exact URL given by the @import rule (such as
'imported.css')thiswilldependonthebrowser.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

191/223

5/30/2015

JavaScripttutorial

@importrulescancontainalistofmediatypesaswell,althoughthisfeatureisnotveryoftenused.

As a result, the rule object also has the media property, which behaves exactly like the media
propertyoftheStyleSheet.
Most importantly, the rule object also has the styleSheet object. This references the StyleSheet
objectfortheimportedstylesheet,anditsrulescanbereferencedandmodifiedinexactlythesame
way as a normal stylesheet. The imported stylesheet also has the ownerRule property that
referencesthe@importrulethatimportsit.
alert(document.styleSheets[0].cssRules[0].styleSheet.cssRules[0].cssText);

@mediablocks
Safari/ChromeandKonquerordonotprovidetheparentRulepropertyforrulesina@mediablock.
ICEbrowserdoesnotunderstandmediaqueriesbutinterpretsthemasamediablockwiththeirtokenstreatedas
separatemediatypes.
@media blocks allow you to target a selection of style rules to a specific set of media types. The
@mediaruleappearsasasingleruleinthestylesheet's cssRulescollection.Thestylerulesinsideit

do not appear in the stylesheet's cssRules collection at all. Instead, the rule has its own cssRules
collection,thatcontainsallthestyleswithinit.Thiscollectionbehavesinexactlythesamewayasthe
cssRulescollectionfortheStyleSheetobject.

The@mediarulealsohastheinsertRuleanddeleteRulemethods,whichbehaveinthesamewayas
those for the StyleSheet object. As the @media rule also has a list of media types, it also has the
mediaproperty,whichalsofunctionslikethatoftheStyleSheetobject.

Allrulesinsidethe @mediablockalsohavethe parentRuleproperty,whichreferencesthe @mediarule


that they are inside. @media blocks may contain other @media blocks, and these can be nested as
much as needed. If they are nested, their rules must be accessed by going through the chain of
cssRulescollections.
alert(document.styleSheets[0].cssRules[0].cssRules[0].cssText);

Testithere:showthecontentsofthelastrecognisedmediablockinthefirststylesheet.

GettingsupportforlegacyInternetExplorer
Internet Explorer 8 on Windows and Mac does not provide many of the DOM 2 Style Sheets
methods or properties, but it has an alternative that is not as complete as the standard, but can
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

192/223

5/30/2015

JavaScripttutorial

handle basic stylesheet manipulation. Internet Explorer 9+ follows the DOM standard only in
standards rendering mode. Pages rendered in quirks mode will need to use the Internet Explorer
model instead. Pages rendered in IE9+'s IE 7 compatibility mode (enabled automatically or by the
useronsomepages,orbydefaultforintranetsites)willalsonotbeabletousethestandardmodel.
IfyouneedInternetExplorer8(or9+quirksmode)support,youwillhavetoacceptthedifferences
andlimitations,makesureyourcodedoesnotrelyonthepartsthatInternetExplorerismissing,and
implementthebranchingcodeIwillshowyouhere.
In standards rendering mode, Internet Explorer 9+ maintains both the DOM and IE models, which
are completely separate. When referencing the same rule using both collections, the returned
objectsarenotthesameaseachother.Thecommonpropertiesinbothmodels(like selectorText)
can hold completely different values, depending on the bugs present in the implementation of that
model. This can catch scripts out very easily, so it's best to use the least buggy model the DOM
model.

ThestyleSheetslist
InternetExploreronMacdoesnotpopulatethelistwithstylesheetsthatareaddedusingDOMafterthepagehas
loaded.
ThemediapropertyisreadonlyinInternetExploreronMac.
Settingmediato'print'followedby''causesInternetExplorer8onWindowstostartusingprintmediainstead
ofscreenmediafornormalWebpageviewing.

InternetExplorerprovidesthesamecollectionastheotherbrowsers,andtoalargeextentitworks
the same way. The type, disabled, href, and title properties all work the same way. The media
propertyisdifferent.Insteadofbeingamediaobject,itisastring.Asaresult,therearenomethods
to add, remove, or list media types. If you want to change it, you will need to treat it as a string.
TryingtosetitwillthrowanerrorinIEMac,soitwillneeda try...catchstatement.(NotethatinIE
9+standardsmode,IEprovidesbothmodelsthemediaattributefollowsthestandardsmodel.)
varoSheet=document.styleSheets[0];
if(typeof(oSheet.media)=='string'){
try{oSheet.media='screen';}catch(e){}
}else{
oSheet.media.mediaText='screen';
}

Testithere:setthemediatypeonallstylesheetsonthispageto 'print'(thepageshouldappear
unstyledwhenviewednormally),useprintpreviewtocheckifitworked,thenreturnittonormal.
Eachstylesheetcanreferencetheelementthatcreatesitusing owningElement,inthesamewayas
standardscompliantbrowsersuseownerNode.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

193/223

5/30/2015

JavaScripttutorial

varoSheet=document.styleSheets[0];
varoElement=oSheet.ownerNode?oSheet.ownerNode:oSheet.owningElement;

Although IE on Windows provides the styleSheet property of the LINK or STYLE element, in the
samewayasstandardscompliantbrowsersusesheet,thispropertyisnotavailableinIEonMac.
varoElement=document.getElementsByTagName('style')[0];
varoSheet=oElement.sheet?oElement.sheet:oElement.styleSheet;

Testithere:checkfortheseproperties.

StylesheetcssRulescollection
InternetExploreronMaccannotaddorremoverules.

Internet Explorer provides the rules collection, in the same way as standards compliant browsers
usecssRules.However,itsbehaviourissufficientlydifferentandincompatible,soitisnotpossibleto
simplyindexthesameruleineachcollection. @page,@media, @import, @charset,and @fontfacerules
are not included in the collection. In IE on Windows, all rules inside a @media block are included in
therulescollectionofthestylesheet.InIEMac,theyareignoredcompletely,andarenotavailable
totheDOM.Inbothbrowsers,itisnotpossibletomodifythe @mediaruleitself.Addingnewrulesinto
a@mediablockisnotpossibleinIEonWindows.
NotethatthestylesheetitselfhasacssTextpropertyinIE,whichgivesalltheCSSinthestylesheet.
OnWindows,[email protected],itisnotmuchfuntoeditthestylesheetusing
patternmatching,whichisallthatthiscanprovide.
IEonMacprovidesboththerulesandcssRulescollections,buttreatsthemboththeIEway(sothe
cssRules collection is too short). Internet Explorer 9+, also provides both collections in standards

renderingmode,butthistime,theyareimplementedcompletelyseparatelyusingtheIEandDOM
models.InIE9+,youwouldalmostcertainlywanttousethestandardonewhereitisavailable,while
IEonMacwouldwanttousetheIEmodel.Ifyoudon'tcareaboutIEonMac(it'sbeendiscontinued,
so you probably don't care about it), then simply check for the DOM collection and use it where
available,fallingbacktotheIEmodelotherwise:
varoSheet=document.styleSheets[0];
varoRule=oSheet.cssRules?oSheet.cssRules[7]:oSheet.rules[3];

However,itispossibletogetsupportforIEonMac.CheckifthestadardDOMcollectionisavailable,
andmakesurethatitisnotthesameastheIEcollection(thatcheckwillalsoworkinotherbrowsers
thatdonotprovidetheDOMcollection,sincetheIEcollectionwillbeundefined):
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

194/223

5/30/2015

JavaScripttutorial

varoSheet=document.styleSheets[0];
varoRule=(oSheet.cssRules&&oSheet.cssRules!=oSheet.rules)?oSheet.cssRules[7]:
oSheet.rules[3];

Adding and removing rules in Internet Explorer (on Windows) is done using the addRule and
removeRule methods. The removeRule method is exactly the same as the standard deleteRule

method (except of course that the index will be different). The addRule method, however, is very
different to the standard insertRule method. Firstly, it requires two different parameters the
selectorstring,andtherulestring.Secondly,itcanonlyaddaruleattheendofthestylesheet.
varoSheet=document.styleSheets[0];
if(oSheet.deleteRule){
oSheet.deleteRule(7);
}elseif(oSheet.removeRule){
oSheet.removeRule(3);
}
if(oSheet.insertRule){
oSheet.insertRule('body{background:#779;}',oSheet.cssRules.length);
}elseif(oSheet.addRule){
oSheet.addRule('body','background:#779;');
}

Testithere:addthenewrule'p{color:lime;}',andthendeleteitagain.

TheCSSrule
selectorTextonlyincludeseverythinguptothefirstcommainIE8,andafterthelastcommainIE9+.
selectorTextaddswildcardsforselectorswherewildcardsareassumedinIE.
cssTextcontainsthe{}bracesinIEmac(italsoincludesthemforElement.style.cssText).

Thestyle.item(0)methodreturns'}'inIEmaciftheruledoesnothaveanystylesthatitrecognises.
ElementsandstylenamesinselectorTextandcssTextareuppercaseinIE(meaningthattheyarenotvalidfor
XMLbaseddocuments).
selectorTextisreadonlyinIEMac.

Sincetherulescollectiononlycontainsnormalstylerules,therulesdonothavea typeproperty.In
IEonWindows,theyalsodonothave cssText.Theydohavea selectorTextpropertythough,and
(apartfromafewbugs)itbehavesexactlythesameaswithstandardscompliantbrowsers.Similarly,
theyalsohavetheparentStyleSheetproperty.
They also have the all important style property. However, here there are some significant
differences. The item method does not exist in IE on Windows. You can try using
for(iinstyleobject)butthatdoesnotreturnwhatyouspecifyinthestylesheet.Instead,itsteps

throughallpossiblestylesthatIErecognises,whetheryouactuallyusedthemornot.Itisactuallya
fairlyshortlist(sinceIEdoesnotactuallysupportverymanystyles),butitmakesrecognisingyour
ownstylesveryhard.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

195/223

5/30/2015

JavaScripttutorial

More importantly, however, IE does not provide most of the other methods of the styleobject.To
read or change styles, you will have to stick to the .style.color syntax. Since this works in all
browsers,thatisnottoodifficulttoworkwith.NotethatIEwillthrowerrorsifyousetstylestovalues
thatitdoesnotsupport(suchassetting displayto'table').Notethatthe .style.cssTextproperty
isavailable,butIEMacmakesabitofamessofit.
varoSheet=document.styleSheets[0];
varoRule=oSheet.rules?oSheet.rules[3]:oSheet.cssRules[7];
oRule.style.color='lime';

Testithere:thelastruleinthedemostylesheetiscurrently 'p{}'.Setitscolorpropertyto 'lime',


thensetitbackto''.
Thereisalsoa StyleSheet.pagescollectionthatgivesall @pagerules,butitdoesnotgiveanyuseful
informationaboutthestylesinthatrule.

@importrulesandimportedstylesheets
@importrulesarelistedintheirown StyleSheet.importscollectioninIE.Eachentryinthiscollection

isaStyleSheetobject,thatisthesameasthe styleSheetpropertyofthe @importruleinstandards


compliantbrowsers.Ithasthesamepropertiesasanormalstylesheet.
varoSheet=document.styleSheets[0],oImportedSheet;
if(oSheet.imports){
oImportedSheet=oSheet.imports[0];
}else{
oImportedSheet=oSheet.cssRules[0].styleSheet;
}

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

196/223

5/30/2015

JavaScripttutorial

DOMevents

This is currently supported by Opera 7+, Mozilla/Firefox, Konqueror 3.0+, Safari/Chrome, Internet
Explorer 9+ in standards mode and NetFront 3.3+. It is also partially supported by iCab 3,
ICEBrowser 5+, and Tkhtml Hv3. Espial claim that Escape/Evo 5 supports this, but it does not
supporteventhebasics.
Note:InternetExplorer8onWindowsdoesnotcomplywiththestandardhere,soifyouaretesting,
use a browser that supports the standard correctly, such as Opera. Internet Explorer 9+ drops
supportforthestandardmodelinquirksmodeandIE7compatibilitymode,andwillcontinuetoneed
the Internet Explorer 8 workarounds. I will give details later on how to get support for Internet
Explorer 8 on Windows as well. Internet Explorer on Mac does not support either the DOM or IE
eventsmodels.

Problemswiththetraditionaleventmodels
Traditionally, browsers had a simple way to listen for events, and run scripts when that happened.
The script could be held inside an appropriate event handler attribute, such as
onclick="alert('here');".Internally,thebrowserwouldregisterthisasananonymousfunction,that

ascriptcouldoverride:
referenceToElement.onclick=function(){alert('here');};

Returning false from any event handler function would prevent the normal action from happening,
suchaspreventingthebrowserfollowingalinkwhenitdetectedtheclickevent.
In many basic applications, this was adequate. However, it has limits. If an event handler already
exists,andyouwanttoaddfunctionalitytoitpartwaythroughyourscript,youwouldhavetorewrite
the function with both the new and old functionality. Then if you wanted to remove some
functionality, you would have to rewrite it again. You might even have to write your own handler
functionmanagementsystem,withoneeventhandlerthatrunstheappropriatefunctionsinturn.
Anotherproblemwiththetraditionalmodelwasthatitnevercopedwellwiththepossibilitythattwo
elementsmaydetectthesameevent.Imaginethatalinkisinsideadiv,andboththelinkandthediv
aresetuptodetecttheclickevent.Whenyouclickthelink,shouldthelinkseetheclick?Orshould
thedivseeit?Orshouldboth?Ifbothshoulddetectit,inwhatordershouldtheyseeitdivfirst,or
linkfirst?
Initially,whenNetscapeintroducedevents,theiranswerwassimplethelinkshouldseeit.Nothing
more.Later,theyallowedthedivtoseeitaswell,butonlyifyoutoldittocapturetheevent.Thediv
wouldthenseetheclick,andafterthat,thelinkwouldseeit(inNetscape'soriginalimplementation,
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

197/223

5/30/2015

JavaScripttutorial

theeventwouldonlybeseenbythelinkifyouexplicitlytoldittocontinueaftertheinitialcapture
thisisnotnecessaryinDOM2events).Atthesametime,InternetExplorerintroducedanalternative
version. By default, both the link and the div would see the click, and unlike in Netscape, the link
wouldseeitfirst.Thiswascalledbubbling.

AddingDOMeventlisteners
ICEbrowsersometimesfailstodetectthepage'sloadevent.
ICEbrowserwillforgettoremovelistenersifyoureload,sotheeffectiscumulative.
TkhtmlHv3versionsbeforeSeptember2007fireeventsonlyinthebubblingorder,butfireboththebubblingand
capturinglisteners(inthatorder).

The DOM 2 events module was designed to cope with all possibilities, so not only could you add
multipleeventhandlersforasingleevent,butyoucouldalsosayinwhatorderelementsshouldsee
theevent.TheDOMreferstotheseeventhandlerfunctionsaseventlisteners.Thewaytoaddan
eventlistenerislikethis:
referenceToElement.addEventListener('nameOfEvent',referenceToFunction,phase)

Youcanaddasmanylistenersforthesameeventonthesameelementasyouwant,butnotethat
thereisnowaytoguaranteeinwhatordertheywillberun.(Tryingtoaddthesameevent,function,
and phase to the same element multiple times will result in it being added just once.) Note that,
unlikewiththetraditionaleventsmodels,itisnotpossibletoobtainareferencetotheeventhandler
functions(thiscouldpreviouslydonewithreferenceToElement.oneventname,butDOM2eventsdoes
notprovideanyequivalenttolistalltheeventhandlers).
Thenameoftheeventiswrittenlikethis:'click','mouseover',or'keyup'.Thereferencedfunction
will be run in much the same way as with the traditional model. According to the spec, the
'referenceToFunction' parameter should actually be a reference to an object that has a method

called 'handleEvent', and that method will be called instead. However, in practice, Opera 8+,
Mozilla/Firefox, Konqueror 3.2+, Safari/Chrome, Internet Explorer 9+ and iCab implement this
correctly,buttheothersdonot.Aditionally,mostauthorsarenotevenawarethatthisfunctionality
exists.Inmostcases,itiseasiesttojustuseadirectfunctionreference.
Thephasesaysinwhatordertheeventshouldbedetected.Falsemeansthebubblingphase,and
is usually the one you want to use. True means the capturing phase. Any event handlers added
usingthetraditionaltechniquesaretreatedasabubblingeventlistener.Thephaseisactuallyvery
important to get right, since its behaviour is not straightforward. Capturing is special. According to
thespecification,ifanelementissetuptocaptureaclickevent(forexample),andyouclickit,the
event handler should not be run. It should only be run if you click on a child element inside the
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

198/223

5/30/2015

JavaScripttutorial

element.Inotherwords,thecapturephaseisonlyusedonancestorsofthetargetelement.
In our earlier link and div example, assume that both elements are set up to detect the click event
using both the capturing and bubbling phase. If you click the link, the specification says that the
eventlistenersshouldberuninthisorder:
1. Capturelistenersforthediv
2. Bubblinglistenersforthelink
3. Bubblinglistenersforthediv
This progression from listener to listener is known as propagation. You can check what stage the
propagation is at by checking the eventObject.eventPhase property. It should be 1 during the
capturephase,2duringthebubblephaseonthetargetelementitself(inthiscasethelink),and3
duringthebubblingphaseonthetarget'sancestors.Itcanalsobe0ifitisamanuallycreatedevent
objectthathasnotyetbeenfired.Seebelowforfurtherdetails.
Note that some events (such as the load event) do not bubble up to ancestors, but they will still
capture, so capture phase listeners will always see the events of their children (with load events
detected in the capture phase on the document, this means they should see an event every time
anyimage,plugin,ormanyotherembeddedfiletypesload).
Alsonotethatintheaboveexample,onlyOpera9.2,Safari1.1,NetFront3andICEBrowserfollow
thespecification.Mozilla/Firefox,Opera9.5+,Konqueror,Chrome/Safari1.2+,InternetExplorer9+,
Netfront 4+ and iCab will fire the capture listeners on the link. Mozilla 1.7/Firefox 1.0 will fire it
before point 3. Opera 9.5+, Konqueror, Safari, iCab and Mozilla 1.8+/Firefox 1.5+ before point 2
givingthis(commonlysupported)eventpropagation:
1. Capturelistenersforthediv
2. Capturelistenersforthelink
3. Bubblinglistenersforthelink
4. Bubblinglistenersforthediv
ThatbehaviouriswrongaccordingtoDOM2Events,butitisreliedonbymanyWebpages,soitit
unlikely that the browsers will follow the DOM 2 Events specification. It may be changed to be
correctinDOM3(thoughitcurrentlyisnot),inwhichcasetheotherbrowserscanbeexpectedto
implementitthatwayaswell.However,youshouldbeawarethatbrowsersmaybehaveeitherway.
Do not rely on the capturing phase firing on the target, since it is currently incompatible, and may
wellbechangedatsomepoint.
Sonow,toputthisexampleintopractice:
<divid="thediv"><ahref="/"id="thelink">test</a></div>
...
varoDiv=document.getElementById('thediv');
varoLink=document.getElementById('thelink');
oDiv.addEventListener('click',function(e){
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

199/223

5/30/2015

JavaScripttutorial

alert('1.Divcaptureran');
},true);
oDiv.addEventListener('click',function(e){
alert('3.Divbubbleran');
},false);
oLink.addEventListener('click',function(e){
alert('Linkcaptureranbrowserdoesnotfollowthespecification');
},true);
oLink.addEventListener('click',function(e){
alert('2.Linkbubbleran(firstlistener)');
},false);
oLink.addEventListener('click',function(e){
alert('2.Linkbubbleran(secondlistener)');
},false);

Testithere:clickthislinktoactivatetheeventlisteners.
Notethatsomebrowserswillrunthefirstlinkbubblelistenerbeforethesecond,andsomewillrun
the second before the first the standard does not say in which order they should be run, and it
evenallowsthemtoberunatthesametimeyoushouldnotrelyonanyspecificbehaviourhere).

Removingeventlisteners
Removingeventlistenersisaseasyasaddingthem:
referenceToElement.removeEventListener('nameOfEvent',referenceToFunction,phase)

Note that you can remove event listeners at any time, and you must remove them using the exact
sameparametersasyouaddedthemwith.ThiscanbedifficultifyouusedanonymousfunctionsasI
did in the example above. If you use anonymous functions, you can use the arguments.callee
property provided by JavaScript to reference the function and remove the listener. This reference
can only be done from inside the listener itself. So for example, to add an event listener that
removesitselfafterithasfiredonce,youcanuse:
oLink.addEventListener('click',function(e){
alert('Linkbubblefired');
this.removeEventListener('click',arguments.callee,false);
},false);

Test it here: fire the event listener and see if it can remove itself (you should get an alert the first
timeyouclickthelink).

Referencingtheelementsthatdetecttheevent
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

200/223

5/30/2015

JavaScripttutorial

YoumaynoticethatIusethe 'this'keywordinthelastexample.Insideaneventlistenerfunction,
the 'this' keyword is a reference to the element that is currently detecting the event. In the first
example,thatcouldbethediv,orthelink,dependingonwhichonetheeventlistenerisattachedto.
You may also notice that the functions accept a parameter (I called it 'e', but you could call it
whateveryouwant).Thatparameter,aswiththeoriginalNetscapeeventmodel,istheeventobject,
andcontainsalotofinformationabouttheevent.Fornow,Iwillstickwiththebasics.
eventObject.currentTargetisthesameas 'this'itreferstotheelementthatthelistenerfunction

isattachedto(ifthesamefunctionisattachedasalistenertoseveralelements,itwillbeareference
tothelistenerthatiscurrentlybeingrun).
eventObject.target is the element that the event actually happened to. In the case of the earlier

example, this would be the link. If there was a span inside the link, and you clicked that, then
eventObject.target would be a reference to the span, even if the span itself did not have any

listeners attached directly to it. Note that older Safari and Konqueror sometimes make the target
pointtothetextNodeinsidetheelement.Thatisincorrectbehaviour,andisfixedincurrentversions.
Ifthisislikelytocauseproblems,checkthenodeTypeofthetarget.IfitisatextorCDATAnode,then
youwillneedtouseitsparentnodeinstead.
vartheTarget=e.target;
if(theTarget&&(e.target.nodeType==3||e.target.nodeType==4)){
theTarget=theTarget.parentNode;
}

Testithere:clickanywherewithinthissentencetoseewhatelementyouclicked.
Some events (such as mouseover) will also provide eventObject.relatedTarget. This will be a
reference to the element the mouse was over before it was moved over the current element. With
mutationevents,itistypically(butnotalways)theparentnodeofthenodebeingmanipulated.

Obtainingotherinformationfromtheevent
Information such as mouse button and position, keyCode, ctrlKey, altKey, shiftKey, and detail
(suchasclickcount)areavailableinthesamewayaswiththeoldermodel(seetheHTMLevents
section of this tutorial for more details). They are available as properties of the event object.
Mutation events can also provide prevValue, newValue, attrName and attrChange values (see the
DOM2eventsspecificationformoredetails).

Preventingthedefaultaction

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

201/223

5/30/2015

JavaScripttutorial

In the example above, clicking the links will activate the listeners, but the link will be followed
anyway. Returning false from a listener function does not work like it used to in the traditional
models.Instead,youmustuse eventObject.preventDefault()onlyoneeventlistenerneedstorun
thismethodforthedefaultactiontobeprevented.
Notalleventtypescanbecancelled(theloadevent,forexample,hasnodefaultaction,andcannot
becancelled).Ifaneventisofatypethatcanbecancelled,the eventObject.cancelableproperty
willbetrue.
oLink.addEventListener('click',function(e){
alert('Linkdetectedaclick.Cancellable:'+e.cancellable);
e.preventDefault();
},false);

Testithere:ifyouclickthislink,youshouldremainonthispage.

Preventingotherlistenersfromseeingtheevent
TkhtmlHv3doesthiscorrectly,butbecauseversionsbeforeSeptember2007activatethelistenersinthewrong
order,theyappeartofailhere.

When an event is being processed by the event listeners, it is possible for any event listener to
prevent any more event listeners in the propagation chain from seeing the event. In the example
above, the div's capture phase click event listener could prevent the other event listeners from
seeingtheclickevent,byusingtheeventObject.stopPropagation()method.Notethatyoucancheck
iftheeventisatypethatcanbubblebycheckingtheeventObject.bubblesproperty.
The stopPropagation method only prevents listeners further along the propagation chain from
seeingtheevent.Forexample,Iaddedtwoeventlistenerstothelinkinthebubblephase.Ifoneof
theseusesthe stopPropagationmethod,theotheronewillalwaysrun,nomatterinwhatorderthe
browser ran them. The method would only stop the event listener that was added to the div in the
bubblephase.
<divid="thediv"><ahref="/"id="thelink">test</a></div>
...
varoDiv=document.getElementById('thediv');
varoLink=document.getElementById('thelink');
oDiv.addEventListener('click',function(e){
alert('Divcaptureran.Nowstoppingpropagation.');
e.stopPropagation();
},true);
oLink.addEventListener('click',function(e){
alert('Thisalertshouldneverappear');
},false);

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

202/223

5/30/2015

JavaScripttutorial

Testithere:clickthislinktoactivatetheeventlisteners.

Morethanbasicevents
As well as the basic events defined in HTML, DOM 2 provides aditional event types that can be
detected. A useful example of these are the mutation events. These fire when elements or
descendantnodesareadded,modified,orremovedbyascript(Iwillnotgointomoredetailhere,
see the DOM 2 events specification for more details). They are partially supported by Opera,
Mozilla/Firefox, Konqueror, Safari/Chrome and Internet Explorer 9+. Note that browser support for
'DOMNodeInsertedIntoDocument',

'DOMNodeRemovedFromDocument',

and

'DOMSubtreeModified'

eventsiscurrentlyverypoor,sotheseeventsshouldnotbeused.Safari4alsodoesnotworkwith
the 'DOMAttrModified' event. Note that Opera 7.1, Safari 1.2, and Konqueror 3.23.3 will crash if
you attempt to use any mutation events. Opera 7.2+, Safari 1.3+, and Konqueror 3.4+ will work
correctly.Konqueror4.2.2seemstohavelostallsupportforallmutationevents.
The DOM does not provide any way to work out if the event will fire or not. If a browser does not
support an event, it will still allow you to add the event listener, but it will not fire the event. It is
possibletocheckifabrowsersupportstherequiredeventsmodelusinghasFeature,butthisisnota
perfect indication, since a browser will only claim to support the feature if its support is relatively
complete.Browsersmaysupportalargeamountofthefeature(enoughforwhatyouneed)butstill
notclaimtosupportit.Assumingyouwantarelativelycompleteimplementation,insteadofsupport
forjustoneortwoeventtypes,checkingformutationeventsisassimpleasthis:
if(document.implementation.hasFeature('MutationEvents','2.0'))

NotethatthiswillexcludeMozilla/Firefox,eventhoughitdoessupportmanyofthecommonmutation
events. You could alternatively check for the interface as well, since Mozilla/Firefox (Opera, newer
Safari/Chrome and Internet Explorer 9+ provide it too, but not Konqueror or older Safari) should
providethis:
if(document.implementation.hasFeature('MutationEvents','2.0')||window.MutationEvent)

Some other types of event may also cause problems, not because the browsers do not support
them,butbecausethebrowserssupportthemonlyonthewrongobject.Theloadeventistheworst
behavedinthisrespect.AccordingtotheoriginalDOM2eventsspecification,theloadeventshould
be detected on the document object. Unfortunately, the traditional models used the body tag, and
mapped it to the window object. As a result, when browsers added support for it via DOM, most of
theminitiallychosetodetectitonlyonthewindowobject.Futurespecificationswillmakeitmoreclear
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

203/223

5/30/2015

JavaScripttutorial

thatitshouldonlyworkwiththewindowobject.
Opera 10.1, and similarly aged versions of Konqueror, Safari/Chrome and NetFront correctly
detecteditonthedocumentobject(aswellasonthe windowobject,forcompatibilityreasons).This
waschangedinOpera10.5+,andsimilarlyagedversionsoftheotherbrowsers,tofollowtheMozilla
behaviour. Internet Explorer 9+ also follows the Mozilla behaviour. New implementations may
theoreticallyfollowtheDOMspecification,andonlydetectitonthe documentobject.Forthisreason,
you should check if the window and document objects can detect events before adding listeners to
them.Ifthebrowserallowsyoutoattacheventlistenerstothe window,youcanassumethatitcan
detecttheloadeventthere.Thisistrueforallcurrentimplementations.
Note also that as described above, you should always use the bubble phase when detecting load
events, or they will repeatedly fire when other embedded content loads. However, note that
Mozilla/FirefoxandiCab3cannotcaptureloadevents,Opera9.5+,Safari/Chrome,InternetExplorer
9+ and Konqueror only capture load events when the listener is attached to the document(notthe
window), and only Opera 9.2 and ICEBrowser correctly always capture load events. Unless you

really know what you are doing, and you have worked around all the incompatibilities, you should
only ever detect load events in the bubbling phase. Most importantly, do not rely on the
implementations of browsers that do not capture load events they are wrong, and the same code
willnotworkthesamewayinotherbrowsers.
if(window.addEventListener){
window.addEventListener('load',handlerFunction,false);
}elseif(document.addEventListener){
document.addEventListener('load',handlerFunction,false);
}

Congratulationsyourbrowserdetectedtheloadeventusingthisscript.
Thesituationissimilarforseveralotherevents,suchasscrollandresize.Theywillalsorequireyou
tousethewindowanddocumentbranches.

Manuallyfiringevents
Safari/Chromemakesthe keyCodeand charCodepropertiesreadonly,soitisnotpossibletosimulatespecific
keyswhenmanuallyfiringevents.
Mozilla/Firefoxincorrectlygeneratesthedefaultactionformouseandprintablecharacterkeyboardevents,when
theyaredispatchedonformelements.
iCab3,ICEbrowser,NetFront3.3andTkhtmlHv3cannotmanuallyfireevents(ICEbrowser,NetFront3.3and
TkhtmlHv3providethemethods,buttheydonotworkcorrectly).

With the old events model, it was easy to fire event handlers manually, using
referenceToElement.oneventname()sincetherewasonlyonepossiblehandler,anditwastreatedas
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

204/223

5/30/2015

JavaScripttutorial

amethod,itcouldberunaseasilyasanyothermethod.WiththeDOM2eventsmodel,thisisnot
possible, since there may be multiple handlers for the same event. The DOM provides a few
methodsthatcanbeusedtocreateandprepareafakeeventobject,thenuseittofiretheeventon
anytarget.
Theelementyoufireaneventondoesnothavetobelisteningforthatevent,sincepotentially,the
parentelementmayalsobelisteningforthatevent.
Notethatmanuallyfiringaneventdoesnotgeneratethedefaultactionassociatedwiththatevent.
Forexample,manuallyfiringafocuseventdoesnotcausetheelementtoreceivefocus(youmust
useitsfocusmethodforthat),manuallyfiringasubmiteventdoesnotsubmitaform(usethesubmit
method),manuallyfiringakeyeventdoesnotcausethatlettertoappearinafocusedtextinput,and
manuallyfiringaclickeventonalinkdoesnotcausethelinktobeactivated,etc.InthecaseofUI
events,thisisimportantforsecurityreasons,asitpreventsscriptsfromsimulatinguseractionsthat
interactwiththebrowseritself.
TherearefiveDOM2eventmodules,andtheymapdirectlytothenamesoftheDOMfeatures
Events
Coversalleventtypes.
HTMLEvents
Covers 'abort', 'blur', 'change', 'error', 'focus', 'load', 'reset', 'resize', 'scroll',
'select','submit',and'unload'.

UIEvents
Covers 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut',and(sincetheydonothavetheirown
key events module in DOM 2) it also covers 'keydown', 'keypress', and 'keyup'. Also
indirectlycoversMouseEvents.
MouseEvents
Covers'click','mousedown','mousemove','mouseout','mouseover',and'mouseup'.
MutationEvents
Covers

'DOMAttrModified',

'DOMNodeInserted',

'DOMCharacterDataModified',

'DOMNodeRemoved',

'DOMNodeInsertedIntoDocument',

'DOMNodeRemovedFromDocument',and'DOMSubtreeModified'.

Otherevents(suchas 'dblclick')arenotpartofthespecification,andbrowsersarenotrequired
tosupportthem.Browsersthatdosupportthemwilleitherchooseanappropriateeventmoduleto
class them as dblclick would fit very well into MouseEvents or they will create a new module.
You will need to know what module the browser has put the events into when you create these
events.
Fakeeventobjectsarecreatedusingthe document.createEventmethod,andtheappropriateevent
moduleshouldbespecifiedwhencreatingit.Theyarethenpreparedusingtheappropriatemethod,
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

205/223

5/30/2015

JavaScripttutorial

and finally they are then fired on the desired target element using the element.dispatchEvent
method.Ifyouusethemorespecificeventtypeinsteadofthegenericeventtype,youcanprovide
more information when preparing it. dispatchEvent will return false if the detault action was
prevented.
The event object methods for preparing the event object properties for the various event modules
are:
HTMLEventsandgenericEvents
initEvent('type',bubbles,cancelable)

UIEvents
initUIEvent('type',bubbles,cancelable,windowObject,detail)

MouseEvents
initMouseEvent('type',bubbles,cancelable,windowObject,detail,screenX,screenY,
clientX,clientY,ctrlKey,altKey,shiftKey,metaKey,button,relatedTarget)

MutationEvents
initMutationEvent('type',bubbles,cancelable,relatedNode,prevValue,newValue,
attrName,attrChange)

Note, although prevValue, newValue, and attrName can all be null, attrChange must always
beprovided,eveniftheeventisnotaDOMAttrModifiedevent(setitto1,2,or3)
MouseEventsareasubclassofUIEvents,andalleventmodulesareasubclassofEvents,soifyou
create a mouse event object, it will also inherit the initUIEvent and initEvent methods from the
moregenericUIEventsandEventsinterfaces.Youcanchoosewhich init*Eventmethodyouwant
tousewhenpreparingtheevent.
Thefollowingisanexampleoffiringaclickevent:
varfireOnThis=document.getElementById('someID');
varevObj=document.createEvent('MouseEvents');
evObj.initMouseEvent('click',true,true,window,1,12,345,7,220,false,false,true,
false,0,null);
fireOnThis.dispatchEvent(evObj);
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

206/223

5/30/2015

JavaScripttutorial

Testithere:moveyourmouseoverhereandIwillmanuallyfireamouseupeventinstead.
Thefollowingisanotherexampleoffiringaclickevent,thistimeusingthegenericinitEventmethod,
and leaving undefined properties at their default values (even when using the generic initEvent or
initUIEvent,youshouldstillusetheexactmodulename,andnotagenericmodule,oritwillnotwork
inMozilla/Firefox,Konqueror,orSafari/Chrome):
varfireOnThis=document.getElementById('someID');
varevObj=document.createEvent('MouseEvents');
evObj.initEvent('click',true,true);
fireOnThis.dispatchEvent(evObj);

Key events are a little harder, because Mozilla/Firefox does not implement the standard correctly,
anddoesnotallowyoutocreatekeyeventsusinggenericUIEvents(itmayjustcrash).Instead,it
provides a proprietary module 'KeyEvents', and initialisation method 'initKeyEvent'. The
proprietary initKeyEvent method expects the following parameters: 'type', bubbles, cancelable,
windowObject, ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode. You can use
if(window.KeyEvent) to detect support for the KeyEvents module. Browsers that expect you to use

UIEvents do not have a specific initialisation function for key events, so some properties must be
addedmanually:
varfireOnThis=document.getElementById('someID');
if(window.KeyEvent){
varevObj=document.createEvent('KeyEvents');
evObj.initKeyEvent('keyup',true,true,window,false,false,false,false,13,0);
}else{
varevObj=document.createEvent('UIEvents');
evObj.initUIEvent('keyup',true,true,window,1);
evObj.keyCode=13;
}
fireOnThis.dispatchEvent(evObj);

GettingsupportforlegacyInternetExploreronWindows
InternetExplorer8onWindowsdoesnotprovideanyoftheDOM2Eventsmethods,andprovides
veryfewofthepropertiesoftheeventobject.InternetExplorer9+alsodoesnotsupporttheDOM2
Events methods on pages that trigger quirks mode. Pages rendered in IE9+'s IE 7 compatibility
mode(enabledautomaticallyorbytheuseronsomepages,orbydefaultforintranetsites)willalso
not be able to use the standard model. Version 5.0+ (including IE9+ in quirks or standards mode)
does provide a similar system that is much more limited in its capabilities, but if you need legacy
Internet Explorer support, you will have to accept the differences and limitations, make sure your
codedoesnotrelyonthepartsthatInternetExplorerismissing,andimplementthebranchingcode
Iwillshowyouhere.
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

207/223

5/30/2015

JavaScripttutorial

Addingandremovinglisteners
Addingandremovingeventlistenersisdoneusingthesemethods:
referenceToElement.attachEvent('onNameOfEvent',referenceToFunction);
referenceToElement.detachEvent('onNameOfEvent',referenceToFunction);

These are almost synonymous with the addEventListener and removeEventListener methods, but
theyareunabletospecifyaphase.TheInternetExplorermodelonlydetectseventsinthebubbling
phase,notcapture.Italsorequires'on'tobeincludedatthestartoftheeventname,sofortheclick
event, you should use 'onclick' in IE, and not 'click'. (Note also that IE 8 only supports the
basiceventtypesitdoesnotsupportanyoftheadvancedtypes,suchasmutationevents.)Ifyou
needlegacyInternetExplorersupportaswell,youshouldusethiscode:
functioneventHandler(e){
alert('Divbubbleran');
}
varoDiv=document.getElementById('thediv');
if(oDiv.addEventListener){
oDiv.addEventListener('click',eventHandler,false);
}elseif(oDiv.attachEvent){
oDiv.attachEvent('onclick',eventHandler);
}

Test it here: this text has been set up to detect click events, and should alert a message when
clicked.

Referencingtheelementsthatdetecttheevent
InternetExplorer'smodelismoreannoyinghere.The 'this'keywordisareferencetothewindow
object.ThereisnoequivalenttotheeventObject.currentTargetproperty.InternetExplorer'smodel
makesitimpossibletoseewhatelementiscurrentlyprocessingtheevent.
Itispossibletoreferencetheactualtargetoftheevent,usingtheeventObject.srcElementproperty,
whichisequivalenttotheeventObject.targetpropertyprovidedbyDOM2Events.Unlikethewayit
workswithtraditionaleventmodels,IEdoescorrectlyprovidetheeventobjectasanargumenttothe
handler function when you use attachEvent. There is no need to check if window.event is needed
instead, because it is not needed. However, it is important to note that in IE, the event object only
existsforaslongastheinitialeventpropagationthread.Itcannotbestoredandreferencelater,or
usedintimeoutthreads.Touse srcElement,simplydetectwhatyouneed(makesurethestandards
compliantcheckismadefirst):
vartheTarget=e.target?e.target:e.srcElement;
if(theTarget&&(theTarget.nodeType==3||theTarget.nodeType==4)){
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

208/223

5/30/2015

JavaScripttutorial

theTarget=theTarget.parentNode;
}

Testithere:clickanywherewithinthissentencetoseewhatelementyouclicked.
Youcanalsodothesametogettheequivalentto eventObject.relatedTargetwhichisknownas
eventObject.fromElementinIE.Itisavailableformouseoverandmouseoutevents.
varrelTarget=e.relatedTarget?e.relatedTarget:e.fromElement;

Preventingthedefaultaction
The IE model does not provide eventObject.preventDefault() but provides an alternative. The
eventobjecthasapropertycalled 'returnValue'thatwillperformtheequivalentfunctionalityifitis
settofalse.Settingthisvalueinotherbrowserswillnotcauseanyproblems,sotheeasiestwayto
supportIEaswellislikethis:
if(e.preventDefault){e.preventDefault();}
e.returnValue=false;

Testithere:ifyouclickthislink,youshouldremainonthispage.
ItisnotpossibletocheckiftheeventisatypethatcanbecancelledinIE.

Preventingotherlistenersfromseeingtheevent
The IE model does not provide the stopPropagation method (probably because it only supports
bubbling). Instead, it uses a property called 'cancelBubble', which must be set to true to prevent
propagation.ItisnotpossibletocheckiftheeventisatypethatcanbubbleintheIEmodel.
if(e.stopPropagation){e.stopPropagation();}
e.cancelBubble=true;

Testithere:clickthislinktoactivatetheeventlisteners.

Detectingtheloadevent
LegacyInternetExplorerdetectstheloadeventonthe windowobject,usingtheusual attachEvent
method.Thismakestheloadeventlistener(shownabove)requireonemorebranch:

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

209/223

5/30/2015

JavaScripttutorial

if(window.addEventListener){
window.addEventListener('load',handlerFunction,false);
}elseif(document.addEventListener){
document.addEventListener('load',handlerFunction,false);
}elseif(window.attachEvent){
window.attachEvent('onload',handlerFunction);
}

Congratulationsyourbrowserdetectedtheloadeventusingthisscript.

Manuallyfiringevents
This is a little more messy than the other event handling, since the initialisation is considerably
different.TheInternetExplorermodelhasamethodformanuallyfiringevents,calledfireEvent,and
it is available in IE 5.5+ (there is no equivalent in IE 5.0). In its simplest form, this is similar to the
DOMversion,butthe bubblesand cancelable properties are not available. The fireEventmethod
expectstobepassedeitheroneortwoparameters.Thefirstshouldbethenameoftheevent(for
example 'onchange'),andtheoptionalsecondparametershouldbeaneventobjecttobepassed
tothehandler.
Note that even though the window object can detect several events in IE (such as load, unload,
scroll,andresizeallofwhichshould,accordingtothespec,bedetectedbythe documentobject,

notwindow),itisnotpossibletousefireEventonthewindowobject.
varfireOnThis=document.getElementById('someID');
if(document.createEvent){
varevObj=document.createEvent('MouseEvents');
evObj.initEvent('mousemove',true,false);
fireOnThis.dispatchEvent(evObj);
}elseif(document.createEventObject){
fireOnThis.fireEvent('onmousemove');
}

If you want to specify more details, you will need to use the createEventObject method in IE to
replicate the createEvent and init*Event methods of the DOM. The createEventObject method
normally returns a blank event object, and you will need to define parameters yourself. You can
optionally pass an existing event object to createEventObject, and it will use that as a template
whenpreparingtheneweventobject.Usually,youwillnotneedtopassitanyarguments.
varfireOnThis=document.getElementById('someID');
if(document.createEvent){
varevObj=document.createEvent('MouseEvents');
evObj.initMouseEvent('mousemove',true,false,window,0,12,345,7,220,false,false,
true,false,0,null);
fireOnThis.dispatchEvent(evObj);
}elseif(document.createEventObject){
varevObj=document.createEventObject();
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

210/223

5/30/2015

JavaScripttutorial

evObj.detail=0;
evObj.screenX=12;
evObj.screenY=345;
evObj.clientX=7;
evObj.clientY=220;
evObj.ctrlKey=false;
evObj.altKey=false;
evObj.shiftKey=true;
evObj.metaKey=false;
evObj.button=0;
evObj.relatedTarget=null;
fireOnThis.fireEvent('onmousemove',evObj);
}

Testithere:moveyourmouseoverhereandIwillmanuallyfireamouseupeventinstead.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

211/223

5/30/2015

JavaScripttutorial

DOMobjectsandmethods

This gives all properties, collections and methods of the W3C DOM that can be reliably used in all
majorDOMbrowsers,aswellasdocument.styleSheets,whichismuchlessreliable,butusefulifitis
available.

Contents
Thedocumentnode
Allnodes
Tableandassociatednodes
Stylesheets
Events

Key
Parentobject
Childobject
Childproperty
Childobjectbeingaccessedthroughacollection[]
Event
Method()
Eachcanbeclickedformoreinformation.
Collectionswillalsohavethelengthproperty,givingthenumberofentriesinthatcollection.

Thedocumentnode
Creatingnodes
documentThedocumentobjectforthecurrentdocumentreadonly
createDocumentFragment()Returnsadocumentfragmentthatcanbeusedtoaddmultiple
nodestothedocument
createElement('element_name')Returnsanewelementoftypeelement_name
createTextNode('textcontent')Returnsatextnodewithastringvaluematchingthetextcontent

TowalktheDOMtree
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

212/223

5/30/2015

JavaScripttutorial

documentThedocumentobjectforthecurrentdocumentreadonly
bodyTheBODYelementnodereadonly
documentElementTheHTMLelementnodereadonly
getElementById('elementid')Returnsareferencetotheelementwiththespecifiedid
getElementsByTagName('element_name')Returnsacollectionofallelementswiththespecified
elementnameNOTE:doesnotreturnatruecollectionreturnsanobjectwith.0....nand
.lengthproperties

DOMsupport
documentThedocumentobjectforthecurrentdocumentreadonly
implementationAnobjectgivinginformationabouttheDOMimplementation(Alsohasother
methodsingoodbrowsers[notcoveredhere])readonly
hasFeature(string:feature,string:domVersion)Returnstrueifthebrowsersupportsthat
featureoftheDOMspecificationDonotrelyonbrowserstoaccuratelyrepresenttheir
supportforfeatures

Allnodes
TowalktheDOMtree
IE8incorrectlyprovideselementmethodslikegetElementsByTagNameoncommentnodes.

nodeAnelement,textnode,documentnode,oranyothernodetypereadonly
childNodes[]Acollectionofalltextnodesandelementnodesthenodecontainsdirectlyifnode
isanelementnodeordocumentnodereadonly
parentNodeAreferencetothecontainingnodereadonly
firstChildThefirstentryinthechildNodescollectionifnodeisanelementnodeordocument
nodereadonly
getElementsByTagName('element_name')Returnsacollectionofallelementsinsidethecurrent
elementordocumentnode,withthespecifiedelementnameNOTE:doesnotreturnatrue
collectionreturnsanobjectwith.0....nand.lengthproperties
lastChildThelastentryinthechildNodescollectionifnodeisanelementnodeordocumentnode
readonly
nextSiblingThenextentryinthechildNodescollectionoftheparentnodereadonly
offsetParentThenodethattheelement'soffsetcanbecalculatedfromreadonly
previousSiblingThepreviousentryinthechildNodescollectionoftheparentnodereadonly

Attaching,copyingorremovingnodes
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

213/223

5/30/2015

JavaScripttutorial

nodeAnelement,textorattributenodereadonly
appendChild(nodeReference)AppendsthereferencednodetotheendofthechildNodes
collection,anddisplaysitonthepageIfitisalreadyattachedtothedocument,itwillbemoved
tothisnewlocation
cloneNode(bool:copyChildrenToo)ReturnsacloneofanodeorbranchoftheDOMtree,event
handlersmayormaynotbecloned
innerHTMLTheHTMLcontainedbytheelementSmallamountsofHTMLwillbeinsertedintothe
DOMtreeimmediatelyLargeamountsofHTMLmaytakeasmuchas1/2secondtobeinserted
intotheDOMtreeDoesnotworkwithXHTMLinsomebrowsersread/write
insertBefore(nodeReferenceX,nodeReferenceY)InsertsormovesnodenodeReferenceXasa
childNodeoftheelementbeforenodeReferenceY
removeChild(nodeReference)RemovesthespecifiedchildfromthechildNodescollection
(deletesit)IfchildNodes.lengthbecomes0,theparentNodeisalsodeleted
replaceChild(nodeReferenceX,nodeReferenceY)ReplaceschildnodeReferenceYwithnode
nodeReferenceXReturnsnodeReferenceY
splitText(index)Splitsatextnodeintotwoatthespecifiedindexcreatinganewentryinthe
childNodescollection

Nodeinformation
IE8incorrectlyprovideselementpropertiesliketagNameoncommentnodes.

nodeAnelement,textorattributenodereadonly
dataEquivalenttonodeValuewherenodeisatextnoderead/write
hasChildNodes()Returnsbooleanifthenodehaschildnodes
idTheidoftheelementread/write
nodeNameNameofthenode(tagname,attributenameor'#text')readonly
nodeType1foranelement/tag,2orundefinedforanattributeor3foratextnodereadonly
nodeValueThestringofatextnodeorattributenoderead/write
specifiedBoolean:saysifthenodehasavaluereadonly
tagNameAnuppercaserepresentationofthetagnameifnodeisanelementnodeIntheory,
thisshouldbelowercaseforXHTML(whenservedasXHTML,notHTML),butsomebrowserswill
stilluseuppercaseThispropertyisincorrectlyalsoprovidedoncommentnodesinIE8
readonly
titleThetitleattributeoftheelementread/write

Elementnodeattributes
nodeAnelementnodereadonly
attributes[]Anumericalcollectionofallattributesdefinedorthatcouldbedefinedforthe
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

214/223

5/30/2015

JavaScripttutorial

elementDifficulttousebecauseofbrowserincompatibilitiesread/write
getAttribute('attributeName')Returnsthevalueofthespecifiedattribute[notclass,styleor
eventhandler]
removeAttribute('attributeName')Removesthespecifiedattribute[notalign,class,styleorevent
handler]
setAttribute('attribute_name','attribute_value')Setsthename=valuepairforthespecified
attributeoftheelement[notname,class,styleoreventhandler]Usealongwithstyle.textAlignto
makealignworkinOpera7.07.1

Elementnodestyle
nodeAnelementnodereadonly
classNameTheclassnameoftheelementread/write
currentStyleAstyleobjectthatgivesthecascadedandinheritedstylesappliedtotheelement
readonlyIEcompatiblebrowsersonlyForcrossbrowserscripting,seealso
window.getComputedStyle
styleNameTextrepresentationofthenamedstylevalueread/only
runtimeStyleAstyleobjectthatgivesthecomputedstylesappliedtotheelementFrequently
givesuselessvaluesoremptystringsreadonlyIEonlyForcrossbrowserscripting,see
alsowindow.getComputedStyle
styleNameTextrepresentationofthenamedstylevalueread/only
styleAnobjectcontainingallinlinestylesoftheelementreadonly
styleNameTextrepresentationofthenamedstylevalueread/write
windowThewindowobjectforthecurrentdocumentreadonly
getComputedStyle(nodeReference,string:pseudoElement)Returnsastyleobjectthatgivesthe
cascadedandinheritedstylesappliedtotheelementpseudoElementparameteriseithera
pseudoelementname,ornullStandardscompliantbrowsersonlyForcrossbrowser
scripting,seealsoelementNode.currentStyleelementNode.runtimeStyle
styleNameTextrepresentationofthenamedstylevalueread/only

Elementnodesizeandposition(notstandardised)
nodeAnelementnodereadonly
clientHeightTheheightoftheelementinsideitsborder,minusanyscrollbarheightreadonly
clientWidthThewidthoftheelementinsideitsborder,minusanyscrollbarwidthreadonly
offsetHeightTheheightoftheelementoutsideitsborderreadonly
offsetLeftThedistancebetweentheleftedgeofthenodeandtheleftedgeoftheoffsetParent
nodereadonly
offsetParentTheparentelementthatthebrowserhaschosentobetheoffsetParentOnly
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

215/223

5/30/2015

JavaScripttutorial

reliablecrossbrowserifallchainedoffsetsareaddedtogetherreadonly
offsetTopThedistancebetweenthetopedgeofthenodeandthetopedgeoftheoffsetParent
nodereadonly
offsetWidthThewidthoftheelementoutsideitsborderreadonly
scrollHeightTheheightoftheelement'scontentsandpaddingOnlyreliableifithasahorizontal
scrollbarreadonly
scrollLeftThehorizontaldistancethattheelementhasbeenscrolledreadwrite
scrollTopTheverticaldistancethattheelementhasbeenscrolledreadwrite
scrollWidthThewidthoftheelement'scontentsandpaddingOnlyreliableifithasavertical
scrollbarreadonly

Tableandassociatednodes
In addition to the normal node functionality, nodes belonging to tables have extra functionality,
specially designed to work with the layouts of tables. All elements have their standard HTML
attributesavailableasproperties(usingthesamecasingpatternasstyleproperties).

TowalktheDOMtree
nodeAtable(orrelated)elementnodereadonly
captionThecaptionofthetableifelementisatablereadonly
cells[]Acollectionofallcellsintheelementiftheelementisatrreadonly
rows[]Acollectionofallrowsintheelementiftheelementisathead,tbodyortfootreadonly
tBodies[]Acollectionofalltbodiesinthetableifelementisatablereadonly
tfootThetfootelementofthetableifelementisatablereadonly
theadThetheadelementofthetableifelementisatablereadonly

Attaching,copyingorremovingnodes
nodeAtable(orrelated)elementnodereadonly
createCaption()Createsatablecaption(orreturnstheexistingone)andinsertsitintothe
element,iftheelementisatableReturnsthecaptionDoesnotworkinIEonMac
createTFoot()Createsatfoot(orreturnstheexistingone)andinsertsitintotheelement,ifthe
elementisatableReturnsthetfootDoesnotworkinIEonMac
createTHead()Createsathead(orreturnstheexistingone)andinsertsitintotheelement,if
theelementisatableReturnsthetheadDoesnotworkinIEonMac
deleteCaption()DeletesthetablecaptioniftheelementisatableDoesnotworkinIEonMac
deleteCell(cellIndex)Deletesthecellatthespecifiedindexiftheelementisatr
deleteRow(rowIndex)Deletestherowatthespecifiedindexiftheelementisatable,thead,
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

216/223

5/30/2015

JavaScripttutorial

tbodyortfoot
deleteTFoot()Deletesthetfootelementiftheelementisatable
deleteTHead()Deletesthetheadelementiftheelementisatable
insertRow(index)Insertsanewtratthespecifiedindexwithintheelementifelementisathead,
tbodyortfootUse1toappendAlsoavailablefortableelements,whereitattemptstoadd
rowsinthesamesectionastheexistingrowatthatindex(itwillcreateatbodyifnoneexists)
ReturnsthenewrowDoesnotworkinIEonMac
insertCell(index)InsertsanewtdatthespecifiedindexwithintheelementifelementisatrUse
1toappendReturnsthenewcellreadonlyDoesnotworkinIEonMac

Nodeinformation
nodeAtable(orrelated)elementnodereadonly
cellIndexTheindexofthecellwithintherow,ifelementisatdorth
rowIndexTheindexoftherowwithinthetable
sectionRowIndexIndexoftherowwithinthethead,tbodyortfoot

Stylesheets(ifsupported)
documentThedocumentobjectforthecurrentdocumentreadonly
styleSheets[]Collectionofallstylesheetsinthedocumentreadonly
addRule(stringselectors,stringstyles)Addsanewruletotheendofthestylesheet
InternetExplorermodelonlyForcrossbrowserscripting,seealso
document.styleSheets[i].insertRule
cssRules[]CollectionofallCSSrulesinthestylesheet,thatarenotinsidea@mediablock
includesnormalstylerules,@charsetrules,@importrules,@fontfacerules,@mediablocks,
@pagerulesread/onlyStandardscompliantbrowsersonlyForcrossbrowserscripting,
seealsodocument.styleSheets[i].rules
cssRules[]Givesallchildrules,iftheruleisa@mediaruleChildrenas
document.styleSheets[intnumberOfStyleSheet].cssRulesread/onlyStandards
compliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].rules
cssTextThetextualrepresentationoftherule,includingtheselectorandstyles
read/write(readonlyinMozilla,KHTML,WebKit,andIE)Standardscompliantbrowsers
only
deleteRule(intindex)DeletestheCSSruleatthespecifiedindexwithinthemediablock,if
theparentruleisa@mediaruleStandardscompliantbrowsersonly
encodingTheencodingspecifiedbytheruleiftheruleisa@charsetruleread/write
Standardscompliantbrowsersonly
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

217/223

5/30/2015

JavaScripttutorial

hrefTheURLspecifiedbytheruleiftheruleisan@importruleread/onlyStandards
compliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].imports[j].href
insertRule(stringrule,intindex)Insertsanewruleatthespecifiedindexwithinthemedia
block,iftheparentruleisa@mediaruleIftheindexisthesameasthecssRules.length,
thenewrulewillbeaddedattheendStandardscompliantbrowsersonly
mediaProvidesinformationaboutwhatmediatypestheruleappliesto,iftheruleisa
@[email protected][int
numberOfStyleSheet].mediaread/onlyStandardscompliantbrowsersonlyForcross
browserscripting,seealsodocument.styleSheets[i].imports[j].media
parentRuleReferstothe@mediarulethatthecurrentruleiscontainedinside(ifthereis
one)read/onlyStandardscompliantbrowsersonly
parentStyleSheetReferstothestyleSheetthattheruleisinsideread/only
selectorTextTheselectorpartoftherule,ifitisanormalstyleruleora@pagerule
read/write
styleReferstothestylesintheCSSrule,iftheruleisanormalstylerule,@fontfacerule
or@pageruleread/only
cssTextThetextualrepresentationofthestylepartoftheruleread/write
item(intindex)ReturnsthestyleatthespecifiedindexwithintheruleStandards
compliantbrowsersonly
lengthGivesthenumberofstylesthatthebrowserseesinsidetheruleread/only
Standardscompliantbrowsersonly
getPropertyValue(stringstylename)Returnsthevalueofthenamedstyle
StandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].rules[j].style.nameOfStyle
setProperty(stringstylename,stringstyleValue,stringpriority)Createsorreplaces
thenamedstyleinsidetherule,assigningitthespecifiedvalueThepriorityistypically
anemptystringor'important'StandardscompliantbrowsersonlyForcrossbrowser
scripting,seealsodocument.styleSheets[i].rules[j].style.nameOfStyle
getPropertyPriority(stringstylename)Returnsthepriorityofthenamedstyle
Typicallyanemptystringor'important'StandardscompliantbrowsersonlyForcross
browserscripting,seealsodocument.styleSheets[i].rules[j].style.nameOfStyle
removeProperty(stringstylename)Removesthespecifiedstylefromtherule
StandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].rules[j].style.nameOfStyle
nameOfStyleTextrepresentationofthenamedstylevalueread/write
styleSheetThestylesheetobjectofthestylesheetimportedbytherule,iftheruleisan
@importruleChildrenasdocument.styleSheets[intnumberOfStyleSheet]read/only
StandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

218/223

5/30/2015

JavaScripttutorial

document.styleSheets[i].imports[j]
typeNumberthatsayswhattypeofrulethisis:0:unknown@rule1:normalstylerule
2:@charsetrule3:@importrule4:@mediarule5:@fontfacerule6:@pagerule
read/onlyForcrossbrowserscripting,seealsodocument.styleSheets[i].insertRule
deleteRule(intindex)DeletestheCSSruleatthespecifiedindexStandardscompliant
browsersonlyForcrossbrowserscripting,seealsodocument.styleSheets[i].removeRule
disabledSaysifthestylesheetisdisabledread/write
hrefThehrefofthestylesheetreadonly
imports[]Thestylesheetobjectofthestylesheetimportedbyan@importruleChildrenas
document.styleSheets[intnumberOfStyleSheet]read/onlyInternetExplorermodelonly
Forcrossbrowserscripting,seealsodocument.styleSheets[i].cssRules[j].styleSheet
insertRule(stringrule,intindex)Insertsanewruleatthespecifiedindexwithinthestylesheet
IftheindexisthesameasthecssRules.length,thenewrulewillbeaddedattheend
StandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].addRule
mediaSayswhatmediatypesthestylesheetappliestoread/writeInternetExplorer
modelonlyForcrossbrowserscripting,seealsodocument.styleSheets[i].media.mediaText
mediaProvidesinformationaboutwhatmediatypesthestylesheetappliestoread/only
StandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].mediaasproperty
appendMedium(stringmediaType)Addsthenewmediatypetothelistofmediatypesthat
thestylesheetappliestoStandardscompliantbrowsersonlyForcrossbrowser
scripting,seealsodocument.styleSheets[i].mediaasproperty
deleteMedium(stringmediaType)Removesthenewmediatypefromthelistofmediatypes
thatthestylesheetappliestoStandardscompliantbrowsersonlyForcrossbrowser
scripting,seealsodocument.styleSheets[i].mediaasproperty
item(intindex)ReturnsthenameofthemediatypeatthespecifiedindexStandards
compliantbrowsersonly
lengthGivesthenumberofmediatypesthatthestylesheetappliesto(Asinterpretedby
thebrowser)read/onlyStandardscompliantbrowsersonly
mediaTextStringrepresentationofwhatmediatypesthestylesheetappliestoread/write
StandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].mediaasproperty
ownerNodeAreferencetotheSTYLEorLINKelementthatcreatesthestylesheetread/only
StandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].owningElement
sheetReferencestheStyleSheetobjectcreatedbytheSTYLEorLINKelement
read/onlyStandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
document.styleSheets[i].owningElement.styleSheet
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

219/223

5/30/2015

JavaScripttutorial

ownerRuleAreferencetothe@importrulethatimportedthisstylesheetread/only
Standardscompliantbrowsersonly
owningElementAreferencetotheSTYLEorLINKelementthatcreatesthestylesheet
read/onlyInternetExplorermodelonlyForcrossbrowserscripting,seealso
document.styleSheets[i].ownerNode
styleSheetReferencestheStyleSheetobjectcreatedbytheSTYLEorLINKelement
read/onlyInternetExplorermodelonlyForcrossbrowserscripting,seealso
document.styleSheets[i].ownerNode.sheet
removeRule(intindex)DeletestheCSSruleatthespecifiedindexInternetExplorermodel
onlyForcrossbrowserscripting,seealsodocument.styleSheets[i].deleteRule
rules[]CollectionofallCSSnormalstylerulesinthestylesheetread/onlyInternet
ExplorermodelonlyForcrossbrowserscripting,seealsodocument.styleSheets[i].cssRules
parentStyleSheetReferstothestyleSheetthattheruleisinsideread/only
selectorTextTheselectorpartoftheruleread/write
styleReferstothestylesintheCSSruleread/only
cssTextThetextualrepresentationofthestylepartoftheruleread/write
nameOfStyleTextrepresentationofthenamedstylevalueread/write
titleReflectstheTITLEattributeoftheSTYLEorLINKelementthatcreatesthestylesheet
read/only
typeReflectstheTYPEattributeoftheSTYLEorLINKelementthatcreatesthestylesheet
(Typically'text/css')read/only

Events
Addingandremovingeventlisteners
Note that although the methods are attached to all nodes, browsers will only be able to detect
eventsonelementnodes,thedocumentnode,andthewindowobject.
nodeAnelementnode,thedocumentnode,orthewindowobjectreadonly
addEventListener(string:event,function,bool:phase)Addsthespecifiedfunctionasahandler
forthenamedeventPhasecanbetrueforcapture,orfalseforbubbleStandardscompliant
browsersonlyForcrossbrowserscripting,seealsonode.attachEvent
attachEvent(string:onevent,function)Addsthespecifiedfunctionasahandlerforthenamed
eventIEcompatiblebrowsersonlyForcrossbrowserscripting,seealso
node.addEventListener
detachEvent(string:onevent,function)Removesthespecifiedfunctionasahandlerforthe
namedeventIEcompatiblebrowsersonlyForcrossbrowserscripting,seealso
node.removeEventListener
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

220/223

5/30/2015

JavaScripttutorial

removeEventListener(string:event,function,bool:phase)Removesthespecifiedfunctionasa
handlerforthenamedeventPhasecanbetrueforcapture,orfalseforbubbleStandards
compliantbrowsersonlyForcrossbrowserscripting,seealsonode.detachEvent

Creatingeventobjects
documentThedocumentobjectforthecurrentdocumentreadonly
createEvent(string:EventModule)Createsanuninitialisedeventfromthespecifiedevent
moduleEventmodulesare:Events:nonstandardeventsthatdonotfitintoothercategories
HTMLEvents:'abort','blur','change','error','focus','load','reset','resize','scroll','select',
'submit','unload'KeyEvents:'keydown','keypress',and'keyup'(Mozillaonly,forcrossbrowser
scriptingseeUIEvents)MouseEvents:'click','mousedown','mousemove','mouseout',
'mouseover',and'mouseup'MutationEvents:'DOMAttrModified','DOMNodeInserted',
'DOMNodeRemoved','DOMCharacterDataModified','DOMNodeInsertedIntoDocument',
'DOMNodeRemovedFromDocument',and'DOMSubtreeModified'UIEvents:'DOMActivate',
'DOMFocusIn','DOMFocusOut',alsoinnonMozilla'keydown','keypress',and'keyup'(forcross
browserscriptingseeKeyEvents)StandardscompliantbrowsersonlyForcrossbrowser
scripting,seealsodocument.createEventObject
createEventObject(optionaltemplateObject)CreatesanuninitialisedeventIfanexisting
eventobjectispassedasaparameter,itwillbeusedasatemplatetocreatethenewobject
IEcompatiblebrowsersonlyForcrossbrowserscripting,seealsodocument.createEvent

Preparingeventobjects
eventObjectTheeventobjectcreatedbydocument.createEventreadonlyStandards
compliantbrowsersonly
initEvent('type',bubbles,cancelable)Initialisestheeventasagenericevent,withoutdefining
additionalpropertiesAvailableforalleventtypesStandardscompliantbrowsersonly
initKeyEvent('type',bubbles,cancelable,window,ctrlKey,altKey,shiftKey,metaKey,
keyCode,charCode)InitialisestheeventasakeyeventAvailablefor'KeyEvents'eventtypes
Mozillaonly
initMouseEvent('type',bubbles,cancelable,window,detail,screenX,screenY,clientX,
clientY,ctrlKey,altKey,shiftKey,metaKey,button,relatedTarget)Initialisestheeventasa
mouseeventAvailablefor'MouseEvents'eventtypesStandardscompliantbrowsersonly
initMutationEvent('type',bubbles,cancelable,relatedNode,prevValue,newValue,attrName,
attrChange)InitialisestheeventasamutationeventAvailablefor'MutationEvents'eventtypes
Standardscompliantbrowsersonly
initUIEvent('type',bubbles,cancelable,window,detail)InitialisestheeventasagenericUI
event,withoutdefiningadditionalpropertiesAvailablefor'MouseEvents','UIEvents',and
Mozilla's'KeyEvents'eventtypesStandardscompliantbrowsersonly
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

221/223

5/30/2015

JavaScripttutorial

Firingevents
nodeAnelementnode,thedocumentnode,orthewindowobjectreadonly
dispatchEvent(eventObject)Firestheevent,withtheelementnodeasthetargetStandards
compliantbrowsersonlyForcrossbrowserscripting,seealsonode.fireEvent
fireEvent('ontype',eventObject)Firesthespecifiedevent,withtheelementnodeasthe
srcElementIEcompatiblebrowsersonlyForcrossbrowserscripting,seealso
node.dispatchEvent

Additionaleventobjectmethodsandproperties
As well as the traditional event object properties, some more are provided by DOM events (or IE
events)capablebrowsers.
eventObjectTheeventobjectreadonly
attrChangeSaysthetypeofchangeforDOMAttrModifiedmutationevents1:modification2:
addition3:removalreadonlyStandardscompliantbrowsersonly
attrNameThenameoftheattributeforDOMAttrModifiedmutationeventsreadonly
Standardscompliantbrowsersonly
bubblesBooleanvaluesaysiftheeventisatypethatcanbubblereadonlyStandards
compliantbrowsersonly
cancelableBooleanvaluesaysiftheeventcanbecancelledreadonlyStandards
compliantbrowsersonly
cancelBubbleSettotruetopreventtheeventfrombeingprocessedbyanymoreeventhanler
stagesreadwriteIEcompatiblebrowsersonlyForcrossbrowserscripting,seealso
eventObject.stopPropagation
charCodeThevalueoftheUnicodecharacterassociatedwithkeyeventsreadonlyMozilla
compatiblebrowsersonly
currentTargetAreferencetotheelementthatiscurrentlyprocessingtheeventreadonly
Standardscompliantbrowsersonly
detailExtrainformationdependingontheeventforexampleaclickeventmaygivethenumber
ofconsecutiveclicksreadonlyStandardscompliantbrowsersonly
eventPhaseSayswhatphaseoftheeventiscurrentlybeingprocessed1:capturephase2:
bubblephaseonthetargetelementitself3:duringthebubblingphaseonthetarget'sancestors
0:foramanuallycreatedeventobjectthathasnotyetbeenfiredreadonlyStandards
compliantbrowsersonly
fromElementGivesthepreviouselementthemousewasoverformouseovereventsreadonly
IEcompatiblebrowsersonlyForcrossbrowserscripting,seealso
eventObject.relatedTarget
metaKeyBooleanvaluesaysifthesystemmetakeyispressedForWindowsthisisthewindow
http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

222/223

5/30/2015

JavaScripttutorial

keyForMacthisistheapple/commandkeyOthersystemsmayhavetheirownmetakeys
readonlyStandardscompliantbrowsersonly
newValueThenewnodeValueafteramutationeventreadonlyStandardscompliant
browsersonly
preventDefault()Preventsthedefaultactionfromoccuringaftereventprocessingiscomplete
StandardscompliantbrowsersonlyForcrossbrowserscripting,seealso
eventObject.returnValue
prevValueThepreviousnodeValuebeforeamutationeventreadonlyStandardscompliant
browsersonly
relatedNodePerformsasimilarfunctiontorelatedTarget,formutationeventsreadonly
Standardscompliantbrowsersonly
relatedTargetAreferencetotherelatedelementforrelevanteventssuchastheelementthe
mouseusedtobeoverbeforeamouseovereventreadonlyStandardscompliantbrowsers
onlyForcrossbrowserscripting,seealsoeventObject.fromElementeventObject.toElement
returnValueSettofalsetopreventthedefaultactionfromoccuringaftereventprocessingis
completereadwriteIEcompatiblebrowsersonlyForcrossbrowserscripting,seealso
eventObject.preventDefault
stopPropagation()Preventstheeventbeingprocessedbyanymorehandlersatfurtherstages
intheeventflowreadonlyStandardscompliantbrowsersonlyForcrossbrowser
scripting,seealsoeventObject.cancelBubble
toElementGivestheelementthemouseisabouttomoveoverformouseouteventsreadonly
IEcompatiblebrowsersonlyForcrossbrowserscripting,seealso
eventObject.relatedTarget
Lastmodified:11May2011

http://www.howtocreate.co.uk/ThissitewascreatedbyMark"Tarquin"WiltonJones.

http://www.howtocreate.co.uk/tutorials/javascript/combinedpage#functions

223/223

You might also like