Using Javascript on Web pages

berserkarithmeticInternet and Web Development

Dec 14, 2013 (3 years and 6 months ago)

69 views

3.12.2008Jaana Holvikivi2
Javascripton HTML pages
Client-side JavaScript statements on an HTML page can
respond to user events such as:
•Mouse clicks, form input, and
•Page navigation,
•Help in filling forms, and checking input,
•Pageupdatingand customizationon user
side.
JavaScript locationon HTML pages:
•Scriptwithinan <script> element(tag) in the head
orbody-section.
•Referenceto externalJavaScript sourcefile
•JavaScript commandsas a valueto an HTML
attribute, suchas eventhandlerin forms
3.12.2008Jaana Holvikivi3
HTML –page: parts
HTML
STYLEHEAD
BODY
Javascript
SCRIPT
<tagJavascript>
<tagstyle>
STYLEsheet
Javascriptfile
3.12.2008Jaana Holvikivi4
Javascripton an HTML page1
<html>
<head>
<title>Javascriptbasics</title>
</head>
<body>
<p>
<form>
<input value=”Press" type="button" onClick="
alert('HELLO
')">
</form> </p>
<p>
<scriptlanguage="JavaScript">
document.write(”Lastupdated:");
document.write(document.lastModified);
</script>
</p>
</body>
</html>
3.12.2008Jaana Holvikivi5
Javascripton an HTML page2
<html>
<head>
<title>Javascriptbasics</title>
</head>
<body>
<p>
<a href="http://www.metropolia.fi"
onMouseOver="
window.status=' clickhere'; returntrue"
onMouseOut="window.status=' ';
">
Clickon the link</a>
</p>
</body>
</html>
3.12.2008Jaana Holvikivi6
<html>
<head>
<title>Javascriptand DOM</title>
<scripttype="text/javascript" >
vardate=newDate();
varhour=date.getHours();
if(hour>=22 || hour<=5)
document.write("Youshouldgoto sleep");
else
document.write("Hello, world!");
</script>
</head>
<body>
</body>
</html>
Javascripton an HTML page3
3.12.2008Jaana Holvikivi7
Externalcodefile
vardate=newDate();
varhour=date.getHours();
if(hour>=22 || hour<=5)
document.write("Youshouldgoto sleep");
else
document.write("Hello, world!");
jsdom.js:
<html>
<head>
<title>Javascriptand DOM</title>
<scripttype="text/javascript" src="
jsdom.js
"></script>
</head>
<body>
I loveyou!
</body>
</html>
Hello, world! I loveyou!
3.12.2008Jaana Holvikivi8
Javascriptuse
￿
Javascriptis alwaysdownloadedfromthe serverto the
client
￿
Eitheras a filereference
￿
Orembeddedin HTML
￿
Javascriptis executedon clientside.
￿
Lessloadon server
￿
Example: checkson forminput (numericfields,
dates, requiredfields)
￿
Javascriptunderstandsthe structureof the HTML page
(document); DOM
3.12.2008Jaana Holvikivi9
Programminglanguagefeatures
￿
Data types
￿
Constants
￿
Variables
￿
Expressions
￿
Operators
￿
Statements
￿
Functions
￿
Methods
￿
Events
￿
Objects
￿
Errormessages
3.12.2008Jaana Holvikivi10
Variablesand values
var
i
=0,
result
= 0; // = assingmentstatement
for (
i
= 0;
i
<= 10; i++) {
result
+= i;
document.write(
i
+ ": " +
result
+ "<br/>");
}
vari = 0declaresa variableand setsthe valueto 0
(assignmentstatement)
;statementterminator
Vara, A;
JavaScript is case sensitive
A declaredvariableis local
Reservedwordscannotbeusedas variablenames
3.12.2008Jaana Holvikivi11
Data typesin JavaScript
￿
Numbers0.44
￿
Strings
document.write
(”greeting"+mj
);
in quotations( ' or")
<input value="Paina" type="button"
onClick="alert(
'HELLO'
)">
￿
Null”empty"
￿
Stringliterals
alert("Iam an alertbox!!
\n\t
Man!");
whenHTML is notin use, addsa new lineand a tab
￿
Booleanvalues
true, false
3.12.2008Jaana Holvikivi12
Characterstrings
￿
Methodsto operateon strings;
mj= "kissa"; other="la"
mj.lengthvalue5
mj.toUpperCase()KISSA
mj.charAt(0)k
mj.substring(0,3)kiss
concatenation:
mj+ otherkissala
3.12.2008Jaana Holvikivi13
Arrays
blocks= [8, 4, 7, 6, 15]
blocks.lengthgetsvalue5
blocks[0]containsnumber8
novel= blocks.sort()
Containsarray[4,6,7,8,15]
Arrayscancontaindifferenttypesof data
document.images[0].src = pics[frame].src
3.12.2008Jaana Holvikivi14
Expressions
i <= 10 conditionalexpression: trueorfalse
Stringoperation:
”resultis" + summa
Statement:
timerID= setTimeout(’alternate()', 800);
;statementterminator
3.12.2008Jaana Holvikivi15
Operators
AssignmentOperators
+addition
x+=yis the sameas x=x+y
x++sameas x=x+1
-Subtraction
* Multiplication
/Division
%remainder
ComparisonOperators, trueorfalse
==is equalto
!=is notequal5!=8 returnstrue
<lessthan
>Greaterthan
>=Greaterthanorequal
<=lessthanorequal
3.12.2008Jaana Holvikivi16
Operators
LogicalOperators
&&AND
||OR
!NOT
1 0
0 1
NOT
1
1
1
1
1
0
1
0
1
0 00
OR
1
1
1
0
1
0
0
0
1
0 00
AND
RESULT
3.12.2008Jaana Holvikivi17
Conditionalstatements
￿
if
( !Math.random) // hereyouchecka standardfunction
{
document.write('<pre> --weathercalledoffdueto rain--
</pre>');}
elseif
( Math.floor((Math.random()*2)) == 0 )
{
document.write("<b>It'sjust awful. </b>");}
else
{
document.write("<em>Howwonderfulitis!</em>");
}
3.12.2008Jaana Holvikivi18
Loops: for
￿
for (i = 0; i <= 10; i++)
￿
{
result+= i;
document.write(i+ ": " + result+ "<br/>"); }
document.write("<p></p>");
￿
Incrementi=i+1 or
i++
3.12.2008Jaana Holvikivi19
Loops: while
￿
varx = 1;
varresult= 0;
while( x <= 10 ) { // the loopis repeateduntilx>10
result+= x;
x++; }
alert("The resultis " + result+ " and x is " + x );
3.12.2008Jaana Holvikivi20
Functions
Userdefined
Predefined
alert
prompt
parsIntconvertsvariableinto an integer
parseFloatconvertsvariableinto a number
Math.sqrtsquare root
Math.floorroundingto the lowerinteger
Math.roundrounding
3.12.2008Jaana Holvikivi21
Functions: userdefined
<html>
<head>
<scripttype="text/javascript">
functiondisp_alert()
{
alert("Iam an alertbox!!")
}
</script>
</head>
<body>
<form>
<input type="button" onclick="disp_alert()" value="Display
alertbox">
</form>
</body>
</html>
3.12.2008Jaana Holvikivi22
Methods
￿close()
￿getElementById()
￿getElementsByName()
￿getElementsByTagName()
￿open()
￿document.write()
Closes an output stream opened with the
document.open() method, and displays the
collected data
Returns a reference to the first object with
the specified id
Returns a collection of objects with the
specified name
Returns a collection of objects with the
specified tagname
Opens a stream to collect the output from
any document.write() method
Writes HTML expressions or JavaScript code
to a document
3.12.2008Jaana Holvikivi23
Eventhandlers
onabortLoading of an image is interrupted
onblurAn element loses focus
onchangeThe user changes the content of a field
onclickMouse clicks an object
ondblclickMouse double-clicks an object
onerrorAn error occurs when loading a document or an image
onfocusAn element gets focus
onkeypressA keyboard key is pressed or held down
onloadA page or an image is finished loading
onmousedownA mouse button is pressed
onmouseoutThe mouse is moved off an element
onmouseoverThe mouse is moved over an element
onresetThe reset button is clicked
onresizeA window or frame is resized
onselectText is selected
onsubmitThe submit button is clicked
onunloadThe user exits the pagesetTimeout(), clearTimeout()timeris activated
3.12.2008Jaana Holvikivi24
Event: onload() & getElementById
functionprocess()
{varstring;
string="<ul>"
+ "<li>Black</li>"
+ "<li>Red</li>"
+ "<li>Blue</li>"
+ "</ul>";
varmyDiv=document.getElementById("
Hook
");
myDiv.innerHTML=string;
}
ESIMERKIKSI: <div id="hook">storiesand <h2>headings</h2></div>
Hookhasan
innerHTML
-property
storiesand <h2>headings</h2>
Hookhasan
outerHTML
-property
<div id="hook">storiesand <h2>headings</h2></div>
3.12.2008Jaana Holvikivi25
..onload()
<html>
<head>
<title>AJAXFoundations: javascriptand DOM</title>
<scripttype="text/javascript" src="
morejsdom.js
"></script>
</head>
<body
onload="process()"
>
Hello! Hereis a coollistof colorsfor you:
<br/>
<div
id="Hook"
/>
</body>
</html>
3.12.2008Jaana Holvikivi26
DOM DocumentObjectModel
￿
document.form1.text1.value
<formname="form1">
<input type="text" name="text1">
</form>
￿
parent.location= word1 + word2 + ".html"
3.12.2008Jaana Holvikivi27
Javascriptand documentstructure
3.12.2008Jaana Holvikivi28
HTML document
<html>
<head>
<title>Thisis a testpage</title>
</head>
<bodyid=”trunk">
<p>Atableis presented</p>
<table>
<tr>
<td> item</td>
<td> cell</td>
</tr>
<tr>
<td> <imgsrc=”picture.gif"/> </td>
<td> 1 </td>
</tr>
</table>
</body>
</html>
3.12.2008Jaana Holvikivi29
Document tree
Document
Root: html
Element: Head
Element: Body
Element: tr
Element: title
Element: td
Element: p
Element: table
Text: "test page"
Text: “A table"
Element: img
Attribute: src
3.12.2008Jaana Holvikivi30
DocumentObjectModel(DOM)
￿
Used by many programming languages
(php, java, c#, c++, Javascript…)
￿
And understood by browsers (Mozilla, IE, Opera, Safari)
￿
XML -document is a collection of nodes that make a
hierarchical tree structure
￿
The hierarchy is used in navigating the tree to locate
information
￿
Inefficient use of memory: the tree structure is created in
the memory
￿
DOM enables adding, moving, deleting and changing of
nodes
3.12.2008Jaana Holvikivi31
Document tree
Ancestor
Parent / ancestor
Sibling
Node
Child /descendant
Attribute
Descendant
Namespace
3.12.2008Jaana Holvikivi32
Processingof the tree
￿
Startwiththe rootnode( document-object)
￿
Elementproperties
￿
firstChild
￿
lastChild
￿
nextSibling
￿
parentNode
￿
Methodsto navigatethe tree
￿
getElementByID(id)
￿
getElementsByName(name)
￿
getElementsByTagName(name)
￿
getAttribute(name)
3.12.2008Jaana Holvikivi33
Example
<form>
<imgid="faceIm" src="happy.gif" />
<input type="button" value="Iloinen"
onClick="document.getElementById('faceIm').src=
'happy.gif';
"/>
<input type="button" value="Murheissani"
onClick="document.getElementById('faceIm').src=
'sad.gif';
"/>
3.12.2008Jaana Holvikivi34
Javascriptas a programming language
￿
Object-oriented:
￿
Instead of writing procedural programs, write class
libraries to encapsulate behaviors
￿
DOM is not a collection of dumb elements but a
hierarchy of types
￿
Styles are properties of objects
￿
Complete OO code with error handling, instance
methods, static methods and type hierarchies
￿
Versatile use of functions
￿
A large number of object-oriented libraries
￿
Used to create flexible user interfaces