Transcript Lecture 3

Lecture 3: Dynamic Web Pages –
Introduction to JavaScript
Instructor: Dr. M. Anwar Hossain
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 1
Learning Outcomes
 In this chapter, you will learn about:
◦ DOM Objects.
◦ Graphics and animation.
◦ Understand the differences between methods of posting
form data.
◦ Understand how to program using different form event
handlers.
◦ Understand how to use JavaScript to read the values
from various form objects.
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 2
Review
• Client-side programming overview
• Basics of JavaScript programming
• Variables, arrays and objects
• Operators and maths
• Sequence, repetition and selection
• Functions
• Events
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 3
Today …
• Document/JavaScript Object Model (DOM)
• Accessing elements
• Forms
• Graphics and Animation
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 4
The Document Object Model (DOM)
• A specification
• An Application Programming Interface (API)
• Is used so programs can interact with web pages
• Language and platform neutral (whether Javascript or
VBScript for example)
• Some problems with variations in browsers, always
check
• DOM sometimes known as Dynamic HTML Object
Model within Microsoft specific contexts
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 5
The Document Object Model
• The main idea is to let any script access any part of
a web document, simply.
• This idea is extended to controlling browser related
features.
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 6
The Document Object Model
• Root level of the JavaScript DOM is the window object
• Window objects have properties such as status line
• The next level up is the document object…which is the
loaded HTML page
• Document objects have properties such as background
colour
• Each HTML element (e.g. links or forms) is a property
of the document object.
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 7
Javascript Document Object Model
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 8
Document properties
Property
Description
anchors[]
applets[]
body
cookie
domain
An array referring to document anchors
An array referring to document applets
The element that contains the content of document
The current document cookie string
The domain name of the server where
the current document is located ...
forms[]
images[]
links[]
referrer
title
URL
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 9
• The first image on a web page can be represented as the
property document.images[0]
• A web form also has its properties accessible in the
object tree
• You can find any property by tracing it through the tree:
document.forms[0].elements[0]
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 10
window
|
+-------parent, frames, self, top
|
+-------location
|
+-------history
|
+-------document
|
+--forms
|
|
|
elements (text fields, textarea, checkbox, password
|
radio, select, button, submit, reset)
+--links
|
+--anchors
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 11
Can also access elements by name:
<html>
<body>
<h1 id="header">Test theDOM</h1>
<script type="text/javascript">
document.getElementById('header').style.color="red"
</script></body>
</html>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 12
Using the Document Object Model
Using both JavaScript and VBScript various elements within a page can be
changed. One of the simplest examples of accessing the current HTML page is:
document.write(“Hello, world!”)
Which writes new text to the current document, this can also contain HTML:
document.write(“<H1>Hello, world!</H1>”)
Note: the syntax is the same for both languages with the exception of the
semicolon needed in JavaScript! The API produces the same ‘interface’ for both
languages.
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 13
DOM Example 1
<HTML>
<HEAD>
<TITLE>Test DOM</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<FONT FACE="Verdana, Arial, Helvetica" SIZE=2>
<script language="javascript">
<!-var a=document.body.bgColor;
document.write(a);
document.body.bgColor='#109032';
document.fgColor='#ffffff';
-->
</script>
</BODY></HTML>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 14
DOM
Example 2
<HTML><HEAD><TITLE>Got Flash?</TITLE>
<SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
hasFlash = false
for (i=0; i<navigator.plugins.length; i++) {
if (navigator.plugins[i].name.indexOf("Flash") >= 0) {
hasFlash = true
}
}
</SCRIPT>
</HEAD><BODY BGCOLOR=WHITE><H2>
<SCRIPT LANGUAGE=JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
if (hasFlash) {
document.write("You have Flash, you lucky person, you!")
}
else {
document.write("Sorry, you don't have Flash.")
}
</SCRIPT>
</H2></BODY></HTML>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 15
Accessing HTML Elements
Elements within a document can be accessed by name:
<HTML>
<HEAD>
<TITLE>Test DOM</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<FONT FACE="Verdana, Arial, Helvetica" SIZE=2>
<div id="myobject" name="myobject" style="position:absolute;top:120px;
left:150px;width:390px;height:190px;background:#aaffaa">
This is a test
</div>
<script language=“JavaScript">
<!-document.all.myobject.style.backgroundColor="Red“;
-->
</script>
</BODY>
</HTML>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 16
Accessing Form Elements
The normal HTML syntax is usually along the lines of:
<form name=“logon" action="html_form_action.php"
method="get">
Username:
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
• name (what the form is identifed by)
• action (where the form data sent to for processing)
• method (how the data is transported)
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 17
Accessing Form Elements
You can access and manipulate form related information
using the JavaScript DOM
• document.forms[number].elements[number]
• document.forms[number].username
• document.logon.username
If you want the actual value passed back use:
• document.logon.username.value
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 18
DOM Example 3
<HTML>
<HEAD>
<script language="Javascript">
<!-function hello(passed) {
document.write("Hello, "+document.logon.user.value);
document.write("<br>are you *sure* you're called, "+passed);
}
//-->
</script>
</HEAD>
<BODY>
<form name="logon" onsubmit="hello(document.forms[0].elements[0].value)">
Username:
<input type="text" name="user">
<input type="submit" value="Submit">
</form>
</HTML>
</BODY>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 19
Graphics and animation
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 20
The basic idea …
<!-- This div is the element we are animating -->
<div id="urgent"><h1>Red Alert!</h1>The Web server is under attack!</div>
<!-- This is the animation script for the element -->
<script>
var e = document.getElementById("urgent");
// Get the element object
var colors = ["white", "yellow", "orange", "red"] // Colors to cycle through
var nextColor = 0;
// Position in the cycle
// Evaluate the following expression every 500 milliseconds.
// This animates the background color of the DIV element.
setInterval("e.style.backgroundColor=colors[nextColor++%colors.length];", 500);
</script>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 21
The HTML image tag
A static image can be placed in HTML using the image tag
<img src="url">
If it doesn’t load properly there’s the text alternative
<img src="boat.gif" alt="Big Boat">
You can control features of the image such as the size
<img src="/images/hackanm.gif“ width="20"
height="20">
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 22
• The Image Object
– Represents images created using <img> tag
– Each <img> tag in an HTML document is
represented in the DOM images[] array by an Image
object
– Use with JavaScript to change images based on user
selection
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 23
Image object properties
border, complete, height, hspace, lowsrc, name
src, vspace, width
Image object events
OnLoad, OnAbort, OnError
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 24
• The Image Object
– SRC property
• Allows JavaScript to change an image dynamically
• More efficient than loading a new document each
time a new image is displayed
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 25
 Animation
–Simple
with the Image Object
animation
Created
by a sequence of images changed automatically
Enabled
by combining Image object SRC attribute with
setTimeout() or setInterval() methods
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 26
 Animation
–True
with the Image Object
animation
Requires
a different graphic, or frame, for each movement that a
character or object makes
Frames
can be automatically cycled using JavaScript
–Ensure
each frame is consistent in size and position
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 27
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 28
Runner script
<HTML>
<HEAD>
<TITLE>Runner 1</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
<!-var runner = new Array(6);
var curRunner = 0;
var startRunning;
runner[0] = “runner0.jpg”
runner[1] = “runner1.jpg”
runner[2] = “runner2.jpg” ...
function marathon() {
if (curRunner == 5) curRunner = 0;
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 29
Runner script
else
++curRunner;
document.animation.src = runner[curRunner];
}
-->
<SCRIPT></HEAD>
<BODY>
<P><IMG SRC = “runner0.jpg” NAME = “animation”></P>
<FORM>
<INPUT TYPE=“button” NAME=“run” VALUE=“ Run ”
onClick=“startRunning=setInterval(‘marathon()’,100);”>
<INPUT TYPE=“button” NAME=“stop” VALUE=“ stop ”
onClick=“clearInterval(startRunning);”>
</FORM></BODY></HTML>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 30
• Image Caching
Allows JavaScript to store and retrieve images from memory rather than
downloading image each time it is needed (erratic!)
– Three steps
• Create a new object using the Image() constructor
• Assign graphic file to SRC property of new Image
object
• Assign SRC property of new Image object to SRC
property of an <img> tag
– To ensure all images are cached prior to
commencing animation:
• Use onLoad event handler of the Image object
• Cache with function in <head>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 31
Runner script with caching
<HTML><HEAD><TITLE>Runner 2</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
<!-var runner = new Array(6);
var curRunner = 0;
var startRunning;
for(var i=0; i < 6; ++i) {
runner[i] = new Image();
runner[i].src = “runner”+i+”.jpg”;
}
function marathon() {
if (curRunner == 5) curRunner = 0;
else ++curRunner;
document.animation.src = runner[curRunner].src;
}
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 32
Runner script with caching
-->
</SCRIPT></HEAD><BODY>
<P><IMG SRC=“runner1.jpg” NAME=“animation”></P>
<FORM>
<INPUT TYPE=“button” NAME=“run” VALUE=“ Run ”
onClick=“startRunning=setInterval(‘marathon(),100);”>
<INPUT TYPE=“button” NAME=“stop” VALUE=“ Stop ”
onClick=“clearInterval(startRunning);”>
</FORM>
</BODY>
</HTML>
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 33
Image Animation (another way)
• Now suppose we have the tag
<IMG NAME=img>
in the <BODY>. The following recursive method
animates the cached images:
var n = 0;
function animate() {
document.img.src = images[n].src;
n = (n + 1) % images.length;
id = setTimeout("animate()", 250);
}
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 34
Dynamic HTML (DHTML)
• Introduced in the 4.0 series of browsers
• Is a combination of HTML, CSS and Javascript
• Variations in how each browser implements it
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 35
<HTML><HEAD>
<script language="javascript">
function onMove() {
ex=event.x;
ey=event.y;
gr.left=ex;
gr.top=ey;
}
function setup() {
window.document.onmousemove = onMove();
}
</script>
</HEAD><BODY>
<DIV ID="test2" STYLE="position: absolute; top:110; left:140;">
Some text...
</DIV>
<DIV ID="test" STYLE="position:absolute; top: 100; left: 100;">
<IMG SRC="arrow_up.gif" border="0">
</DIV>
<script language="javascript" >
gr=document.all.test.style;
window.onload = setup();
</script>
</BODY></HTML>
29/03/2016
Modified from Moseley’s slides
Web Applications Development. Lecture 3
DHTML 1
Follow mouse!
Slide 36
36
Course work 1:
• An animation incorporating static and dynamic images
• Unique to you
Hints and Tips:
• It should be a combination of HTML, CSS and JavaScript–DHTML
• Keep any functions in the <head>
• Comment it well
• Structure it well
• I’ll try it in at least a couple of browsers (IE 6 and Firefox)
• Keep it user friendly
• Keep it easy to use (it should be all in 1 folder)
• Be creative
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 37
What we did:
• JavaScript DOM
• Forms
• Animation
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 38
What you still need to cover:
• Cookies (http://www.webreference.com/js/column8)
• String manipulation
(http://www.w3schools.com/js/js_string.asp)
• Objects
(http://www.javascriptkit.com/javatutors/object.shtml)
Next:
• XML
Modified from Moseley’s slides
Web Applications Development. Lecture 3
Slide 39