38954115 javascript tutorial
Post on 04-Jun-2018
236 Views
Preview:
TRANSCRIPT
-
8/13/2019 38954115 Javascript Tutorial
1/265
JavaScript tutorial - Important guidelines
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 languageitself !eeps evolving and there is already a vast amount of the JavaScript language available for
browsers to support. "o browser will ever support all of it and you cannot e#pect them to.
There are many reasons why people cannot or will not 'upgrade' to your chosen browser. A few are$
They are at wor! and they can only use the system default browser.
They want to view pages more %uic!ly so they use a te#t only browser.
They are blind or have poor eyesight so they need a te#t only browser&reader&raille reader.
They realise that the more e#tra features li!e JavaScript or (Script you use the more you
leave yourself open to becoming a target for viruses or vulnerability e#ploits.
They don't li!e the way some sites insist on ta!ing over their control of the browser opening
popup windows brea!ing the operation of the bac! button preventing the conte#t menu from
wor!ing or insisting on ma!ing things appear and disappear in a way that causes usability
problems.
)hatever their reasons you should notstop them from using your site. If your site uses JavaScript
for navigation or content then that navigation and content should be there without JavaScript
enabled. *our JavaScript can e#tract content from the page and do whatever it wants with that but
you should ma!e sure that content is available without the script. If you want to use a script in way
that you cannot simply e#tract the information from the static page then you should
use to provide an alternative for people that cannot run your script.
There are also many browsers out there that you do not realise e#ist. I !now of well over a hundred
different browsers that support JavaScript to varying degrees. If your script uses something that
browsers may not support you should detect if the browser is capable of using it and then fall bac!
to an accessible alternative if it doesn't.
There is no magic formula for this but the basic rules are that you should not detect a browser ma!e
or version. *ou willget it wrong and you will mista!enly detect one browser and thin! it is another
ending up with you using the wrong code. *ou willma!e incorrect assumptions about current and
future browsers and you will cause problems for your users.
This tutorial should help you learn how to correctly detect capabilities and wherever needed it will
show you how to wor! out when a browser cannot do what you need so you can halt your script or
provide an alternative. )hen there are different ways to do the same thing and some browsers only
-
8/13/2019 38954115 Javascript Tutorial
2/265
support one while others support another it will show you how to correctly wor! out which one to
use.
Introduction to JavaScript
JavaScript is a programming language that can be included on web pages to ma!e them moreinteractive. *ou can use it to chec! or modify the contents of forms change images open new
windows and write dynamic page content. *ou can even use it with +SS to ma!e ,T/ 0,ynamic
yperTe#t ar!up /anguage1. This allows you to ma!e parts of your web pages appear or
disappear or move around on the page. JavaScripts only e#ecute on the page0s1 that are on your
browser window at any set time. )hen the user stops viewing that page any scripts that were
running on it are immediately stopped. The only e#ception is a coo!ie which can be used by many
pages to pass information between them even after the pages have been closed.
efore we go any further let me say2 JavaScript has nothing to do with Java. If we are honest
JavaScript originally nic!named /ive)ire and then /iveScript when it was created by "etscape
should in fact be called 3+Ascript as it was renamed when "etscape passed it to the 3+A for
standardisation.
JavaScript is a client side interpreted ob4ect oriented high level scripting language while Java is a
client side compiled ob4ect oriented high level language. "ow after that mouthful here's what it
means.
+lient side
5rograms are passed to the computer that the browser is on and that computer runs them.
The alternative is server side where the program is run on the server and only the results
are passed to the computer that the browser is on. 3#amples of this would be 55 5erl
AS5 JS5 etc.
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. +ompiled 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 0to 'byte code'1
before it is passed then e#ecuted in a virtual machine which converts it to fully compiled
code 4ust before use in order to e#ecute it on the computer's processor. Interpreted
languages are generally less fussy about synta# and if you have made mista!es in a part
they never use the mista!e usually will not cause you any problems.
-
8/13/2019 38954115 Javascript Tutorial
3/265
Scripting
This is a little harder to define. Scripting languages are often used for performing repetitive
tas!s. Although they may be complete programming languages they do not usually go into
the depths of comple# programs such as thread and memory management. They may use
another program to do the wor! 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
them. This is %uite accurate for JavaScript. )e do not have to tell the browser e#actly what
to put on the screen for every pi#el we 4ust tell it that we want it to change the document
and it does it. The browser will also ta!e care of the memory management and thread
management leaving JavaScript free to get on with the things it wants to do.
igh level
)ritten in words that are as close to english as possible. The contrast would be withassembly code where each command can be directly translated into machine code.
6b4ect oriented
See the section on 'ob4ect oriented programming'for details.
How is JavaScript constructed
The basic part of a script is a variable literal or ob4ect. A variable is a word that represents a piece of
te#t a number a boolean true or false value or an ob4ect. A literal is the actual number or piece of
te#t or boolean value that the variable represents. An ob4ect is a collection of variables held together
by a parent variable or a document component.
The ne#t most important part of a script is an operator. 6perators assign literal values to variables or
say what type of tests to perform.
The ne#t most important part of a script is a control structure. +ontrol structures say what scripts
should be run if a test is satisfied.
Functions collect control structures actions and assignments together and can be told to run thosepieces of script as and when necessary.
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. ethods are a special !ind of function and may do
things li!e submitting forms writing pages or displaying messages.
http://www.howtocreate.co.uk/tutorials/javascript/objectorientedhttp://www.howtocreate.co.uk/tutorials/javascript/objectorientedhttp://www.howtocreate.co.uk/tutorials/javascript/objectoriented -
8/13/2019 38954115 Javascript Tutorial
4/265
3vents can be used to detect actions usually created by the user such as moving or clic!ing the
mouse pressing a !ey or resetting a form. )hen triggered events can be used to run functions.
/astly and not %uite so obvious is referencing. This is about wor!ing out what to write to access the
contents of ob4ects or even the ob4ects themselves.
As an e#ample thin! of the following situation. A person clic!s a submit button on a form. )hen they
clic! the button we want to chec! if they have filled out their name in a te#t bo# and if they have we
want to submit the form. So we tell the form to detect the submit event. )hen the event is triggered
we tell it to run the function that holds together the tests and actions. The function contains a control
structure that uses a comparison operator to test the te#t bo# to see that it is not empty. 6f course
we have to wor! out how to reference the te#t bo# first. The te#t bo# is an ob4ect. 6ne of the
variables it holds is the te#t that is written in the te#t bo#. The te#t written in it is a literal. If the te#t
bo# is not empty a method is used that submits the form.
Examples
All e#amples on this page and elsewhere in my JavaScript tutorial are provided free of charge.
5lease see theterms and conditions pagefor terms of use.
These e#amples are all useful in their own right but when used together can produce spectacular
results. I will leave that to your own creativity.
"ote that the synta# highlighted source of all the header files I use in these e#amples as well as
several others is available on my JavaScript librariespage. The header files can also be
downloaded from there.
The header file scripts are meant to be real scripts for real use not tutorials. I have included them on
this page as they can be viewed as e#amples 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 optimised for real
use. *ou may choose to see this as a bad programming method but I do not as I can always see
what I was intending for the script to do and it helps to cut down on the transmitted file si7e
something which modem users are always happy for.
To give you an e#ample of a more 'friendly' format which is easier to use as a learning aid one of
my readers has !indly produced a reformatted version of my generic re-writable elementsscript
which is included in the email they sent me.
http://www.howtocreate.co.uk/jslibs/termsOfUse.htmlhttp://www.howtocreate.co.uk/jslibs/http://www.howtocreate.co.uk/jslibs/http://www.howtocreate.co.uk/tutorials/jsexamples/rewritediv.htmlhttp://www.howtocreate.co.uk/emails/RobertLawrence.html#rdExhttp://www.howtocreate.co.uk/jslibs/termsOfUse.htmlhttp://www.howtocreate.co.uk/jslibs/http://www.howtocreate.co.uk/tutorials/jsexamples/rewritediv.htmlhttp://www.howtocreate.co.uk/emails/RobertLawrence.html#rdEx -
8/13/2019 38954115 Javascript Tutorial
5/265
Non DHTML
The most popular use of JavaScript; changing images when the mouse hangs over a link
5reloading images for use in mouseovers and pre-caching.
The next most popular use of JavaScript; opening new browser winows
6pening a window with customisable settings.
The next most popular use of JavaScript; writing !namic content
+hanging what is written depending on conditions.
The next most popular use of JavaScript; checking forms
Form chec!ing ensuring a form is filled in correctly.
Slightl! less use but "ust as useful# retaining variables from one page for use on another
page
+omplicated string manipulation ta!ing variables from the location bar.
+reating reading and modifying coo!ies.
Some specialist scripts
Form manipulation offering the correct countries for a continent.
ore form manipulation e#pandable tree structure.
The most irresponsible script
rowser sniffing - to be used only to help avoid browser specific bugs not to determine
capability.
http://www.howtocreate.co.uk/tutorials/jsexamples/imageHandle.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/popwin.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/popwin.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/dywrite.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/dywrite.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/formcheck.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/formcheck.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/vartransfer.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/cookies.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/cookies.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/formman.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/formman.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/formman.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/treeselect.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/treeselect.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/sniffer.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/imageHandle.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/popwin.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/dywrite.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/formcheck.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/vartransfer.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/cookies.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/formman.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/treeselect.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/sniffer.html -
8/13/2019 38954115 Javascript Tutorial
6/265
DHTML
$ppearing % isappearing content
5opup enus.
5opup enus with delay - see8ec!o engine bug.
Auto-generation 5opup enus with delay -8ec!o engine bugsremoved.
Tooltips.
Movable content
Tooltips.
Static logo.
Falling ob4ects 0snow1.
Flying stars 0changes apparent si7e of div elements1.
Firewor!s 0demonstrates changing colour1.
Analogue cloc!.
Mouse trails
o Single trail with bouncing animation.
o ultiple trail with several possibilities.
&ewritable ocument content
8eneric re-writable elements.
0Simple1 message scroller.
'() D*M
Importing 9/ data files - a very advanced scripting topic.
Solitaire game - a very advanced script.
These scripts any many more are included on my JavaScript libraries page. The page also contains
several utility scripts which you may find useful for your )eb development. 5lease see the terms
and conditions pagefor terms of use.
http://www.howtocreate.co.uk/tutorials/jsexamples/showhide.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/showhidedelay.htmlhttp://www.howtocreate.co.uk/mozmousebug.htmlhttp://www.howtocreate.co.uk/mozmousebug.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/showhidedelayarray.htmlhttp://www.howtocreate.co.uk/mozmousebug.htmlhttp://www.howtocreate.co.uk/mozmousebug.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/movetooltip.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/movetooltip.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/statlogo.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/snowscript.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/starfield.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/fireworks.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/anclock.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/anclock.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/boing.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/multitrail.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/rewritediv.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/rewritediv.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/msgscroll.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/msgscroll.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/importingXML.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/solitaire.htmlhttp://www.howtocreate.co.uk/jslibs/http://www.howtocreate.co.uk/jslibs/termsOfUse.htmlhttp://www.howtocreate.co.uk/jslibs/termsOfUse.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/showhide.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/showhidedelay.htmlhttp://www.howtocreate.co.uk/mozmousebug.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/showhidedelayarray.htmlhttp://www.howtocreate.co.uk/mozmousebug.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/movetooltip.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/movetooltip.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/statlogo.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/snowscript.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/starfield.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/fireworks.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/anclock.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/boing.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/multitrail.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/rewritediv.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/msgscroll.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/importingXML.htmlhttp://www.howtocreate.co.uk/tutorials/jsexamples/solitaire.htmlhttp://www.howtocreate.co.uk/jslibs/http://www.howtocreate.co.uk/jslibs/termsOfUse.htmlhttp://www.howtocreate.co.uk/jslibs/termsOfUse.html -
8/13/2019 38954115 Javascript Tutorial
7/265
+ames
6! so they are far too complicated to be e#amples but all of the principles are the same as I have
described in these tutorials. These games re%uire various different technologies li!e T/ +SS
,T/ etc. "ot all browsers will be able to use all of the games in particular the :, games
because they are (3;* demanding on resources. The simpler games may even wor! in browsers
li!e "etscape :.
These games are all on my games site.
Adding JavaScript to a page
*ou can add a script anywhere inside the head or body sections of your document. owever to
!eep your document well structured there are some basic guidelines$
ost scripts can go inside the document head. This !eeps them out of the way of the main
document content.
If your script needs to run at a certain stage during page layout 0for e#ample if it uses
document.write to create content1 it should be put at the correct stage of the document almost
always somewhere inside the document body. If the script is very small then put it all where it
will be used. If it is larger then put it inside the head inside a function and you can then call that
function when you need it.
If your script is used on more than one page or if it is of any significant si7e then put it in its
own file and load it in the document head. "ot only will this help to !eep the clutter of the
document but it will also help avoid potential synta# problems 0I will cover these later1. As an
e#tra benefit these can be used by multiple pages allowing browsers to use their cache and
saving bandwidth for you and your visitors.
$ing a script to the page
To insert JavaScript into a web page use the tag. *ou should use the type attribute to
specify the type of script being used which in the case of JavaScript is text/javascript. It is also
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
vastly different capabilities. All JavaScript supporting browsers currently in use will support a level of
JavaScript e%uivalent to JavaScript 4avascript1 or higher so this is what I
will teach you in this tutorial.
http://www.freegames.uk.eu.org/http://www.freegames.uk.eu.org/http://www.freegames.uk.eu.org/ -
8/13/2019 38954115 Javascript Tutorial
8/265
rowsers will generally choose an arbitrary version number that they will claim to support and will
run any script that has either no language version number or a version e%ual to or lower than the
one they claim to support. Since the language is so unreliable you should generally omit this
attribute although it is common to see scripts using it. *our script can then detect if the browser is
capable of running your script and it can do this a lot more accurately than the version number can.
This is an e#ample of a script tag used to include a script in your page$
//JavaScript goes here
If your script is incapable of providing its own fallbac! but it is needed to access the page youshould include support for non-JavaScript browsers by using$
This will not be displayed if JavaScript is enabled
,sing comments
+omments allow you to leave notes to yourself and other people in your script and are useful as a
reminder of what the script is doing and why. The double slash indicates a single line comment.
3verything after it on the same line will be ignored by the script engine. The slash-asteris! indicates
a bloc! comment. 3verything after it will be ignored by the script engine until an asteris!-slash is
encountered.
//This is a single line comment
/ This is a
-
8/13/2019 38954115 Javascript Tutorial
9/265
bloc! comment /
,sing external script files
*ou can also use a separate header file to contain the JavaScript 0usually ?.4s1 ma!ing it easy to
share across pages$
)hen using header files if you put any script code in between
the and tags it will only be e#ecuted if the browser does not support
header files 0assuming it doessupport the version of JavaScript shown in the language attribute if
you used one1. In reality this is only for very old browsers that are not used at all any more so there
is no need for anything to be put there.
Scripts in header files are e#ecuted as if they were in the main page. If the script referances any
e#ternal files such as images the addresses it uses are relative to the main page not the script
@;I.
)ommenting out !our scripts
This is not needed any more. All current browsers are aware of script tags and how to treat their
contents since they have been part of T/ since T/ :. rowsers that do not understand T/
: or scripts 0these are virtually never used now1 will display the script as if it was the content of the
page. *ou can hide the script from them by commenting out your script with standard T/
comments. rowsers that understand script will simply ignore these comments and will 4ust interpret
the script within them. The opening comment is ignored as if it were a normal single line JavaScript
comment. The closing comment will not so it needs to have a JavaScript comment put before it$
-
8/13/2019 38954115 Javascript Tutorial
10/265
//JavaScript goes here
//$$>
These T/ comments should not be used if you are using an e#ternal script file and are not to be
used anywhere else in your scripts.
Dealing with -HTML
"ote that when I tal! about 9T/ I am tal!ing about pages that are served using a content type
ofapplication/xhtml%xml- the ma4ority of pages that use 9T/ mar!up are actually served
as text/htmland as a result are correctly treated as T/ not 9T/.
The rules in 9T/ are different. Script tags are not treated as being special. Their contents are
treated as any other part of 9T/ so various operators can be misinterpreted as part of the
mar!up. To avoid this it is best to put all scripts in e#ternal script files so that they do not interfere
with the page itself. If you feel the need to put something directly on the page you can declare it as
+,ATA 0the default for script contents in normal T/1$
-
8/13/2019 38954115 Javascript Tutorial
11/265
also do not understand 9T/ but in case you want to use it 0maybe you are serving it as 9T/
to some browsers and T/ to others1 this is what to use$
-
8/13/2019 38954115 Javascript Tutorial
12/265
onsubmit onreset
a
onclic! onmouseover onmouseout onfocus onblur
body
onload onunload
+hec! with the T/ specifications on the ):+ sitefor 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. For some of these older browsers such as "etscape it is possible to compensate using a
combination of onmouseover onmouseout and then document.capture3vents and onmousemove
on the body 0see the section on 3vent information1. The3vent informationand more advanced,6
eventschapters of this tutorial show how to listen for more event types and obtain information from
them.
These are some e#amples of using events 0shown here using traditional inline event handlers - later
on in this tutorial I will show you alternative ways to attach events to elements that will not re%uire
you to alter your T/1$
Another way of ma!ing T/ activate JavaScript is to usebut in general it is best to use events so the lin!
can provide an accessible alternative if JavaScript is not available 0the event handler can prevent the
browser from using the lin! normally if scripting is available1.
In all these cases the script is contained within T/ attributes and is sub4ect to the normal rules ofT/ entities. If you need to put %uotes in the script in between the %uotes in the html use the
T/ entity B%uot2 or BC:2 for > style %uotes or if your %uotes in the T/ are done using the '
%uotes 0which is unusual ...1 you can use BC:D2 to represent these in the script. If you need to
include E or operators you should use the Blt2 and Bgt2 entities.
http://www.w3.org/TR/html4/http://www.howtocreate.co.uk/tutorials/javascript/eventinfohttp://www.howtocreate.co.uk/tutorials/javascript/eventinfohttp://www.howtocreate.co.uk/tutorials/javascript/eventinfohttp://www.howtocreate.co.uk/tutorials/javascript/domeventshttp://www.howtocreate.co.uk/tutorials/javascript/domeventshttp://www.howtocreate.co.uk/tutorials/javascript/domeventshttp://www.w3.org/TR/html4/http://www.howtocreate.co.uk/tutorials/javascript/eventinfohttp://www.howtocreate.co.uk/tutorials/javascript/eventinfohttp://www.howtocreate.co.uk/tutorials/javascript/domeventshttp://www.howtocreate.co.uk/tutorials/javascript/domevents -
8/13/2019 38954115 Javascript Tutorial
13/265
Object oriented programming
*b"ects
An ob4ect is a 'thing'. For e#ample a number is an ob4ect. An array is an ob4ect. *our browser
window is an ob4ect. A form in your document is an ob4ect. There are hundreds more and in some
cases you can create your own.
6b4ects can have ob4ects in them. For e#ample your document can have a form in it. This form is a
'child ob4ect' of the document. Therefore the document is the 'parent ob4ect' of the form. To reference
the child ob4ect we have to go through the parent ob4ect eg. doc1mentmy7orm
An array can have numbers in its cells. As we have already discussed the array is an ob4ect and so
would be a cell within it and so is the content of the cell. )e cannot refer to the cell itself but we can
refer to its contents$ my)rray&,cell name or n1mber,*for e#ample.
)lasses .or t!pes/
A class is a group of ob4ects that are similar in some way. For e#ample a number and a piece of te#t
can both be stored as a variable 0in a way li!e the variables you would use in mathematical
algebra1. In essence we can say that pieces of te#t and numbers are e#amples of class 'variable'.
"umbers can be sub divided into two groups integers and floats 0or doubles1. Integers are wholenumbers$
-
8/13/2019 38954115 Javascript Tutorial
14/265
There are many arrays that are inbuilt into each document. The document itself is an array in certain
uses. The most obvious of these collections is the images collection. To refer to images in the
document we use
doc1mentimages&,name of image,*
This is a special !ind of array !nown as a collection.
0roperties
Ta!e for e#ample an image. )hen we define images in T/ we write$
The properties of the image would be src name height width alt and if we also used Style Sheets
we might have included several more 0li!e bac!ground-color for e#ample1. All properties are a type
of ob4ect so to refer to the src of my image I would write doc1mentimages&,my5mage,*src
Methos
There are always actions that are associated with ob4ects. For e#ample a form may be submitted or
reset. The actions are methods. To submit a form in non-ob4ect-oriented programs we might
writes1bmit,name of form,0
That would simply be a function. In ob4ect oriented programming li!e JavaScript we would
usedoc1mentname8f7orms1bmit0
The reason this is a method and not 4ust a function is that each form will have its
own s1bmit0function built in which is referred to using the ob4ect oriented synta# shown above.
*ou will never have to write methods in yourself unless you create your own ob4ects the browser
does that for you.
*ou can thin! of it li!e this$
)ith the non-ob4ect-oriented way we would tell a function to submit the form.
)ith the ob4ect oriented way we would tell the form to submit itself.
If wanted you can run several methods in turn on the same ob4ect by using$
-
8/13/2019 38954115 Javascript Tutorial
15/265
referenceToThe8bjectmethod90method40method;0method9again0
In this case method< must return a class of ob4ect that has the method 'method=' etc.
Operators
The most common operators are mathematical operators2 - & ? 0add subtract divide multiply1 for
e#ample. 6perators can be split into two groups comparison operators and assignment or 'action'
operators. +omparison operators test to see if two variables relate to each other in the specified
way for e#ample one variable is a higher number than the other. 6ther operators perform an action
on a variable such as increasing it by one.
The following table gives those that are most commonly used. There are many JavaScript number on the left must be greater than the number on the right - this also
-
8/13/2019 38954115 Javascript Tutorial
16/265
JavaScript operators
Opera
torUses
works with strings and values
=number on the left must be greater than or equal to the number on the right -
this also works with strings and values
bitwise rightshift
& bitwise !"
| bitwise #$
^ bitwise %#$
~ bitwise !#&
! logical !#& 'the statement must not be true(
&& logical !" 'both statements must be true(
|| logical #$ 'either statement must be true(
-
8/13/2019 38954115 Javascript Tutorial
17/265
JavaScript operators
Opera
torUses
in object or array on the right must have the property or cell on the left
"ote if you do not set the lang1age="javascript94"attribute in the Escript tag : == false ==
,,and1ndefined == n1ll. If you do set the language attribute to ,javascript94,
o7illa&Firefo# and other 8ec!o browsers 0but none of the other ma4or browsers1 will change this so
that none of these will e%uate to each other. Since the attribute is deprecated anyway and the
JavaScript versions were never standardised you should not rely on this behaviour.
There are also a few operators that can also be used li!e functions$
void
void statementor voidstatement00see the section on writing functions1
typeof
typeof variableor typeofvariable0returns the type 0or class1 of a variable.
eval
evalstring0interprets a string as JavaScript code.
There are also the 'var' 'new' and 'delete' operators. See the section on variablesfor e#amples of
their uses. Also see the section on the ath ob4ect operators below.
"ote that JavaScript has no logical 96; operator. If you need that functionality see my
separate 96; article.
*perator preceence
If you as! JavaScript to perform a calculation using multiple operators those operators will be
evaluated in a specific order. For e#ample ; % is calculated as 0 % ;because the ?
is calculated before the . The order in which these are evaluated is$ / % $ %0where the
second is appending strings1. To change the order in which they are calculated use parenthesis 0 1
http://www.howtocreate.co.uk/tutorials/javascript/functionshttp://www.howtocreate.co.uk/tutorials/javascript/variableshttp://www.howtocreate.co.uk/tutorials/javascript/variableshttp://www.howtocreate.co.uk/xor.htmlhttp://www.howtocreate.co.uk/tutorials/javascript/functionshttp://www.howtocreate.co.uk/tutorials/javascript/variableshttp://www.howtocreate.co.uk/xor.html -
8/13/2019 38954115 Javascript Tutorial
18/265
as the contents of parenthesis are calculated before the contents outside the parenthesis. For
e#ample ; % = ?@but ; % 0 = ;
The Math ob"ect methos
In reality these are methods of the ath ob4ect but they are used in place of operators.
)ath object methods
Operator What it does
Math.abs(n) $eturns the absolute value of n
Math.acos(n) $eturns 'in radians( cos-*of n
Math.asin(n) $eturns 'in radians( sin-*of n
Math.atan(n) $eturns 'in radians( tan-*of n
Math.atan2(n,k)$eturns the angle 'rads( from cartesian
coordinates , to n,k
Math.ceil(n)$eturns n rounded up to the nearest whole
number
Math.cos(n) $eturns cos n 'where n is in radians(
Math.e(n) $eturns en
Math."loo#(n)$eturns n rounded down to the nearest whole
number
Math.lo$(n)
$eturns ln'n(
!ote, to find log*'n(, use )athlog'n(
)athlog'*(
Math.a(a,b,c,...)$eturns the largest number
Math.in(a,b,c,...)$eturns the smallest number
-
8/13/2019 38954115 Javascript Tutorial
19/265
)ath object methods
Operator What it does
Math.o(n,k) $eturns nk
Math.#an'o() $eturns a random number between and *
Math.#on'(n)$eturns n rounded up or down to the nearest
whole number
Math.sin(n) $eturns sin n 'where n is in radians(
Math.s#t(n) $eturns the square root of n
Math.tan(n) $eturns tan n 'where n is in radians(
Variables
(ariable types are not important in JavaScript. They may be interchanged as necessary. This means
that if a variable is a string one minute it can be an integer the ne#t. The basic variable types are$
character
'a' or 'K' or '!' etc.
string
'hdttgs L -Mhs 01 8et the idea'
integer
G or < or = or : or etc. or -< or -= or -: or - etc.
float 0or double1
=:.HM or -
-
8/13/2019 38954115 Javascript Tutorial
20/265
A function2 see the section on Functions
ob4ect
An ob4ect2 see the section on 6b4ect oriented programming
array
A type of ob4ect that can store variables in cells 0see below1
undefined
A variable that has not been given a value yet
null
A variable that has been defined but has been assigned the value of null
Integer and float are grouped together as 'number'. +haracter and string are grouped together as
'string'.
@se the typeof operator to find out which variable type your variable is. "ote typeof will return
'ob4ect' for arrays and null.
Defining variables
See the section on ';eferencing'subsection 'Avoiding referencing conflicts'to see how to choose
names for your variables.
Normal variables
It is good practice to pre-define all variables using the var!eyword. It is possible to define the
variable leaving its value undefined or assigning a value immediately or even to define multiple
variables in a single command$
var variablename.
var variablename = val1e.
var vari9 = val1e2 vari4 = another+al1e2 vari;.
http://www.howtocreate.co.uk/tutorials/javascript/functionshttp://www.howtocreate.co.uk/tutorials/javascript/objectorientedhttp://www.howtocreate.co.uk/tutorials/javascript/referencinghttp://www.howtocreate.co.uk/tutorials/javascript/referencinghttp://www.howtocreate.co.uk/tutorials/javascript/referencinghttp://www.howtocreate.co.uk/tutorials/javascript/referencing#refconhttp://www.howtocreate.co.uk/tutorials/javascript/referencing#refconhttp://www.howtocreate.co.uk/tutorials/javascript/referencing#refconhttp://www.howtocreate.co.uk/tutorials/javascript/functionshttp://www.howtocreate.co.uk/tutorials/javascript/objectorientedhttp://www.howtocreate.co.uk/tutorials/javascript/referencinghttp://www.howtocreate.co.uk/tutorials/javascript/referencing#refcon -
8/13/2019 38954115 Javascript Tutorial
21/265
JavaScript is fairly lenient and will create a global variable if you forget to use the 'var' !eyword but
you assign a value to an undeclared variable 0if you attempt to read the value of an undeclared
variable it will throw an error as discussed below1. owever this can lead to problems if you end up
accidentally overwriting variables from another scope 0this will be covered in the chapter
onFunctions1. 6nce a variable is defined do not use ,var variablename,again unless you wish tocompletely overwrite the variable. It ma!es no sense to redeclare a variable with the var!eyword
within the same scope but browsers will not complain if you do it.
These are some e#amples of how to define variables in this case a string a number and a regular
e#pression$
var my7ish = ,) fish swam in the river,.
var myA1mber8fBoats = 4;.
var myCattern = /*E&D/gi.
"ote that variables can be defined at any point in your script including inside a control structure that
causes that statement never to be e#ecuted. owever no matter where you choose to define your
variable the JavaScript engine will create the variable at the start of the current scope. It will hold
the value 1ndefineduntil a statement is e#ecuted that gives it a value.
*b"ects
)ebT( =.M- does not support the NO synta# for creating ob4ects.
If you want to create variables that you want to be able to give child properties to you must define
the variable as an ob4ect. To define a variable as an ob4ect use either the new
8bject0or FGsynta#$
var variableAame = new 8bject0.
var variableAame = Fmy7irstCroperty692myAextCroperty6,hi,2etcG.
*ou can then assign child ob4ects or properties to that ob4ect as you want$
variableAameaCropertyAame5HadeIp = ,hello,.
variableAamea'hild8bjectAame5HadeIp = new 8bject0.
http://www.howtocreate.co.uk/tutorials/javascript/functionshttp://www.howtocreate.co.uk/tutorials/javascript/functionshttp://www.howtocreate.co.uk/tutorials/javascript/functions -
8/13/2019 38954115 Javascript Tutorial
22/265
"ote that if you want to run a method on an ob4ect that you 4ust created for true JavaScript
-
8/13/2019 38954115 Javascript Tutorial
23/265
In JavaScript arrays and ob4ects are almost e%uivalent and accessing a named cell of an array is
the same as accessing a property of an ob4ect. If a cell of an array is called 'mycell' you could use
either of these to access its contents$
name8f)rray&,mycell,*
name8f)rraymycell
There are some important differences between arrays and ob4ects. y default arrays have far more
methods attached to them for stepping through the array or splitting it into pieces. In addition if
numbers are used for entries you can find out how many entries 0or variables1 the array is holding
using name8f)rraylength
It is possible to create multi-dimensional arrays by creating aditional arrays as the contents of the
cell of another array$
var name8f)rray = new )rraynew )rray9242;2?02,hello,2&,a,2,b,2,c,*0.
*ou can refer to the cells of that array using the s%uare brac!et notation twice 0or multiple times
depending on how many dimensions your array has1$
name8f)rray&name3or3n1mber3of3entry*&name3or3n1mber3of3inner3entry*
*ther t!pes of ob"ects
rowsers will have many built in types of ob4ects. All JavaScript capable browsers will provide the
following aditional ob4ect types$
,ate
+reates a date ob4ect which can perform calculations based on the date for e#ample$
var mydate = new (ate0.
windowalert ,The year is, % mydateget71llKear0 0.
Image
-
8/13/2019 38954115 Javascript Tutorial
24/265
+reates an image that is not visible but is stored in cache. Setting the src attribute of the
image causes the image to be loaded and stored in the browser's cache$
var myimage = new 5mage0.
myimagesrc = ,thinggif,.
"ow each time I want to change an image on the page I can
saydoc1ment&,imagename,*src = myimagesrc.and the image will change without
having to wait for the new image to load.
6ption
+reates an option that can be added into a select input for e#ample$
var myoption = new 8ption,text,2,val1e,0.
select5np1toptions&select5np1toptionslength* = myoption.
See the section on '+reating ob4ects'for how to create your own ob4ects that are not one of the pre-
defined ob4ect types. ,6 compliant browsers will provide far more ob4ect types - these will be
covered in later chapters of this tutorial.
Deleting properties
6n several occasions here I have created properties for ob4ects. 3ven if these are set to undefined
or null they still e#ist holding that new value and will be found using the for-in control structure. *ou
can delete them completely by using the 'delete' !eyword$
delete my8bjectitsCroperty.
6f course unless you have serious computer memory considerations or security ris!s it is usually
not necessary to do this at all since JavaScript engines clean up after themselves once the variable
is no longer referenced.
http://www.howtocreate.co.uk/tutorials/javascript/objectshttp://www.howtocreate.co.uk/tutorials/javascript/objectshttp://www.howtocreate.co.uk/tutorials/javascript/objectshttp://www.howtocreate.co.uk/tutorials/javascript/controlshttp://www.howtocreate.co.uk/tutorials/javascript/objectshttp://www.howtocreate.co.uk/tutorials/javascript/controls -
8/13/2019 38954115 Javascript Tutorial
25/265
$voiing errors with variables
If at any time you refer to a variable that does not e#ist you will cause an error. owever JavaScript
allows you to refer to one level of undefined child properties of an ob4ect. This is a very important
rule to learn as it forms the basis of ob4ect and capability detection and is fundamental to ma!ing
cross browser scripts. The following series of e#amples will demonstrate what will throw errors$
var my8bject = new 8bject02 non8bject = ,,2 non8bject4.
This sets everything up for the following e#amples. So far everything is fine but in the code below b
is undefined. This will cause an error$
var a = b% @.
In the ne#t e#ample the parent ob4ect has been defined but its property has not. Since this is only
one level of undefined properties this is allowed and will not cause an error$
var b = my8bjectmy'hild.
In the ne#t e#ample the parent ob4ect has been defined but its property has not. Trying to refer to a
child of the non e#istent property means there are now two levels of undefined properties. This will
cause an error$
b = my8bjectmy'hildits'hild.
In the ne#t e#ample the parent ob4ect has been defined but it is a type of variable that cannot
accept child properties. Trying to create a child property will not throw an error since it is only one
level of undefined properties. owever it will not do anything since the new property will be
re4ected$
non8bjectits'hild = .
windowalertnon8bjectits'hild0.
//This will alert ,1ndefined,
-
8/13/2019 38954115 Javascript Tutorial
26/265
In the ne#t e#ample the parent ob4ect has been declared but it was not given a value. As a result it
holds the value undefined. Trying to refer to a child property means there are now two levels of
undefined properties and will throw an error$
non8bject4its'hild= .
&eferencing a variable or "ust its value
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
it 4ust provides you with a new way to reference that variable. The following is an e#ample of where
this might occur$
var myAew+ariable = my8ld+ariable.
If my8ld+ariablewas already defined as a string number boolean null or undefined it would
simply have copied my8ld+ariableand 'pasted' it into myAew+ariable. If the new variable were
changed 0for e#ample using myAew+ariable = ,some new val1e,.1 my8ld+ariableretains its old
value.
If on the other hand my8ld+ariablewas already defined as a function array ob4ect or
optionmyAew+ariablewould have been created as a pointer to my8ld+ariable. The children of
my6ld(ariable would now also be the children of my"ew(ariable. If the new variable were changed
0for e#ample usingmyAew+ariable = ,some new val1e,.1 it would only alter the value
of myAew+ariableso that it no longer references the same contents as my8ld+ariable. owever
changing the child properties ofmyAew+ariablewill change the properties of the ob4ect it
references and as a result my8ld+ariablewould also see the change$
var my8ld+ariable = new 8bject0.
var myAew+ariable = my8ld+ariable.
myAew+ariablenew'hild = ,-ello,.
alertmy8ld+ariablenew'hild0.
//This will alert ,-ello,
-
8/13/2019 38954115 Javascript Tutorial
27/265
More about numbers
JavaScript understands numbers in several formats allowing you to specify numbers in he#
decimal and octal. If a G precedes a number and there is no number higher than the number is
considered to be in octal 0base L1 and if the number is preceded by G# then it is considered to be in
he# 0base
-
8/13/2019 38954115 Javascript Tutorial
28/265
Special string characters
There are a few string characters that can be escaped with a bac!slash and can be used to replace
untypeable characters. These are$
Rn
A newline character. @se this if you want to insert a line brea! into te#t.
Rf
A form feed. Try not to use this ever. @se Rn instead.
Rr
A carriage return. Try not to use this ever. @se Rn instead.
Rt
A tab character.
RR
A R character
R&
A & character 0most web developers Pmyself included on occasionQ forget this one - generallybrowsers will have no trouble with you forgetting the bac!slash but it is important for
representing closing tags and in theory you should always use the bac!slash escape when
writing a forward slash - see the section on )riting with scriptfor details of where it is
needed1
If you need to recognise a )indows linebrea! you need to loo! for RrRn. If you are trying to add a
linebrea! 0for e#ample when modifying the value of a te#tarea input1 you should insert a Rn
character. This will wor! cross browser. "ote that browsers on )indows may convert this Rn
character into a RrRn automatically depending on where you use it.
6ld ac 6perating Systems 06S D and below1 used Rr for linebrea!s but as far as my tests showed
they are converted to Rn by JavaScript. owever 4ust be aware that you may encounter some of
these especially in te#t inputs 0ac 6S D is still popular among ac users - probably a little less
than HG of the ac mar!et1. @ni# based 6perating Systems 0including ac 6S 91 use Rn for
linebrea!s.
http://www.howtocreate.co.uk/tutorials/javascript/writinghttp://www.howtocreate.co.uk/tutorials/javascript/writinghttp://www.howtocreate.co.uk/tutorials/javascript/writing -
8/13/2019 38954115 Javascript Tutorial
29/265
If you are writing a string that contains double %uotes the easiest way to deal with it is to surround it
with single %uotes. *ou should also use double %uotes if your string contains single %uotes$
var mystring = ,)nd he said "help" twice,.
var mystring = "-elp )ndy,s cat".
*ou may notice a problem. )hat if you have both single and double %uotes in your string The
solution is to use the escape character 'R' to e#cape the %uotes 0in fact you can always escape
%uotes even if the string is delimited by the other type of %uotes1. For e#ample both of the following
are valid$
var mystring = ,)nd he said "help )ndyL,s cat" twice,.
var mystring = ")nd he said L"help )ndy,s catL" twice".
If your string becomes too long to fit on one line 0this really doesn't matter - you can ma!e the te#t as
long as you want1 and you want to split it onto several lines simply end the string follow it with the
concatenation operator and start a new string on the ne#t line$
var mystring = ,first line of the string , %
,still on the first line of the string $ itL,s li!e we never bro!e the line,.
"ote in theory you can use R to brea! the string$
var mystring = ,li!e L
this,.
ut this has significant problems2 the R will not always cope with trailing whitespace may or may not
correctly treat the leading whitespace before the new line and does not wor! correctly in all
JavaScript implementations$
"etscape 0inventors of JavaScript1 3scape 6pera .M- and I+3browser include the
linebrea!s in the string.
Internet 3#plorer o7illa&FireFo# 6pera L Safari&Uon%ueror i+ab and 6mni)eb ignore
the linebrea! characters.
-
8/13/2019 38954115 Javascript Tutorial
30/265
I+3browser sometimes ignores the whole string
I mention this only for completeness. ,o not use it. It is easier and better to use the concatenation
operator as shown above.
&egular expressions
6pera -M has a ma4or bug in its regular e#pression handling and will fail on even the simplest regular
e#pressions.
5oc!et Internet 3#plorer Internet 3#plorer for )indows +3 and i+ab =- do not support regular e#pressions
properly.
+ertain methods li!e the string8bjectreplace0and string8bjectmatch0methods can
recognise patterns in te#t. To do this they use regular e#pressions. These are well
documented elsewhereso I will not describe the synta# here. asically what you can do is use
special characters to recognise te#t patterns 0li!e Rw for characters a-7 A-V G-D and W1. To define a
collection of characters as a regular e#pression you use the & character 0sometimes with a g or i
after it1. For e#ample the regular e#pression /L/L&LwLM*LL//matches bloc! comments.
Some rare browsers do not support regular e#pressions. In theory you should be able to detect
regular e#pression support using this$
if windowNegOxp 0 F var myNeg1larOxpression = new NegOxp"pattern"0. G
This should not produce errors in 5oc!et Internet 3#plorer and Internet 3#plorer for )indows +3 0as
they do not understand the &pattern&options synta# or support the ;eg3#p ob4ect1. owever as
6pera M- and i+ab =- support the ;eg3#p ob4ect but fail to use it correctly your scripts will still fail
though hopefully without errors. Than!fully current releases of 6pera and i+ab do support regular
e#pressions correctly.
ontrol structures
The 1if1 statement
if my+ariable == 4 0 F
my+ariable = 9.
http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.5/guide/regexp.htmlhttp://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.5/guide/regexp.html -
8/13/2019 38954115 Javascript Tutorial
31/265
G else F
my+ariable = :.
G
If my(ariable had been = it would now be
-
8/13/2019 38954115 Javascript Tutorial
32/265
avoiding this synta#. It ma!es your code harder to read especially if you start nesting your control
structures. It also ma!es it easy to forget to put them in when you needed them and also ma!es
debugging code much harder since you will need to go bac! through your code to add them so that
you can add e#tra debugging tests. It is best to always use the curly braces even if they are
optional.
As always there is an e#ception. "ested 'if' statements li!e this can start to get difficult to manage$
if my+ariable == 4 0 F
my+ariable = 9.
G else F
if my+ariable == @ 0 F
my+ariable = ;.
G else F
my+ariable = ?.
G
G
y strategically removing curly braces that can usefully be reduced to this construct 0which you mayrecognise from other programming languages1 - note that 'else if' is notwritten as 'elseif'$
if my+ariable == 4 0 F
my+ariable = 9.
G else if my+ariable == @ 0 F
my+ariable = ;.
G else F
my+ariable = ?.
G
-
8/13/2019 38954115 Javascript Tutorial
33/265
The 1for1 loop
This is one of the most common constructs in use. Typically it is used to cycle through the contents
of an array or to create a specific number of new ob4ects but it can do many more useful things if
needed. The synta# of the 'for' loop is as follows$
for starting3initialise. contin1e3as3long3as3condition. do3this3each3time 0
startingWinitialise
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 0if you have not done so
already1. *ou can define multiple variables if needed using$
var my+ariable9 = val1e2 my+ariable4 = another3val1e.
These variables are not restricted to being inside the 'for' loop and will be available to all
code after the loop 0in the same scope as the loop1.
continueWasWlongWasWcondition
This is where you define the conditons under which the loop should continue to e#ecute. The
synta# is e#actly the same as for the 'if' statement so you can apply more than one continue
condition by using the BB or XX operators$
my+ariable9 = :.
If the condition is not satisfied when the for loop begins then it will never loop through it.
doWthisWeachWtime
6nce the end of the loop is reached it will do whatever you tell it to here. Typically this is
used to increment or decrement a stepping variable and it is possible to perform actions on
more than one variable by separating them with a comma$
my+ariable9%%2 my+ariable4 $= ?
The following is a full e#ample.
-
8/13/2019 38954115 Javascript Tutorial
34/265
for var my+ariable = 9. my+ariable
-
8/13/2019 38954115 Javascript Tutorial
35/265
The 1while1 loop
The 'while' loop is identical in behaviour to the 'for' loop only without the initial setup and loop-end
actions. It will continue to run as long as the condition is satisfied$
var my+ariable = 9.
while my+ariable
-
8/13/2019 38954115 Javascript Tutorial
36/265
do F
my)rray&my+ariable* = 9.
my+ariable%%.
G while my+ariable
-
8/13/2019 38954115 Javascript Tutorial
37/265
If a case is satisfied the code beyond that case will also be e#ecuted unless the brea! statement is
used. In the above e#ample if my(ar is
-
8/13/2019 38954115 Javascript Tutorial
38/265
x = ro1nd RA4 % O % pow y2 ? 0 0.
G
"ote that the 'with' statement brings e#tra variable names into the current scope. In the e#ampleabove if I already had a variable called powbefore the 'with' statement this variable would be
unavailable inside the with statement as it would have been replaced by the method of
the Hathob4ect 0as would any other variables that matched property or method names1. 6nce the
'with' statement is complete the old variables would become available again.
The 3uick 1if1 statement
This is !nown as the conditional or ternary operator and is an easy way to assign different values toa variable depending on a condition.
var my+ariable = doc1mentgetOlementy5d 9 6 :.
This is identical to$
if doc1mentgetOlementy5d 0 F
var my+ariable = 9.
G else F
var my+ariable = :.
G
The tr! 2 catch 2 finall! statement
"etscape Internet 3#plorer and )ebT( do not support this structure and will produce errors if you use
it.
The 'try - catch - finally' control stucture allows you to detect errors and %uietly deal with them
without producing error messages or aborting the script and in fact without even interrupting the
-
8/13/2019 38954115 Javascript Tutorial
39/265
flow of the script that is running. This ma!es it superior to the original way of handling script errors
0without error messages1 where scripts are completely aborted$
windowonerror = referenceTo71nction.
The synta# of the 'try - catch - finally' control stucture is as follows$
try F
//do something that might ca1se an error
G catch myOrror 0 F
//if an error occ1rs2 this code will be r1n
//two properties will by defa1lt0 be available on the
//object passed to the statement
alert myOrrorname % ,6 , % myOrrormessage 0.
G finally F
//optional $ this code will always be r1n before the
//control str1ct1re ends2 even if yo1 rethrow the error
//in the catch
G
If an error occurs in the 'try' section it immediately 4umps to the 'catch' part passing some
information about the error. ,ifferent browsers provide different information for the same error so
don't trust it 0in theory ,6 browsers will use a specific set of error types but this depends on their
level of ,6 support - Internet 3#plorer is the least compliant here1. 6nce the 'try' or 'catch' parts
have been run the 'finally' part is run if you have provided one then the script following the control
structure is run unless you throw another error.
If you nest these statements 0one 'try - catch' inside another1 you can rethrow the error from the
'catch' part of the inner statement to the 'catch' part of the outer statement 0the 'finally' part - if there
is one - would still be run before the outer 'catch' is run but the script following the inner structure
will not be run1. This is done using the ,throw,method$
-
8/13/2019 38954115 Javascript Tutorial
40/265
tryF
//some other code goes in here
try F
var a = nonexistb. //this will prod1ce an error
G catchmyOrror0 F
//this catches the error and alerts the message
alert myOrrormessage 0.
//re$throw the error 1p to the o1ter try $ catch
throw myOrror 0.
G
//some other code goes in here
G catch myOrror8bject 0 F
//5 re$threw the first error2 so this is the same error object
//the message sho1ld be the same
alert myOrror8bjectmessage 0.
G
*ou can also throw your own errors at any point by creating an ob4ect with the re%uired properties
and passing it as the parameter when using throw$
tryF
var myOr = new 8bject0.
myOrname = ,Hy error,.
myOrmessage = ,Ko1 did something 5 didnL,t li!e,.
throw myOr 0.
G catch detectedOrror 0 F
-
8/13/2019 38954115 Javascript Tutorial
41/265
alert detectedOrrorname % ,Ln, % detectedOrrormessage 0.
G
'hat is wrong with it4
It's lac! of support in older browsers is its ma4or failing. Than!fully these browsers are hardly used
any more. It would be very useful to use this structure detect errors in "etscape 0li!e the 'this'
!eyword inline method bug- for e#ample - there are lots more errors1 but that browser does not
support the statement. It would also be useful for chec!ing for stupid bugs li!e where chec!ing for
something li!e navigatortaintOnabledcauses errors in Internet 3#plorer. owever the error is
not correctly thrown for these errors.
@nfortunately 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.
It should never be used to detect if a browser supports a method or property
li!edoc1mentgetOlementy5das a proper ob4ect detect would suffice.
So when shoul it be use4
It can be used for ):+ ,6 scripting where you may want to avoid ,6 mutation errors 0for
e#ample1 which are valid errors but serve to warn you not to do something and do not always need
to abort the whole script. 6lder browsers do not support the ,6 anyway so it doesn't matter if they
don't understand this part of it. owever they will still run the script 0it is not possible to protect them
by using the language attribute on the script tag as you need to use JavaScript
-
8/13/2019 38954115 Javascript Tutorial
42/265
try F
selectoxaddoption8bject2other8ption8bject0.
G catch e 0 F
selectoxaddoption8bject2index0.
G
)onitionals without a conition4
*ou may notice in the e#ample for >The %uic! 'if' statement> that I tested for a property without
testing for any specific value$ 'if doc1mentgetOlementy5d 0'
That is valid and is one of the most useful parts of JavaScript. This is a very important rule to learn
as it forms the basis of ob4ect and capability detection and is fundamental to ma!ing cross browser
scripts. This will be true if$
doc1mentgetOlementy5d #= "" PP
doc1mentgetOlementy5d #= : PP
doc1mentgetOlementy5d #= false PP
doc1mentgetOlementy5d #= 1ndefined PP
doc1mentgetOlementy5d #= n1ll
The opposite is also possible$ 'if #doc1mentgetOlementy5d 0'
This will be true if$
doc1mentgetOlementy5d == "" QQ
doc1mentgetOlementy5d == : QQ
doc1mentgetOlementy5d == false QQ
doc1mentgetOlementy5d == 1ndefined QQ
doc1mentgetOlementy5d == n1ll
-
8/13/2019 38954115 Javascript Tutorial
43/265
@sing this you can detect one type of capability and if it fails detect another type and continue until
you find one that wor!s.
*ou can also do this anywhere where a condition is e#pected such as with the 'while' loop condition
the'do - while' loop condition and the 'continueWasWlongWasWcondition' in the for loop.
)hecking for properties with 1in1
)ebT( crashes if you use the 'in' operator to chec! for a property that does not e#ist.
"etscape Internet 3#plorer H.G- on )indows and Internet 3#plorer on ac cannot use the 'in' operator as
shown here.
The 'in' operator used in the 'for - in' loop has another purpose. It can also be used to chec! for the
e#istence of named properties of an ob4ect. In most cases it is best to use a conditional without acondition as shown above. owever there are some cases where you want to test for the e#istence
of a property even thought the property's value may be one that does not evaluate to true. An
e#ample would be where you want to chec! for the e#istence of a property whose value may be G or
an empty string or null.
If you !now what the type of the property will be it is possible to achieve this using identity
operators or thetypeofoperator as shown here$
if typeof doc1mentbodyinner-THR 0 == ,string, 0 F
owever it is also possible to use the 'in' operator to test for a property. This allows you to test for
its e#istence no matter what value it currently holds and no matter what type of value it currently
has 0even if it has been assigned a value of 1ndefined1. In the 'for - in' loop the 'in' operator
returned the name of properties as a string and so here it e#pects the name to be a string. This
limits the usefulness a little as it can only search for the name and cannot be used to see if one of
the properties holds a specific value or value type.
if ,inner-THR, in doc1mentbody 0 F
"ote that this is around =G times slower in Internet 3#plorer than the conditional without a condition
as shown above. In most other browsers the two alternatives perform about the same. In general I
consider it best to use the more common alternatives unless you have a specific use that needs the
behaviour of the 'in' operator.
-
8/13/2019 38954115 Javascript Tutorial
44/265
$ssignments insie a conitional
JavaScript allows you to perform an assignment at the same time as testing if the assignment
wor!ed. This can be used inside any conditional including inside an 'if' 'for' 'while' and 'do - while'.
if x = doc1mentgetOlementy5d,mydiv,0 0 FG
do F
alert nodetagAame 0.
G while node = nodeparentAode 0.
"ote that Internet 3#plorer on ac will produce an error if you try to do this with an array when it
steps off the end of the array.
)ontinue an break statements an labels
Labels
/abels are used to name the 'while' 'do - while' 'for' 'for - in' and 'switch' control structures. The
synta# used is$
RabelAame6
'ontrol Str1ct1re
/abels are very rarely used in JavaScript.
The break statement
)riting brea! inside a switch for for-in while or do - while control structure will cause the program
to 4ump to the end of the statement. If you 4ust use for e#ample$
for var x = 9. x < @. x%% 0 F
var y = 9.
while y < 0 F
-
8/13/2019 38954115 Javascript Tutorial
45/265
y%%.
if y == @ 0 F brea!. G
doc1mentwritey0.
G
G
The script will 4ump past the end of the while loop when y is H. ut if you use this$
my7orRoop6
for var x = 9. x < @. x%% 0 F
var y = 9.
while y < 0 F
y%%.
if y == @ 0 F brea! my7orRoop. G
doc1mentwritey0.
G
G
The script will 4ump past the end of the for loop when y is H.
The continue statement
)riting continue inside a 'for' 'for - in' 'while' or 'do - while' control structure will cause the program
to 4ump to the test condition of the structure and re-evaluate it having performed any
'doWthisWeachWtime' instructions. If you 4ust use this for e#ample$
for var x = 9. x < @. x%% 0 F
var y = 9.
-
8/13/2019 38954115 Javascript Tutorial
46/265
while y < 0 F
y%%.
if y == @ 0 F contin1e. G
doc1mentwritey0.
G
G
This script will 4ump to the test condition of the while loop when y is H so H will never be written but M
and will be. If you use this instead$
my7orRoop6
for var x = 9. x < @. x%% 0 F
var y = 9.
while y < 0 F
y%%.
if y == @ 0 F contin1e my7orRoop. G
doc1mentwritey0.
G
G
ere the script will increment # as part of the for loop and then re-evaluate the for condition.
!riting wit" script
e careful when writing with script. If script is not available that content will not be created. *ou
should limit your use of this to parts of the page that are not needed to access page content. If you
do write important parts of the page that are unavailable without scripting you should
use tags to provide an alternative.
-
8/13/2019 38954115 Javascript Tutorial
47/265
'riting while the page is still loaing
If your code is being e#ecuted while the page is still loading 0in other words if it is run as part of the
initial page layout1 put the following$
doc1mentwrite,
Mhat ever yo1 want to write,0.
doc1mentwriteln,
Mhat ever yo1 want to write,0.
//writeln p1ts a line brea! after the line
//This is treated as a line brea! in the so1rce of -THR
It will write whatever you put in whatever part of the page the script is currently running. 6f course
you can include T/ tags in there too or some pre-programming.
"ote that if you write content using an event handler 0such as the onload handler for an image1 it
will be treated as if the page has completed loading even if it has not.
'riting after the page has loae
After the page has completed loading the rules change. Instead of adding content to the page it will
replace the page. To do this you should firstly open the document stream 0most browsers will
automatically do this for you if you 4ust start writing1. 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 e#ception here is the o7illa&Firefo# family of browsers that will
continue to show a loading graphic until you close the stream. Some other browsers may fail to
render part or all of the content. Just to be safe ma!e sure you always close the stream.
doc1mentopen0.
doc1mentwrite,
Mhat ever yo1 want to write,0.
doc1mentwrite,
Hore st1ff yo1 want to write,0.
-
8/13/2019 38954115 Javascript Tutorial
48/265
doc1mentclose0.
That will remove everything that is currently being shown and replace it with what you write in there.This is the e%uivalent of moving the user to a completely new page. *ou should put Ehtml tags and
things li!e that in there too if you want to use that method.
*ou may notice that I close my T/ tags inside the script with a bac!slash before the forward
slash in the closing tag. This is a re%uirement of the specification 0and can cause the T/ validator
not to validate your page if you forget it1 although all browsers will understand if you omit the
bac!slash.
owever since you can write T/ with script you can write style or even script tags with it
ma!ing one script import another. If you omit the bac!slash on any E&script tags that you are writingwith the script the browser will read that as the closing tag for the current script and your script will
fail.
The same applies to opening or closing comments 0although I fail to see why you would want to
write comments using a script1. These can be written as ,,. )hen the script
runs the plus sign tells it to append the strings creating a valid T/ comment.
0roblems with ol browsers
Although not really in use any more you may want to be nice to older browsers li!e "etscape . If
using doc1mentwriteto dynamically write a div element do notgive the div an inline style with
left$ or top$ positioning. This will cause "etscape to fail completely and be unrecoverable without
careful use of dialogs and tas! !ills.
Also "etscape will completely fail to load if you attempt to use this method to create a and instead you should use the unnofficial tag. *ou can use
if doc1mentlayers 0to detect if the layer tag should be used.
-
8/13/2019 38954115 Javascript Tutorial
49/265
!riting #unctions
+eneral s!ntax
5re-alpha versions of T!html v: do not correctly interpret the Function class constructor.
Functions group together script code2 control structures operations method calls etc. in the same
way as a normal script. These functions can then be called when needed and the code contained
within them will be run. This ma!es it very easy to reuse code without having to repeat it within your
script.
Functions are defined using one of these constructs$
"ormal function construct
f1nction name8f71nctionlist8f+ariableAames0 F
f1nction code sho1ld be written here
G
Anonymous function assigned to a variable
@sing this synta# for ob4ect methods in early "etscape versions will cause problems with
the 'this' !eyword due to bugs.
name8f71nction = f1nction list8f+ariableAames0 F
f1nction code sho1ld be written here
G.
"ormal function construct assigned to a variable
name8f71nction = f1nction anotherAame7orThe71nctionlist8f+ariableAames0 F
f1nction code sho1ld be written here
G.
-
8/13/2019 38954115 Javascript Tutorial
50/265
"ote that in this particular case because the function is being assigned and not defined
normally the name anotherAame7orThe71nctioncan be used by the code inside the
function to refer to the function itself but the code outside the function cannot see it at all
0note that some browsers mainly Internet 3#plorer do not implement this correctly so you
should not rely on it - it is better to usearg1mentscalleeas shown below1.
The Function class constructor
f1nctionAame = new 71nction"f1nction code sho1ld be written here"0.
This construct evaluates the code as a string and is much slower than assigning anonymous
functions. It should only be used in places where it is actually needed.
The Function class constructor with parameters
f1nctionAame = new 71nction"varAame"2"varAame4"2"etc"2"f1nction code"0.
See the section on ';eferencing'subsection 'Avoiding referencing conflicts'to see how to choose
names for your functions.
Functions are called using one of these$
name8f71nctionlist8f+ariables0.
windowname8f71nctionlist8f+ariables0.
objectonOventAame = name8f71nction.
)hen created using the normal function construct the definition does not have to appear at the start
of the script 0though it is usually best to do so for the sa!e of clarity1. It can even be defined after the
the code that calls it. In most cases no matter where you choose to define your function the
JavaScript engine will create the function at the start of the currentscope.
"ote that you should never create a function using the normal function construct inside an 'if'
statement 0or any e%uivalent control structure1$
if some'ondition 0 F
f1nction f1nctionAame0 F
this will not wor! in most browsers
http://www.howtocreate.co.uk/tutorials/javascript/referencinghttp://www.howtocreate.co.uk/tutorials/javascript/referencinghttp://www.howtocreate.co.uk/tutorials/javascript/referencinghttp://www.howtocreate.co.uk/tutorials/javascript/objectoriented#refconhttp://www.howtocreate.co.uk/tutorials/javascript/objectoriented#refconhttp://www.howtocreate.co.uk/tutorials/javascript/objectoriented#refconhttp://www.howtocreate.co.uk/tutorials/javascript/functions#varscopehttp://www.howtocreate.co.uk/tutorials/javascript/functions#varscopehttp://www.howtocreate.co.uk/tutorials/javascript/referencinghttp://www.howtocreate.co.uk/tutorials/javascript/objectoriented#refconhttp://www.howtocreate.co.uk/tutorials/javascript/functions#varscope -
8/13/2019 38954115 Javascript Tutorial
51/265
G
G
This is permitted by o7illa's JavaScript
-
8/13/2019 38954115 Javascript Tutorial
52/265
G
This function when called will set the value of a te#t input to whatever value of passvar was as long
as passvar was not blan!.
As an e#ample part of my html will contain this$
-
8/13/2019 38954115 Javascript Tutorial
53/265
windowalertvariable90. //alerts @
windowalertarg1ments&:*0. //alerts @
windowalertvariable40. //alerts
windowalertarg1ments&9*0. //alerts
windowalertarg1ments&4*0. //alerts
windowalertf1nctionAamearg1ments&;*0. //alerts
G
f1nctionAame@2220.
The arg1mentscollection also has a very useful property2 arg1mentscallee. This is a referenceto the function itself meaning that code running inside an anonymous function can still obtain a
reference to the function that is being run. This property is not available in some older browsers.
,sing the return statement
The return statement causes a function to stop e#ecuting at that point. The code that called the
function will still continue to e#ecute.
f1nction doMhatever0 F
var apod = Hathpow;20.
ret1rn.
//the following code will not be exec1ted2
//no matter what
apod = ;?.
if :: ;
-
8/13/2019 38954115 Javascript Tutorial
54/265
G else F
windowalert,The script has made a mista!e,0.
G
G
The following is an e#ample of using the return statement to return a variable from a function$
f1nction append'ommentpassvar0 F
//in this case2 5 have passed a string variable and 5 ret1rn
//a string variable 5 co1ld ret1rn any variable type 5 want
passvar %= , witho1t yo1r help,.
ret1rn passvar.
G
var myString = append'omment,5 did it,0.
//myString is now ,5 did it witho1t yo1r help,
"ote that if you need your code to wor! in older browsers it is important to ma!e sure that if the
return statement is used to return a value you must ensure that in all cases the function returns a
value or some "etscape versions will produce errors.
Ta!e for e#ample the action of fading. I want to write the same thing repeatedly slowly fading from
one colour to another. ;ather than having to calculate this manually I want to run some script that
calculates the fade for me. The script will run nicely as part of a function where the function returns
the ne#t colour at each step which I can then use. This is useful because I can then use the same
function to produce a variation of the same effect later on based on different parameters.
f1nction fade'olo1r fromcol2 tocol2 fadeCortion 0 F
//in the format fade'olo1r ,ff::U,2 ,fe:U;?,2 :4; 0
var o7 = &*2 oT = &*2 oC = &*.
-
8/13/2019 38954115 Javascript Tutorial
55/265
var o- = &,:,2,9,2,4,2,;,2,?,2,@,2,,2,,2,,2,U,2,a,2,b,2,c,2,d,2,e,2,f,*.
//get the red2 green and bl1e s1bstrings
for var x = :. x < ;. x%% 0 F
// and convert them from hex into decimal
o7&x* = eval ,:x, % fromcols1bstring 4 x2 4 x 0 % 4 0 0.
oT&x* = eval ,:x, % tocols1bstring 4 x2 4 x 0 % 4 0 0.
// add on the reV1ired portion of difference between the two
oC&x* = Hathro1nd o7&x* % oT&x* $ o7&x* 0 fadeCortion 0 0.
// and convert it bac! into hex
oC&x* = o-& oC&x* $ oC&x* 9 0 0 / 9 * % o-& oC&x* 9 *.
G
// and p1t them bac! together again as a colo1r string
ret1rn ,W, % oCjoin,,0.
G
for var y = :. y < 9:. y%% 0 F
//in 9: steps2 fade the colo1r $ also see the section on writing with script
doc1mentwrite ,7ade# , 0.
G
for var y = :. y < 94. y%% 0 F
//in 94 steps2 fade the colo1r
doc1mentwrite ,7ade# , 0.
-
8/13/2019 38954115 Javascript Tutorial
56/265
G
FadeYFadeYFadeYFadeYFadeYFadeYFadeYFadeYFadeYFadeY
FadeYFadeYFadeYFadeYFadeYFadeYFadeYFadeYFadeYFadeYFadeYFadeY
!arning if you are returning a value from a function do not call the function directly from the
-
8/13/2019 38954115 Javascript Tutorial
57/265
inside thesamplefunction has access to them. The samplefunction is also global since it is not
inside any other functions. If any other piece of code changes the contents of those variables then
every other part of the code now sees the new contents. As a result the alert here will show ''
since the value held by the global variable is changed when the function is run.
(ariable dis defined inside the samplefunction so it is not global. It is in the local scope of the
function. )hat that means is that only the code inside the function can see it. +ode outside the
function does not even !now it e#ists. This happens with any function. They have the ability to create
their own scopes and their own local variables without them interfering with variables located in the
global scope. (ariable names written in the brac!ets of the function definition are also created as
variables in the local scope 0and the same applies to the arg1mentscollection1$
f1nction samplemyvar0 F
//myvar is now a variable in the local scope
alertmyvar0.
G
sample,hello,0.
"ow try this modification to the earlier code$
var a = 92 b = 42 c = ;.
f1nction sample0 F
var a2 d.
a = .
G
sample0.
alerta0.
ere the variable ais redefined inside the function. ecause it is declared using the var!eyword it
becomes a local instance of a variable. 3ven though it shares the same name as a global variable
the two are completely independent. The changes made to that variable inside the function only
affect the local variable not the global one. As a result the alert will show '
-
8/13/2019 38954115 Javascript Tutorial
58/265
"ow imagine that the code inside the function wants to reference the global variable ,a,instead of
the local one. The global scope is special. In JavaScript the global scope can be referenced using
the name,window,. The code inside the function can use windowato reference the
global ,a,variable. Incidentally this is why methods li!e alert can be called using
either alertor windowalert since these methods are globally available 0unless they are
overwritten in the current scope of course1.
Neste functions
It is possible to create functions inside other functions. Simply declare another function inside the
code of an e#isting function$
var a = 92 b = 42 c = ;.
f1nction sample0 F
var a2 d2 e.
f1nction anothersample0 F
var e2 f.
G
anothersample0.
G
sample0.
In that e#ample the anothersamplefunction only e#ists inside the samplefunction and it can only
be called by the code inside the samplefunction. +ode outside that function does not even !now it
e#ists. The scopes are also nested so the code inside the anothersamplefunction has access
to band c from the global scope aand dfrom the samplescope and then eand ffrom its own
local scope. It can also use windowato reference the variable afrom the global scope.
6f course if you assign a reference to the nested function to a global variable then the function can
be accessed globally through that variable. There is not much point in doing that here but it
becomes very useful when creating ob4ect methods 0these will be covered in detail in a later
chapter1.
-
8/13/2019 38954115 Javascript Tutorial
59/265
Scopes have memor!
Scopes are actually very clever since they persist over time. Imagine that the code inside a function
creates a local variable. It also creates an event handler function that will be triggered when the user
clic!s a lin!$
f1nction sample0 F
var a = 4:.
doc1mentlin!s&:*onclic! = f1nction 0 F
alerta0.
G.
G
sample0.
The action that calls the event handler 0inner1 function happens much later a long time after the
script that created it has finished running. owever the variable ,a,has survived so the alert will
display the number =G.
,sing scope to prevent conflicts
Imagine that you are running a script that uses many global variable and function names. *ou want
to put another script on the same page but there is a chance that the two scripts will use the same
variable names as each other and may conflict. It is easy to wor!around this problem by putting the
code from each script inside a function and running the function. That way the local scope provided
by the function will protect the variables overwriting each other in the global scope. "ote that when
doing this it is veryimportant that you remember to declare your variables properly.
The easy way to do this without creating a global function is to create an anonymous function and
enclosing it in parenthesis 0internally the engine will then replace that entire construct with the
function reference1. *ou can then use the open-close parenthesis to run it immediately. This
construct may loo! a little odd but it wor!s$
f1nction 0 F
//C1t yo1r script code in here
-
8/13/2019 38954115 Javascript Tutorial
60/265
G00.
,sing neste function scope to preserve instantaneous values
This is an advanced topic that iscovered in its own articlegiven below.
$"e problem
This problem is encountered with event handlers and in other situations such as when adding
methods to an ob4ect. ost )eb authors first encounter it with event handlers so that is what this
article will concentrate on but you should be aware that it also applies to those other situations.
In JavaScript whether using traditional event handlers or ,6 events event handlers are attached
to their relevant ob4ect as a reference to the function. In standards compliant browsers when the
event fires the function is e#ecuted as a method of the ob4ect and passed a single parameter2 the
event ob4ect. In Internet 3#plorer it is not passed any parameters at all$
f1nction myhandlere0 F
G
mydivonclic! = myhandler.
mydiv4addOventRistener ,clic!,2 myhandler2 false 0.
There are many occasions when it is desirable to pass a local variable to the handler function. An
e#ample would be when looping through a list of elements and assigning the same event handler to
each of them but needing to pass a uni%ue identifier to each handler so it can always reference the
inde# of the element within a collection. *ou may also want to pass an ob4ect not 4ust an inde#.
5erhaps this would be a reference to another element that is relevant to the handler.
The obvious desire is to try something li!e this$
mydivonclic! = myhandleri2myobject0.
owever this does not wor!. )hat it will do is immediately e#ecute the handler as a normal function
passing it the variables. Then whatever the function returns even if that is a string or perhaps
http://www.howtocreate.co.uk/referencedvariables.htmlhttp://www.howtocreate.co.uk/referencedvariables.htmlhttp://www.howtocreate.co.uk/referencedvariables.htmlhttp://www.howtocreate.co.uk/referencedvariables.html -
8/13/2019 38954115 Javascript Tutorial
61/265
nothing at all is assigned as a property of the element with the name of the event handler. 6bviously
this will not wor! correctly as an event handler.
There are three main ways to overcome the problem. The first two are the most common but have
limitations. The third is one of the most complete solutions but is not very common. The
demonstrations are all prepared assuming the following e#ample algorithm$
f1nction myf1nction0 F
var paras = doc1mentgetOlementsyTagAame,p,0.
var spans = doc1mentgetOlementsyTagAame,span,0.
for var i = :. i < paraslength. i%% 0 F
paras&i*onclic! = f1nction e0 F
//ass1me that here2 we want to !now
// $ what the val1e of i was for this element
// $ the span that corresponds to spans&i*
G.
top related