Documente Academic
Documente Profesional
Documente Cultură
JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers, !s, laptops, tablets, smart phones, and more.
You can only use document.write in the HT ! output. "# you use it a$er the document has loaded% the whole document will &e o'erwri(en.
The alert,- function is not much used in JavaScript, but it is often .uite hand$ for tr$ing out code. The onclic/ event is onl$ one of the man$ HTML events $ou will learn about in this tutorial.
*#ample
/)document.get0lement1y"d("demo") //2ind the element /.innerHT !)"Hello 3a'a4cript"; //.hange the content
&ou will often see document.get*lement'$I1,2 some id 2-. This is defined in the HTML 1)M. The 1)M ,1ocument )b3ect Model- is the official %4! standard for accessing HTML elements.
*#ample
/)document.get0lement1y"d("demo") //2ind the element /.style.color)"567777"; //.hange the style
*#ample
i# is8a8(/) 9alert("8ot 8umeric"):;
Scripts in HTML must be inserted between 8script9 and 8:script9 tags. Scripts can be put in the 8bod$9 and in the 8head9 section of an HTML page.
&ou don't have to understand the code above. Just ta/e it for a fact, that the browser will interpret and e#ecute the JavaScript code between the 8script9 and 8:script9 tags.
Dld e/amples may ha'e type)"te/t/Ea'ascript" in the <script> tag. This is no longer reFuired. 3a'a4cript is the de#ault scrip@ng language in all modern &rowsers and in
HT !B.
JavaScript in 8bod$9
In this e#ample, JavaScript writes into the HTML 8bod$9 while the page loads(
*#ample
<-GD.TYH0 html> <html> <&ody> . . <script> document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph</p>"); </script> . . </&ody> </html>
*#ample
<-GD.TYH0 html> <html>
8head9 8script9 function m$;unction,< document.get*lement'$Id,2demo2-.innerHTML=2M$ ;irst JavaScript ;unction2> ? 8:script9 8:head9 8bod$9 8h@9M$ %eb age8:h@9 8p id=2demo29" aragraph8:p9 8button t$pe=2button2 onclic/=2m$;unction,-29Tr$ it8:button9 8:bod$9 8:html9
*#ample
<-GD.TYH0 html> <html> <&ody>
8p id=2demo29" aragraph8:p9 8button t$pe=2button2 onclic/=2m$;unction,-29Tr$ it8:button9 8script9 function m$;unction,< document.get*lement'$Id,2demo2-.innerHTML=2M$ ;irst JavaScript ;unction2> ? 8:script9 8:bod$9 8:html9
*#ternal JavaScripts
Scripts can also be placed in e#ternal files. *#ternal files often contain code to be used b$ several different web pages. *#ternal JavaScript files have the file e#tension .3s. To use an e#ternal script, point to the .3s file in the 2src2 attribute of the 8script9 tag(
*#ample
<-GD.TYH0 html> <html> <&ody> <script src)"my4cript.Es"></script> </&ody> </html>
&ou can place the script in the 8head9 or 8bod$9 as $ou li/e. The script will behave as if it was located e#actl$ where $ou put the 8script9 tag in the document.
0/ternal scripts cannot contain <script> tags.
JavaScript Variables
JavaScript variables are 2containers2 for storing information(
*#ample
'ar /)B; 'ar y)>; 'ar I)/Jy;
JavaScript 5ariables
"s with algebra, JavaScript variables can be used to hold values ,#=A- or e#pressions ,C=#D$-. 5ariable can have short names ,li/e # and $- or more descriptive names ,age, sum, totalvolume-.
Karia&le names must &egin with a le(er Karia&le names can also &egin with L and M (&ut we will not use it) Karia&le names are case sensi@'e (y and Y are di6erent 'aria&les) 1oth 3a'a4cript statements and 3a'a4cript 'aria&les are case<sensi@'e.
%hen $ou assign a te#t value to a variable, put double or single .uotes around the value. %hen $ou assign a numeric value to a variable, do not put .uotes around the value. If $ou put .uotes around a numeric value, it will be treated as te#t.
*#ample
'ar pi)N.1O; 'ar name)"3ohn Goe"; 'ar answer)+Yes " am-+;
"fter the declaration, the variable is empt$ ,it has no value-. To assign a value to the variable, use the e.ual sign(
carname)"Kol'o";
However, $ou can also assign a value to the variable when $ou declare it(
'ar carname)"Kol'o";
In the e#ample below we create a variable called carname, assigns the value 25olvo2 to it, and put the value inside the HTML paragraph with id=2demo2(
*#ample
<p id)"demo"></p> 'ar carname)"Kol'o"; document.get0lement1y"d("demo").innerHT !)carname;
"t+s a good programming prac@ce to declare all the 'aria&les you will need% in one place% at the &eginning o# your code.
5alue = undefined
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, li/e user input. 5ariable declared without a value will have the value undefined. The variable carname will have the value undefined after the e#ecution of the following statement(
'ar carname;
JavaScript "rithmetic
"s with algebra, $ou can do arithmetic with JavaScript variables, using operators li/e = and D(
*#ample
y)B; /)yJ=;
JavaScript Statements
JavaScript is a se.uence of statements to be e#ecuted b$ the browser.
JavaScript Statements
JavaScript statements are 2commands2 to the browser. The purpose of the statements is to tell the browser what to do. This JavaScript statement tells the browser to write 2Hello 1oll$2 inside an HTML element with id=2demo2(
document.get0lement1y"d("demo").innerHT !)"Hello Golly";
Semicolon >
Semicolon separates JavaScript statements. Formall$ $ou add a semicolon at the end of each e#ecutable statement. 0sing semicolons also ma/es it possible to write man$ statements on one line.
You might see e/amples without semicolons. 0nding statements with semicolon is op@onal in 3a'a4cript.
JavaScript !ode
JavaScript code ,or 3ust JavaScript- is a se.uence of JavaScript statements.
10
*ach statement is e#ecuted b$ the browser in the se.uence the$ are written. This e#ample will manipulate two HTML elements(
*#ample
document.get0lement1y"d("demo").innerHT !)"Hello Golly"; document.get0lement1y"d("myG"K").innerHT !)"How are youP";
*#ample
#unc@on my2unc@on() 9 document.get0lement1y"d("demo").innerHT !)"Hello Golly"; document.get0lement1y"d("myG"K").innerHT !)"How are youP"; :
%hite Space
JavaScript ignores e#tra spaces. &ou can add white space to $our script to ma/e it more readable. The following lines are e.uivalent(
11
!onditional Statements
5er$ often when $ou write code, $ou want to perform different actions for different decisions. &ou can use conditional statements in $our code to do this. In JavaScript we have the following conditional statements(
if statement < use this statement to e/ecute some code only i# a speciRed condi@on is true if...else statement < use this statement to e/ecute some code i# the condi@on is true and another code i# the condi@on is #alse
12
if...else if....else statement < use this statement to select one o# many &loc*s o# code to &e e/ecuted switch statement < use this statement to select one o# many &loc*s o# code to &e e/ecuted
If Statement
0se the if statement to e#ecute some code onl$ if a specified condition is true. Syntax
i# (condition) 9 code to be executed if condition is true :
Fote that if is written in lowercase letters. 0sing uppercase letters ,I;- will generate a JavaScript errorG
*#ample
Ma/e a 2Hood da$2 greeting if the time if less than IJ(JJ(
i# (@me<=7) 9 /)"Sood day"; :
Fotice that there is no ..else.. in this s$nta#. &ou tell the browser to e#ecute some code onl$ if the specified condition is true.
If...else Statement
0se the if....else statement to e#ecute some code if a condition is true and another code if the condition is not true. Syntax
i# (condition) 9 code to be executed if condition is true :
13
*#ample
If the time is less than IJ(JJ, $ou will get a 2Hood da$2 greeting, otherwise $ou will get a 2Hood evening2 greeting
i# (@me<=7) 9 /)"Sood day"; : else 9 /)"Sood e'ening"; :
*#ample
If the time is less than @J(JJ, $ou will get a 2Hood morning2 greeting, if not, but the
14
time is less than IJ(JJ, $ou will get a 2Hood da$2 greeting, otherwise $ou will get a 2Hood evening2 greeting(
i# (@me<17) 9 /)"Sood morning"; : else i# (@me<=7) 9 /)"Sood day"; : else 9 /)"Sood e'ening"; :
"lert 'o#
"n alert bo# is often used if $ou want to ma/e sure information comes through to the user. %hen an alert bo# pops up, the user will have to clic/ 2)62 to proceed. Syntax
window.alert("sometext");
*#ample
<-GD.TYH0 html> <html> <head> <script> #unc@on my2unc@on() 9 alert("" am an alert &o/-"); :
15
</script> </head> <&ody> <input type)"&u(on" onclic*)"my2unc@on()" 'alue)"4how alert &o/"> </&ody> </html>
!onfirm 'o#
" confirm bo# is often used if $ou want the user to verif$ or accept something. %hen a confirm bo# pops up, the user will have to clic/ either 2)62 or 2!ancel2 to proceed. If the user clic/s 2)62, the bo# returns true. If the user clic/s 2!ancel2, the bo# returns false. Syntax
window.conRrm("sometext");
*#ample
'ar r)conRrm("Hress a &u(on"); i# (r))true) 9 /)"You pressed DT-"; : else 9 /)"You pressed .ancel-"; :
rompt 'o#
" prompt bo# is often used if $ou want the user to input a value before entering a page. %hen a prompt bo# pops up, the user will have to clic/ either 2)62 or 2!ancel2 to proceed after entering an input value. If the user clic/s 2)62 the bo# returns the input value. If the user clic/s 2!ancel2 the bo# returns null.
16
Syntax
window.prompt("sometext"%"defaultvalue");
*#ample
'ar name)prompt("Hlease enter your name"%"Harry Ho(er"); i# (name-)null UU name-)"") 9 /)"Hello " J name J "- How are you todayP"; :
Line 'rea/s
To displa$ line brea/s inside a popup bo#, use a bac/Eslash followed b$ the character n.
*#ample
alert("HelloQnHow are youP");
JavaScript Functions
" function is a bloc/ of code that will be e#ecuted when 2someone2 calls it(
*#ample
<-GD.TYH0 html> <html> <head> <script> #unc@on my2unc@on() 9 alert("Hello ,orld-"); : </script> </head> <&ody> <&u(on onclic*)"my2unc@on()">Try it</&u(on> </&ody> </html>
17
The code inside the function will be e#ecuted when 2someone2 calls the function. The function can be called directl$ when an event occurs ,li/e when a user clic/s a button-, and it can be called from 2an$where2 b$ JavaScript code.
3a'a4cript is case sensi@'e. The #unc@on *eyword must &e wri(en in lowercase le(ers% and the #unc@on must &e called with the same capitals as used in the #unc@on name.
The variables and the arguments must be in the e#pected order. The first variable is given the value of the first passed argument etc.
*#ample
<&u(on onclic*)"my2unc@on(+Harry Ho(er+%+,iIard+)">Try it</&u(on> <script> #unc@on my2unc@on(name%Eo&)
18
The function above will alert 2%elcome Harr$ otter, the %iCard2 when the button is clic/ed. The function is fle#ible, $ou can call the function using different arguments, and different welcome messages will be given(
*#ample
<&u(on onclic*)"my2unc@on(+Harry Ho(er+%+,iIard+)">Try it</&u(on> <&u(on onclic*)"my2unc@on(+1o&+%+1uilder+)">Try it</&u(on>
The e#ample above will alert 2%elcome Harr$ otter, the %iCard2 or 2%elcome 'ob, the 'uilder2 depending on which button is clic/ed.
The function above will return the value A. Fote( It is not the entire JavaScript that will stop e#ecuting, onl$ the function. JavaScript will continue e#ecuting code, where the functionEcall was made from. The functionEcall will be replaced with the returnvalue(
'ar myKar)my2unc@on();
The variable m$5ar holds the value A, which is what the function 2m$;unction,-2
19
returns. &ou can also use the returnvalue without storing it as a variable(
document.get0lement1y"d("demo").innerHT !)my2unc@on();
The innerHTML of the 2demo2 element will be A, which is what the function 2m$;unction,-2 returns. &ou can ma/e a returnvalue based on arguments passed into the function(
*#ample
!alculate the product of two numbers, and return the result(
#unc@on my2unc@on(a%&) 9 return aV&; : document.get0lement1y"d("demo").innerHT !)my2unc@on(O%N);
The return statement is also used when $ou simpl$ want to e#it a function. The return value is optional(
#unc@on my2unc@on(a%&) 9 i# (a>&) 9 return; : /)aJ& :
The function above will e#it the function if a9b, and will not calculate the sum of a and b.
20
variables are onl$ recogniCed b$ the function in which the$ are declared. Local variables are deleted as soon as the function is completed.
will declare the variable carname as a global variable , even if it is e#ecuted inside a function.
*#ample
Mouse Over Me
21
Click Me
+eacting to *vents
" JavaScript can be e#ecuted when an event occurs, li/e when a user clic/s on an HTML element. To e#ecute code when a user clic/s on an element, add JavaScript code to an HTML event attribute(
onclic*)JavaScript
,hen a user clic*s the mouse ,hen a we& page has loaded ,hen an image has &een loaded ,hen the mouse mo'es o'er an element ,hen an input Reld is changed ,hen an HT ! #orm is su&mi(ed ,hen a user stro*es a *ey
In this e#ample, the content of the 8h@9 element is changed when a user clic/s on it(
*#ample
<-GD.TYH0 html> <html> <&ody> <h1 onclic*)"this.innerHT !)+Doops-+">.lic* on this te/t-</h1> </&ody> </html>
*#ample
<-GD.TYH0 html> <html> <head> <script> #unc@on changete/t(id)
22
9 id.innerHT !)"Doops-"; : </script> </head> <&ody> <h1 onclic*)"changete/t(this)">.lic* on this te/t-</h1> </&ody> </html>
*#ample
"ssign an onclic/ event to a button element(
<&u(on onclic*)"displayGate()">Try it</&u(on>
In the e#ample above, a function named displa$1ate will be e#ecuted when the button is clic/ed.
*#ample
"ssign an onclic/ event to a button element(
<script> document.get0lement1y"d("my1tn").onclic*)#unc@on()9displayGate():; </script>
In the e#ample above, a function named displa$1ate is assigned to an HTML element with the id=m$'utn2. The function will be e#ecuted when the button is clic/ed.
23
and load the proper version of the web page based on the information. The onload and onunload events can be used to deal with coo/ies.
*#ample
<&ody onload)"chec*.oo*ies()">
*#ample
<input type)"te/t" id)"#name" onchange)"upper.ase()">
*#ample
" simple onmouseoverEonmouseout e#ample(
Mouse Over Me
24
*#ample
" simple onmousedownEonmouseup e#ample(
Click Me
*#ample
'ar mycars ) new ;rray(); mycarsW7X ) "4aa&"; mycarsW1X ) "Kol'o"; mycarsW=X ) "1 ,";
%hat is an "rra$7
"n arra$ is a special variable, which can hold more than one value at a time. If $ou have a list of items ,a list of car names, for e#ample-, storing the cars in single variables could loo/ li/e this(
'ar car1)"4aa&"; 'ar car=)"Kol'o"; 'ar carN)"1 ,";
However, what if $ou want to loop through the cars and find a specific one7 "nd what if $ou had not 4 cars, but 4JJ7
25
The solution is an arra$G "n arra$ can hold man$ values under a single name, and $ou can access the values b$ referring to an inde# number.
!reate an "rra$
"n arra$ can be created in three wa$s. The following code creates an "rra$ ob3ect called m$!ars( @( +egular(
'ar my.ars)new ;rray(); my.arsW7X)"4aa&"; my.arsW1X)"Kol'o"; my.arsW=X)"1 ,";
I( !ondensed(
'ar my.ars)new ;rray("4aa&"%"Kol'o"%"1 ,");
4( Literal(
'ar my.ars)W"4aa&"%"Kol'o"%"1 ,"X;
"ccess an "rra$
&ou refer to an element in an arra$ b$ referring to the inde# number. This statement access the value of the first element in m$!ars(
'ar name)my.arsW7X;
W7X is the Rrst element in an array. W1X is the second . . . . . (inde/es start with 7)
26
JavaScript Strings
" string simpl$ stores a series of characters li/e 2John 1oe2. " string can be an$ te#t inside .uotes. &ou can use simple or double .uotes(
*#ample
'ar carname)"Kol'o Z.>7"; 'ar carname)+Kol'o Z.>7+;
&ou can access each character in a string with its position ,inde#-(
*#ample
'ar character)carnameWCX;
String inde#es are CeroEbased, which means the first character is KJL, the second is K@L, and so on. &ou can use .uotes inside a string, as long as the$ don't match the .uotes surrounding the string(
*#ample
'ar answer)""t+s alright"; 'ar answer)"He is called +3ohnny+"; 'ar answer)+He is called "3ohnny"+;
)r $ou can put .uotes inside a string b$ using the M escape character(
*#ample
'ar answer)+"tQ+s alright+; 'ar answer)"He is called Q"3ohnnyQ"";
String Length
The length of a string ,a string ob3ect- is found in the built in propert$ length(
28
*#ample
'ar t/t)"Hello ,orld-"; document.write(t/t.length); 'ar t/t)";1.G02SH"3T! 8DH[\4TYK,ZY]"; document.write(t/t.length);
*#ample
'ar str)"Hello world% welcome to the uni'erse."; 'ar n)str.inde/D#("welcome");
The method returns E@ if the specified te#t is not found. The lastInde#)f,- method starts searching at the end of the string instead of at the beginning.
Matching !ontent
The match,- method can be used to search for a matching content in a string(
*#ample
'ar str)"Hello world-"; document.write(str.match("world") J "<&r>"); document.write(str.match(",orld") J "<&r>"); document.write(str.match("world-"));
+eplacing !ontent
The replace,- method replaces a specified value with another value in a string.
*#ample
str)"Hlease 'isit icroso$-"
29
*#ample
'ar t/t)"Hello ,orld-"; // 4tring 'ar t/t1)t/t.toYpper.ase(); // t/t1 is t/t con'erted to upper 'ar t/t=)t/t.to!ower.ase(); // t/t= is t/t con'erted to lower
*#ample
t/t)"a%&%c%d%e" // 4tring t/t.split("%"); // 4plit on commas t/t.split(" "); // 4plit on spaces t/t.split("^"); // 4plit on pipe
Special !haracters
The bac/slash ,M- can be used to insert apostrophes, new lines, .uotes, and other special characters into a string. Loo/ at the following JavaScript code(
'ar t/t)",e are the so<called "Ki*ings" #rom the north."; document.write(t/t);
In JavaScript, a string is started and stopped with either single or double .uotes. This means that the string above will be chopped to( %e are the soEcalled To solve this problem, $ou must place a bac/slash ,M- before each double .uote in 25i/ing2. This turns each double .uote into a string literal(
'ar t/t)",e are the so<called Q"Ki*ingsQ" #rom the north."; document.write(t/t);
JavaScript will now output the proper te#t string( %e are the soEcalled 25i/ings2 from the north.
30
The table below lists other special characters that can be added to a te#t string with the bac/slash sign(
Code Outputs Q+ Q" QQ Qn Qr Qt Q& Q# single Fuote dou&le Fuote &ac*slash new line carriage return ta& &ac*space #orm #eed
Methods(
char;t() char.ode;t() concat() #rom.har.ode() inde/D#() last"nde/D#() match() replace() search() slice() split() su&str()
31
32
Most parameters above are optional. Fot specif$ing, causes J to be passed in. )nce a 1ate ob3ect is created, a number of methods allow $ou to operate on it. Most methods allow $ou to get and set the $ear, month, da$, hour, minute, second, and milliseconds of the ob3ect, using either local time or 0T! ,universal, or HMT- time. "ll dates are calculated in milliseconds from J@ Januar$, @NOJ JJ(JJ(JJ 0niversal Time ,0T!- with a da$ containing PB,QJJ,JJJ milliseconds. Some e#amples of initiating a date(
'ar today ) new Gate() 'ar d1 ) new Gate("Dcto&er 1N% 1ACB 11_1N_77") 'ar d= ) new Gate(CA%B%=O) 'ar dN ) new Gate(CA%B%=O%11%NN%7)
Set 1ates
%e can easil$ manipulate the date b$ using the methods available for the 1ate ob3ect. In the e#ample below we set a 1ate ob3ect to a specific date ,@Qth Januar$ IJ@J-(
'ar myGate)new Gate(); myGate.set2ullYear(=717%7%1O);
"nd in the following e#ample we set a 1ate ob3ect to be A da$s into the future(
'ar myGate)new Gate(); myGate.setGate(myGate.getGate()JB);
Fote( If adding five da$s to a date shifts the month or $ear, the changes are handled automaticall$ b$ the 1ate ob3ect itselfG
33
9 alert("Today is &e#ore 1Oth 3anuary =177"); : else 9 alert("Today is a$er 1Oth 3anuary =177"); :
%hat is +eg*#p7
+eg*#p, is short for regular e#pression. " regular e#pression is an ob3ect that describes a pattern of characters. %hen $ou search in a te#t, $ou can use a pattern to describe what $ou are searching for. " simple pattern can be one single character. " more complicated pattern can consist of more characters, and can be used for parsing, format chec/ing, substitution and more. +egular e#pressions are used to perform powerful patternEmatching and 2searchEandE replace2 functions on te#t.
S$nta#
'ar pa()new \eg0/p(pa(ern%modiRers); or more simply_ 'ar pa()/pa(ern/modiRers;
pa(ern speciRes the pa(ern o# an e/pression modiRers speci#y i# a search should &e glo&al% case<sensi@'e% etc.
+eg*#p Modifiers
Modifiers are used to perform caseEinsensitive and global searches. The i modifier is used to perform caseEinsensitive matching. The g modifier is used to perform a global match ,find all matches rather than stopping after the first match-.
34
*#ample @
1o a caseEinsensitive search for 2w4schools2 in a string(
'ar str)"Kisit \estar(echnologies "; 'ar pa(1)/ \estar(echnologies /i;
The mar/ed te#t below shows where the e#pression gets a match(
Kisit \estar(echnologies
*#ample I
1o a global search for 2is2(
'ar str)""s this all there isP"; 'ar pa(1)/is/g;
The mar/ed te#t below shows where the e#pression gets a match(
"s this all there isP
*#ample 4
1o a global, caseEinsensitive search for 2is2(
'ar str)""s this all there isP"; 'ar pa(1)/is/gi;
The mar/ed te#t below shows where the e#pression gets a match(
"s this all there isP
test,The test,- method searches a string for a specified value, and returns true or false, depending on the result. The following e#ample searches a string for the character 2e2(
*#ample
35
Since there is an 2e2 in the string, the output of the code above will be(
true
e#ec,The e#ec,- method searches a string for a specified value, and returns the te#t of the found value. If no match is found, it returns null. The following e#ample searches a string for the character 2e2(
*#ample @
'ar pa(1)new \eg0/p("e"); document.write(pa(1.e/ec("The &est things in li#e are #ree"));
Since there is an 2e2 in the string, the output of the code above will be(
e
36