CICS 515 a Internet Programming Week 3 Mike Feeley 1 JavaScript - - PowerPoint PPT Presentation

cics 515 a internet programming week 3 mike feeley
SMART_READER_LITE
LIVE PREVIEW

CICS 515 a Internet Programming Week 3 Mike Feeley 1 JavaScript - - PowerPoint PPT Presentation

CICS 515 a Internet Programming Week 3 Mike Feeley 1 JavaScript 2 JavaScript is not Java client-side scripting language program that runs in browser at client two ways to include it in HTML document embedded blah.html:


slide-1
SLIDE 1

CICS 515 a Internet Programming Week 3 Mike Feeley JavaScript

1 2

slide-2
SLIDE 2

JavaScript

is not Java client-side scripting language

  • program that runs in browser at client

two ways to include it in HTML document

  • embedded
  • in separate file

<body> <script type="text/javascript"> document.write ("Hello from embedded JavaScript."); </script> </body> <head> <script language="JavaScript" src="blah.js"></script> </head> document.write ("Hello from separate file JavaScript.<br>");

blah.html: blah.html: blah.js:

JavaScript language constructs

variables, objects and arrays functions conditionals loops exceptions Document Object Model (DOM) events

3 4

slide-3
SLIDE 3

Variables in JavaScript

dynamically typed

  • type determined at runtime when value assigned
  • any variable can store any value (of any type)

types

  • primitive types
  • Number, String, Boolean, Undefined, Null (wrapper classes have same name)
  • stored by value, like Java
  • object references

declaration

  • no static types, so declare with var

scope and lifetime

globals

declared outside of any function lifetime of document

locals

declared with var inside of a function lifetime of function invocation

instance variables assigned this. inside of a method

lifetime of object

class variables

assigned in prototype declaration lifetime of document

Dynamically typed objects

fundamentally, an object is

  • a collection of named properties
  • referenced by a variable
  • no class declaration --- classes are static types, Javascript has dynamic types

creating an object

  • new creates a new object reference
  • add properties to object by assigning them values
  • or using an initializer
  • you can add new properties to any object at any time

aStudent = new Object (); aStudent.sid = 10; aStudent.name = 'First Student'; document.myNewProperty = 48; aStudent = { sid: 10, name: 'First Student' };

5 6

slide-4
SLIDE 4

First-class functions

  • ne type of object property is a function
  • first-class means that functions are also data members
  • they can be assigned or re-assigned at runtime and/or passed as arguments to functions etc.

declaring a function

  • assign a function implementation to an object property name
  • assigned or re-assigned dynamically, at runtime

writing a function

  • use this. prefix to refer to object’s properties (unlike Java, this. is required)

invoking a function on an object

  • invocation is just like Java

aStudent.getSID = function () { return this.sid; }; anSID = aStudent.getSID ();

Shared object properties

terminology

  • in Java an object is an instance of a class
  • in JavaScript an object is an instance of constructor function and a shared prototype

common constructor function

  • name of function becomes name of the shared properties (like the class)
  • create a new instance by applying new to function name
  • creates a copy of each property in every instance

function Student (anSID, aName) { this.SID = anSID; this.name = aName; this.getSID = function () { return this.sid; } } aStudent = new Student (10,"First Student");

aStudent = new Object(); aStudent.Student(10,”First Student”);

7 8

slide-5
SLIDE 5

common prototype

  • property of constructor function
  • assigned to object implicitly when it is created
  • so, every object created by a particular constructor shares the same prototype object

prototype delegation

  • when JavaScript looks for a property when accessed
  • look in object, if not found look in prototype
  • updating a delegated property, creates a local copy in object based on prototype’s value
  • what are values of a0.x, a1.x and a2.x?

function A () {} A.prototype.x=1; function whenLoaded () { var a0 = new A (); var a1 = new A (); var a2 = new A (); A.prototype.x = 3; a2.x = 2; alert(a0.x+', '+a1.x+', '+a2.x); }

share method among objects created same constructor use static initializer to create multiple prototype properties

function Student (anSID, aName) { this.SID = anSID; this.name = aName; } Student.prototype.getSID = function () { return this.SID; }; function Student (anSID, aName) { this.SID = anSID; this.name = aName; } Student.prototype = { getSID: function () { return this.SID; }, getName: function () { return this.name; } }

Method declaration using prototypes

9 10

slide-6
SLIDE 6

Delegation using prototypes

delegation is key feature object-oriented inheritance

  • in Java, subclass delegates to its superclass
  • in JavaScript, object delegates to its prototype

setting up the objects for delegation calling delegate’s constructor

function Person (aName) { this.name = aName || ""; } Person.prototype.show = function () { alert (this.name); }; function Student (anSID) { this.SID = anSID || ""; } Student.prototype = new Person (); Student.prototype.show = function () { alert(this.name+" "+this.SID); }; function Instructor () {} Instructor.prototype = new Person (); function Student (anSID, aName) { this.prototypeCtor = Person; this.prototypeCtor (aName); this.SID = anSID; }

  • r better ...

function Person (aName) { this.personCtor = Person; this.name = aName || ""; } Person.prototype.show = function () { alert (this.name); }; function Student (aName, anSID) { this.studentCtor = Student; this.personCtor (aName); this.SID = anSID || ""; } Student.prototype = new Person (); Student.prototype.show = function () { alert(this.name+" "+this.SID); }; function Instructor () {} Instructor.prototype = new Person (); function Person (aName) { this.name = aName || ""; } Person.prototype.show = function () { alert (this.name); }; Person.prototype.personCtor = Person; function Student (aName, anSID) { this.studentCtor = Student; this.prototype.personCtor (aName); this.SID = anSID || ""; } Student.prototype = new Person (); Student.prototype.show = function () { alert(this.name+" "+this.SID); }; function Instructor () {} Instructor.prototype = new Person ();

11 12

slide-7
SLIDE 7

key to modular design is encapsulation

  • hiding some details of the implementation of an abstraction
  • behind a public interface

access-level modifiers

  • are langauge features that implement encapsulation
  • in Java: public, private, protected and package

in JavaScript, support for access levels is poor

  • public
  • any property assigned to an object or its prototype directly is public
  • private
  • local variables created in object’s constructor
  • visible to functions assigned to object, but not to is prototype’s functions

Access-level modifiers in JavaScript

function Student (anSID, aName) { var refCount = 1; this.addReference = function () { refCount++; } this.remReference = function () { refCount--; } this.isReferenced = function () { refCount>0; } }

Inheritance and access limits don’t combine well

why doesn’t this work?

  • one copy per call to RefObjectPrototype() not one per instance

prototype instance properties must be be public

function RefObjectPrototype () { var refCount = 100; this.addReference = function () { refCount++; }; this.remReference = function () { refCount--; }; this.isReferenced = function () { return refCount; }; } function Student (anSID, aName) { this.SID = anSID; this.name = aName; } Student.prototype = new RefObjectPrototype (); Student.prototype.getSID = function () { return this.SID; }; Student.prototype.getName = function () { return this.name; }; function RefObjectPrototype () { this.refCount = 100; this.addReference = function () { this.refCount++; }; this.remReference = function () { this.refCount--; }; this.isReferenced = function () { return this.refCount; }; }

13 14

slide-8
SLIDE 8

Arrays in JavaScript

declaring and initializing getting (and setting) length sorting, converting to a string stacks and queues

var c1 = new Array (3); var c2 = new Array ("red", "green", "blue"); var c3 = ["red", "green", "blue"]; var c4 = { 0: "red", 1: "blue", 2: "green"}; c1[3] = "black"; // c1.length == 4 c1.length = 10; c1.sort (); // c1 == ["blue", "green", "red"] var cs = c1.join(", "); // cs == "blue, green, red" var c5 = c1.concat ("yellow", "orange"); var c5 = c1.slice (2,4); // c5 == ["blue", "yellow"] c1.push ("new"); var x = c1.pop (); c1.shift ("new"); var x = x1.unshift ();

Loops and conditionals in JavaScript

mainly like Java

  • iterative with for (;;) {}
  • logical with while () {} and do {} while ()
  • exiting current iteration with continue and entire look with break
  • conditionals with if () {} {} and switch () {}

iterating over collection

  • for (variable in object) { ... object[variable] ... }
  • does not work with DOM NodeLists (more shortly)
  • regular for loops always work

for (aColour in c1) { document.write (c1[aColour]); } var coll = document.getElementsByName ('x'); for (var i=0; i<coll.length; i++) { ... } var coll = document.getElementsByName ('x'); for (var item in coll) { ... }

15 16

slide-9
SLIDE 9

exceptions

throw e statement

  • control is transferred to enclosing catch clause, if any
  • any object (or value) can be used as e, the exception

try {} catch (e) {} statement

  • handles any exception thrown in “try” block
  • e is bound to the object that was thrown
  • unlike Java (or PHP), catch does not match an exception type

<html> <body> <script type="text/javascript"> var x = prompt("Enter a number between 0 and 10:","") try { if(x>10) throw "Err1" else if(x<0) throw "Err2" } catch(er) { if(er=="Err1") alert("Error! The value is too high") else if(er == "Err2") alert("Error! The value is too low") } </script> </body> </html>

JavaScript Document Object Model (DOM)

defines a object/event framework for elements of HTML page

  • objects give JavaScript access to HTML objects
  • events give HTML access to JavaScript functions

the main standard objects are

  • window
  • browser window and all of its content
  • navigator
  • browser navigation
  • document
  • document in a browser window

17 18

slide-10
SLIDE 10

The window object in Javascript

top-level object in JavaScript

  • ‘window.’ often left out when accessing window properties (e.g., alert)

some useful elements of the window object

  • pen
  • pen a new window for URL

location change the document displayed in window focus set input focus to window moveTo change window position on client screen back move to previous page close close the window alert display an alert pop-up prompt prompt the user for input resizeTo change the size of the window setResizable determine whether window can be resized screenX, screenY get window’s position on client screen frames[] get an array of the frames within the window

http://www.cs.ubc.ca/~feeley/cics515/code/week3/zot.html notice also how to call JavaScript from a hyperlink

<html> <body> <script type="text/javascript"> function openWindows () { var winA = window.open ("http://www.yahoo.com", "A", "width=400,height=400"); var winB = window.open ("http://www.igoogle.com", "B", "width=400, height=400, toolbar=no, scrollbars=no"); winB.focus (); winA.moveTo (100,100); winB.moveTo (400,400); } </script> <a href="javascript: openWindows()">Open Windows</a><br> </body> </html>

19 20

slide-11
SLIDE 11

some useful elements of the navigator object http://www.cs.ubc.ca/~feeley/cics515/code/week3/zot.html

The navigator object in JavaScript

userAgent identity of the browser platform

  • perating system

plugins[] list of installed browser plugins

<html> <body> <script type="text/javascript"> function about () { document.write ("userAgent: "+navigator.userAgent+"<br>"); document.write ("platform: "+navigator.platform+"<br>"); for (var i=0; i<navigator.plugins.length; i++) { document.write ("plugin: "+navigator.plugins[i].name+"<br>"); } } </script> <a href="javascript: about()">About Me</a> </body> </html>

The document object in JavaScript

collections some properties some methods

anchors[] all the anchor objects forms[] all the form objects images[] all the image objects links[] all the area and link objects body body object domain IP domain name of document referrer URL of document that loaded current document URL URL of current document getElementById() locate object by its unique id getElementsByName() list of objects with specified name (as NodeList) write() write HTML (or JavaScript) to document writeln() adds a new-line after writing

21 22

slide-12
SLIDE 12

Element objects in Javascript

each type of element has a set of properties here are some that are common to most elements

className name of element’s CSS class title advisory title style style object innerHTML the HTML inside of the element (e.g., td or a) id unique id name not-necessarily-unique name form containing form (for inputs only)

Finding an element’s object

by reference from another object

  • HTML documnet is a tree of objects rooted at the document object

by ID

  • unique among all elements in document
  • or with some JavsScript syntaxic sugar

<body onload='whenLoaded()'> <form name='formOne' action=''> <input id='formOne_one' name='one' type='text' size='20'> </form> <form name='formTwo' action=''> <input id='formTwo_one' name='one' type='text' size='20'> </form> </body> document.forms[0].elements[0].style.borderColor='blue'; document.getElementById('formOne_one').style.borderColor='red'; document.forms[0].formOne_one.style.borderColor='purple';

23 24

slide-13
SLIDE 13

by Name

  • need not be unique, access all elements with name
  • access first with that name, or if name is unique
  • or access first with syntatic sugar

as this in HTML DOM event handler (more shortly) http://www.cs.ubc.ca/~feeley/cics515/code/week3/findit.html

var ones = document.getElementsByName ('one'); for (var i=0; i<ones.length; i++)

  • nes[i].style.borderColor='orange';

document.getElementsByName('one')[0].style.borderColor='yellow'; document.forms[0].one.style.borderColor='green'; <input id='formOne_one' name='one' type='text' size='20'

  • nclick='this.style.borderColor="grey"'>

The style and className members

used to change the display format of an element

  • document.getElementById (“box100”).style.color = “blue”;
  • document.getElementById (“box100”).className = “moodyBox”;

generally using className is better

  • for same reason that CSS formatting is better than HTML-embedded formatting
  • what were those reasons again?

some of the properties of the style object

color backgroundColor font fontWeight fontSize wordWrap textDecoration posLeft visibility

25 26

slide-14
SLIDE 14

http://www.cs.ubc.ca/~feeley/cics515/code/week3/zot.html

<html> <body> <script type="text/javascript"> function changeColor (anId,aColor) { document.getElementById (anId).style.color=aColor; } </script> <table><tr><td id="td0">Zero</td><td id="td1">One</td></tr></table> <a href="javascript: changeColor('td1','red')">Set Red</a> <a href="javascript: changeColor('td1','black')">Set Black</a> </body> </html>

http://www.cs.ubc.ca/~feeley/cics515/code/week3/betterThanStyle.html

<html> <head> <style type='text/CSS'> *.highlight { color: red; } *.noHighlight { color: black; } </style> <script type='text/JavaScript'> var HIGHLIGHT_CLASS = 'highlight'; var NO_HIGHLIGHT_CLASS = 'noHighlight'; function setClassName (anID, aClassName) { document.getElementById (anID).className = aClassName; } </script> </head> <body> <table><tr><td id='td0'>Zero</td><td id='td1'>One</td></tr></table> <a href="javascript: setClassName ('td1',HIGHLIGHT_CLASS)">Set Highlight</a> <a href="javascript: setClassName ('td1',NO_HIGHLIGHT_CLASS)">Clear Highlight</a> </body> </html>

27 28

slide-15
SLIDE 15

like other objects, DOM objects have prototypes too naming convention

  • “HTML” + name-of-element + “Element.prototype”
  • e.g., HTMLInputElement.prototype

use this to add a property to all objects of some type

  • e.g., add new method to Input DOM object
  • HTMLInputElement.prototype.newMethod = function (arg) { ... };

DOM prototype objects

HTML elements can define JavaScript event handlers here are some events than can have handlers

Events

  • nSubmit

when form is submitted

  • nClick

when element is clicked on

  • nMouseOver when mouse pointer enters element
  • nMouseOut

when mouse pointer leaves element

  • nKeyDown

when key is press when element has focus

  • nKeyUp

when key is released when element has focus

  • nLoad

when page finishes loading

  • nChange

when value of element changes

  • nFocus

when element receives input focus

  • nBlur

when element looses input focus

29 30

slide-16
SLIDE 16

For example

set select box when name changes ...

http://www.cs.ubc.ca/~feeley/cics515/code/week3/enterStudents4.php

<script type="text/javacript"> function checkBox (row) { document.getElementById('checkbox'+row).checked = true; } </script> ... for ($i=0; $i<mysql_numrows($rows); $i++) { $sid = mysql_result ($rows, $i, 'sid'); $name = mysql_result ($rows, $i, 'name'); echo "<tr>\n"; echo "<td><input id='checkbox$i' "; echo "name='selected[]' type='checkbox' value='$i'>\n"; echo "<td>$sid<input type='hidden' name='sid[]' value='$sid'>\n"; echo "<td><input name='name[]' type='text' size='30' value='$name'"; echo "onchange='checkBox($i)'>\n"; echo "</tr>\n"; }

  • r disable name input until select box is checked

http://www.cs.ubc.ca/~feeley/cics515/code/week3/enterStudents5.php

<script type="text/javascript"> function checkBox (row) { var box = document.getElementById('checkbox'+row); var name = document.getElementById('name'+row); name.disabled = !box.checked; } </script> ... echo "<td><input id='checkbox$i' "; echo "name='selected[]' type='checkbox' value='$i'"; echo " onchange='checkBox($i)'>\n"; echo "<td>$sid<input type='hidden' name='sid[]' value='$sid'>\n"; echo "<td><input id='name$i' name='name[]' type='text' size='30'"; echo " value='$name' disabled='true'>\n";

31 32