20
JavaScript JavaScript – the language Web page manipulation with JavaScript and the DOM 2 jonkv@ida Why JavaScript? 19941995: Wanted interactivity on the web Serverside interactivity: CGI Common Gateway Interface Batchoriented (fill in a form, get interactive results) "Heavyweight" clientside interactivity: Java Applets Selfcontained part of a web page Interacts with the user + possibly a server Does not interact with the document itself (Interactive versions of Macromedia Flash not available until 1998) "Lightweight" clientside interactivity: Netscape LiveScript Script language for the web (introduced late 1995) Renamed to JavaScript (marketing!) Standardized version: ECMAscript (ECMA262, ISO16262) Also used in Flash, Firefox/Thunderbird UI, PDF files, MacOS Dashboard Widgets, PhotoShop, … 3 jonkv@ida JavaScript 1: Example A simple JavaScript example : In HTML, scripts are CDATA – not parsed by browsers, validators <!DOCTYPE HTML PUBLIC > <HTML> <head> <title>Hello, World!</title> <script type="text/javascript"> alert("Hello, World!"); // Show an alert to the user </script> </head><body>…</body></HTML> In XHTML, your inline code is by default PCDATA (parsed) if (a < b) – the “<“ will be interpreted as the start of a tag <script type="text/javascript"> /* <![CDATA[ */ … your code … /* ]]> */ </script> 4 jonkv@ida JavaScript 2: Script files Better solution: Separate script file Test.html: <!DOCTYPE HTML PUBLIC > <HTML> <head> <title>Hello, World!</title> </head> <body> <script type="text/javascript" src="example.js"></script> </body> </HTML> example.js: // Show an alert to the user alert("Hello, World!");

1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

JavaScript

JavaScript – the languageWeb page manipulation with JavaScript and the DOM

2

jonk

v@id

a

Why JavaScript? 1994‐1995:  Wanted interactivity on the web Server‐side interactivity:  CGI

▪ Common Gateway Interface▪ Batch‐oriented (fill in a form, get interactive results)

"Heavy‐weight" client‐side interactivity:  Java Applets▪ Self‐contained part of a web page▪ Interacts with the user + possibly a server▪ Does not interact with the document itself▪ (Interactive versions of Macromedia Flash not available until 1998)

"Light‐weight" client‐side interactivity:  Netscape LiveScript▪ Script language for the web (introduced late 1995)▪ Renamed to JavaScript (marketing!)▪ Standardized version:  ECMAscript (ECMA‐262, ISO‐16262)▪ Also used in Flash, Firefox/Thunderbird UI, PDF files, MacOSDashboardWidgets, PhotoShop, …

3

jonk

v@id

a

JavaScript 1: Example A simple JavaScript example: In HTML, scripts are CDATA – not parsed by browsers, validators

▪ <!DOCTYPE HTML PUBLIC …><HTML><head><title>Hello, World!</title><script type="text/javascript">alert("Hello, World!");  // Show an alert to the user

</script></head><body>…</body></HTML>

In XHTML, your inline code is by default PCDATA (parsed)▪ if (a < b) – the “<“ will be interpreted as the start of a tag▪ <script type="text/javascript">/* <![CDATA[ */… your code …/* ]]> */

</script>

4

jonk

v@id

a

JavaScript 2: Script files Better solution:  Separate script file Test.html:

▪ <!DOCTYPE HTML PUBLIC …><HTML><head><title>Hello, World!</title>

</head><body><script type="text/javascript" src="example.js"></script></body>

</HTML> example.js:

▪ // Show an alert to the useralert("Hello, World!");  

Page 2: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

5

jonk

v@id

a

JavaScript 3: Types and type checking Like many script languages:  No static type checking Variables are always declared with "var", not with a type

▪ varmyvar = "Testing";myvar = 10;myvar = true;

Example:  Some calculations▪ var secs_per_min = 60;varmins_per_hour = 60;var hours_per_day = 24;var secs_per_day = secs_per_min * mins_per_hour * hours_per_day;

Special values:▪ null (behaves like 0 in numeric context, false in boolean context)▪ undefined (behaves like false in boolean context)

6

jonk

v@id

a

JavaScript 4: Control Control structures are similar to Java if (condition) { … } else { … } switch / case

for (var i = 0; i < 10; i++) { … } while (condition) { … } do { … } while (condition) break / continue

try { throw new …; } catch (e) { … } finally { … } try { throw "Something"; } catch (e) { … } finally { … } // Comment /* Long comment */

7

jonk

v@id

a

JavaScript 5: Operators Operators are similar to Java, C, C++ ==    != // equals (tries to convert types before comparison) ===   !== // (strict equals – no type conversion) +   ‐ *   / <   > <<   >>   >>>// left shift, right shift, unsigned right shift +=   ‐=   *=   /= ++,   ‐‐ &&,   ||

8

jonk

v@id

a

JavaScript 6: Functions Functions:  Declared using the "function" keyword Late type checking:  Don't declare parameter types

▪ function get_secs(days) {var secs_per_min = 60;var mins_per_hour = 60;var hours_per_day = 24;var secs_per_day =

secs_per_min * mins_per_hour * hours_per_day;return days * secs_per_day;

}▪ var secs_per_week = get_secs(7);

Checking whether functions exist:▪ if (get_secs) { … }▪ Important!  Used to check the level of JavaScript support.▪ Important!  Used to check the level of DOM support.

Page 3: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

9

jonk

v@id

a

JavaScript 7: Object-oriented Object‐oriented but not class‐based Individual objects can have their own methods or fields

▪ varme = new Object();me.name = "Jonas Kvarnström"; // Creates a "name" fieldme.phone = null;me.getName = function() { return this.name; }

▪ var you = new Object();you.name = "Jane Doe";   you.address = "somewhere";

Literal notation:▪ varme = {

name: "Jonas Kvarnström",  phone: null,getName: function() { return this.name; }

}; Only weak syntax checking possible

▪ alert(me.phone); // OK▪ alert(you.phone); // No such property (runtime error)

10

jonk

v@id

a

JavaScript 8: Constructors Can use constructors if you want to Names the type ("Person")

▪ function Person(name, phone) {this.name = name;this.phone = phone;this.getName = function() { return this.name; }

}▪ varme = new Person("Jonas Kvarnström", "2305");

Can still add methods / fields incrementally▪ me.address = "Somewhere";▪ me.setAddress = function(addr) { this.address = addr; }

11

jonk

v@id

a

JavaScript 9: Adding new methods Inheritance based on prototypes Each object inherits properties from a prototype object

▪ function Employee(name, phone, department) {this.name = name;this.phone = phone;this.department = department;

}▪ varme = new Employee("Jonas", "2305", "IDA");me.prototype = new Person();  // Inheritance on a per‐object level!me.getPhone(); // works – inherited function from prototype

Set the prototype of a constructor method▪ Default prototype for objects constructed using Employee function▪ Employee.prototype = new Person();  // "extends Person"

12

jonk

v@id

a

JavaScript 10: Adding to prototype Can add properties to the prototype at any time! Incremental extension

▪ person.prototype.getPhone = function() { return phone; }▪ Now all "person" objects have this method

Works for built‐in classes too!▪ if (!String.prototype.trim) { // If trim does not exist

String.prototype.trim = function() {return this.replace(/^\s+/,"").replace(/\s+$/,"");

} }

Page 4: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

13

jonk

v@id

a

JavaScript 11: Arrays Arrays:  Kind of like Java arrays… Allocated with new operator, or [] syntax

▪ var names1 = new Array("Roger", "Moore");var names2 = [ "Roger", "Moore" ];var empty = new Array(10);

Indexed using [] syntax▪ names[0] == "Roger"▪ empty[0] == undefined

Have a .length property Example:

▪ var reply = prompt("What's your name?", "");var names = reply.split(" ");for (var pos = 0; pos < names.length; pos++) {alert("One of your names is " + names[pos]);

}

Useful array methodsconcat – joins two arraysjoin – joins array elements into stringpush(x), pop()slice() – returns a subsection of the arraysplice() – adds/removes elementssort()

14

jonk

v@id

a

JavaScript 12: Associative arrays Arrays can be associative Can replace Map / HashMap in Java

▪ var phoneNumbers = new Array();phoneNumbers["Jonas"] = "070‐xxxxxxx";phoneNumbers[“Martin"] = "070‐xxxxxxx";

Can iterate over all keys▪ for (var name in phoneNumbers) { // ”Jonas”, ”Martin”, …

doSomethingWith(phoneNumbers[name]);}

Properties and arrays:  Different interfaces, same data structure▪ varme = new Person("Jonas Kvarnström", null);me["name"] = "Jonas Kvarnström";for (var prop inme) { /* iterate over "name", "phone", "getName" */ }

15

jonk

v@id

a

JavaScript 13: Strings String Single or double quotes

▪ varmyvar = 'asdf', othervar = "qwerty"; Fields:  length General Methods

▪ charAt, charCodeAt, indexOf, lastIndexOf▪ fromCharCode // from sequence of Unicode values▪ "abc def ghi".split(" ") == array containing "abc", "def", "ghi"▪ substring, substr, slice, concat▪ match, replace, search // regular expressions▪ toLowerCase, toUpperCase

HTML‐related Methods▪ anchor, link // HTML named anchor / hyperlink▪ big, blink, bold, fixed, italics, small, strike, sub, sup

16

jonk

v@id

a

JavaScript 14: Dates Date Constructors

▪ var date = new Date(); // today▪ var date = new Date("December 31, 2010 12:34:56");▪ var date = new Date(2010, 12, 31);

Methods▪ getYear(), getMonth(), getDate, getDay() // and setters▪ getHour(), getMinute(), getSecond() // and setters▪ getFullYear() // four‐digit year

Page 5: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

17

jonk

v@id

a

JavaScript 15: History and Window Browser‐specific JavaScript objects: history – the page history

▪ history.back(), history.forward()▪ history.go(delta) // ‐1 = back, ‐2 = 2 steps back, ... ▪ history.go('www.ida.liu.se') // nearest URL containing 'www.ida.liu.se'

window.location – the current location URL▪ window.location = "http://www.ida.liu.se"; // New history entry▪ window.location.reload();▪ window.location.replace("http://www.ida.liu.se"); // No new entry

DOM:The Document Object Model

Accessing the Structure of a Document

19

jonk

v@id

a

Manipulating HTML Many web apps activelymanipulate HTML / XML Populate dropdown boxes depending on previous choices

▪ Select country "Sweden"  add Swedish cities to the city dropdown Hide and show elements of a web page

▪ Click "advanced" to show additional fields in a form Check the validity of form input fields

▪ Show errors without requiring a round trip to the server …

20

jonk

v@id

a

DOM 1: Document Object Model W3C DOM:  Document Object Model A document is a tree of nodes with attributes

▪ Well‐defined standard▪ Specified using IDL, the Interface Definition Language▪ Implemented in many different languages, including JavaScript

<Table>

<THead> <TBody>

<TR>

<TH>

Item Price

<TH>

<TR> <TR> <TR>

<TD> <TD>

$100.00Foo

Page 6: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

21

jonk

v@id

a

DOM 2: Navigating through Documents The document is also a node In JavaScript: Accessed through the document variable Has methods for finding other nodes

▪ Give an element a name: <span id="foo">change this text</span>▪ var foonode = document.getElementById(”foo”);

var allspans = document.getElementsByTagName(”span”); All nodes have methods for tree traversal…

▪ readonly attribute Node parentNode;readonly attribute NodeList childNodes;boolean hasChildNodes();

… and for tree manipulation:▪ Node insertBefore(in Node newChild, in Node refCh);

Node replaceChild(in Node newChild, in Node oldCh);Node removeChild(in Node oldChild);Node appendChild(in Node newChild);

22

jonk

v@id

a

DOM 3: Element and Text Nodes Element and Text node <p>This is a paragraph</p>

▪ interface CharacterData : Node {attribute DOMString data;readonly attribute unsigned long length;void replaceData(in unsigned long offset, in unsigned long count,

in DOMString arg)void insertData(in unsigned long offset, in DOMString arg)void deleteData(in unsigned long offset, in unsigned long count)void appendData(in DOMString arg)

};interface Text : CharacterData {

Text splitText(in unsigned long offset);};

<p>

This is a paragraph

Element node

Text node

23

jonk

v@id

a

DOM 4: Attribute Nodes Each node has an attribute list <img src="foo.png" height="100" width="300">

▪ DOMString getAttribute(in DOMString name);void setAttribute(in DOMString name, in DOMString value);void removeAttribute(in DOMString name);Attr getAttributeNode(in DOMString name);Attr setAttributeNode(in Attr newAttr);Attr removeAttributeNode(in Attr oldAttr);

▪ interface Attr : Node {readonly attribute DOMString name;readonly attribute boolean specified;attribute DOMString value;

};

<img>

width300

height100

SRCfoo.png

Attr nodes

24

jonk

v@id

a

DOM 5: Composite Example <P STYLE=“…”>This is a <span>paragraph</span>…</P>

<p>

This is a 

paragraph

<span>STYLE

……

Page 7: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

Using the DOMin JavaScript

26

jonk

v@id

a

DOM/JS 1: DOM in JavaScript JavaScript has a standard DOM implementation Interfaces represented as JavaScript objects / prototypes Several standard objects always available

▪ document ‐‐ the current page (HTMLDocument)▪ window ‐‐ the current window▪ location ‐‐ the current URL being displayed (window.location)▪ navigator ‐‐ the browser (version, platform, …)▪ screen ‐‐ screen properties

Now:  Using DOM interfaces in JavaScript

27

jonk

v@id

a

Example 1

Dynamic Document Generation

28

jonk

v@id

a

Dynamic document generation 1 Dynamic document generation using writeln() Simple but not very structured – often discouraged

▪ var secs_per_min = 60;var mins_per_hour = 60;var hours_per_day = 24;var secs_per_day = secs_per_min * mins_per_hour * hours_per_day;document.writeln("<p>There are ");document.writeln(secs_per_day);document.writeln(" seconds per day");

Example: ex1.html

Page 8: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

29

jonk

v@id

a

Dynamic document generation 2 Dynamic document generation, structured Simple example: Naming an element, modifying it

▪ <body><h2>Hello, World!</h2><p>I can <span id=“changespan">change this text</span>!<p><a href=“javascript_required.html”

onclick=“changeText('changespan', 'modify stuff')">Do it!</a></body>

▪ function changeText(id, text) {var element = document.getElementById(id);

var textnode = element.firstChild;

textnode.data = text;}

Example: ex2.html

<span>

change what I wrote

30

jonk

v@id

a

Example 2

Document Manipulation:Dynamically Adding Rows to Search Forms

Search for messages matching:

term1

term1

term1

New row

31

jonk

v@id

a

Dynamically Adding Rows 1 First shot:

▪ <!DOCTYPE HTML PUBLIC …><html><head><title>Dynamic Forms</title></head><body><h3>Dynamic Forms</h3>

<form><table>

<tbody id=“searchtable"><tr><td><input type="text" name=“input0"></td></tr>

</tbody></table><input type="button" value="Add row“ onClick="addRow(‘searchtable');">

</form></body>

</html>

Next one should be named input1

Instead of a link: Button with HTML event handling (onClick)

32

jonk

v@id

a

Dynamically Adding Rows 2 Create a new <tr> row in addRow()... No constructors exist in IDL – instead, factory methods

▪ HTMLTableElement provides insertRow()▪ HTMLTableRowElement provides insertCell()▪ Document provides generic factory methods▪ Element createElement(in DOMString tagName) raises(DOMException);

Text createTextNode(in DOMString data);Attr createAttribute(in DOMString name) raises(DOMException);

▪ function addRow(someID) { // Param is ID from <tbody id="mybody">var tbody = document.getElementById(someID);var newrow = tbody.insertRow(-1);var newcell = newrow.insertCell(-1);var newinput = document.createElement("input");newinput.type = "text"; // HTML attributes available as fields!newinput.name = “input" + tbody.rows.length; // input1, input2, …newcell.appendChild(newinput);

} Example: ex3b.html

Page 9: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

33

jonk

v@id

a

Example 3

Expanding and Collapsing Elements

34

jonk

v@id

a

Collapsing and Expanding 1 Expand / collapse elements ‐‐ example: sidebar menus Click header => toggle visibility of link box

▪ <tr><td id="general" onclick="toggleBlock('generalbox');“>General</td></tr><tr><td class="linkbox" id="generalbox">

<a class="nav" href="prerequisites.html">Prerequisites</a><br><a class="nav" href="staff.html">Staff</a><br>

</td></tr>

JavaScript code to toggle CSS display property for one block:▪ function toggleBlock(id) {

var style = document.getElementById(id).style;if (style.display == 'none') {

style.display = 'block‘;} else {

style.display = 'none';}

} Example: Old Course Pages

35

jonk

v@id

a

Example 4

CSS + JavaScript Hover Menus

(adapted from "Suckerfish Dropdowns" at http://alistapart.com/articles/dropdowns/)

36

jonk

v@id

a

Hover Menus 1 Goal: Top‐level navigation menu with dropdowns Determine what HTML markup to use Determine what can be done with pure HTML+CSS Might need some scripts too!

Page 10: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

37

jonk

v@id

a

Hover Menus 2 Markup: The structure of a menu is a nested list!

▪ <ul class="menu"><li>Sunfishes<ul><li><a href="">Blackbanded sunfish</a></li><li><a href="">Shadow bass</a></li><li><a href="">Ozark bass</a></li><li><a href="">White crappie</a></li>

</ul></li><li>Grunts<ul> ... </ul>

</li></ul><p>Here is some text after the menu</p>

38

jonk

v@id

a

Hover Menus 3 Suitable structure, but the default display is bad! Don't show as a bullet list Remove list‐related margins

▪ ul.menu,  // any UL of class menuul.menu ul // any UL inside an UL of class menu{padding: 0; // No padding or margins for these elementsmargin: 0;list‐style: none; // Don't show as a bullet list!

}

39

jonk

v@id

a

Hover Menus 4 Wewanted a horizontal menu! Let menu items float

▪ At the current y position▪ As far left as possible

Give them a constant width (for better appearance)▪ ul.menu li { // any LI inside an UL of class menu

float: left;position: relative;width: 10em;

}

40

jonk

v@id

a

Hover Menus 5 Oops! What comes after "float: left" continues at the same line!

▪ This is intended behaviour – lets you float an image to the left To "continue after floating elements", use clear

▪ clear: left – after all elements floating left▪ clear: right – after all elements floating right▪ clear: both – after all floating elements▪ ...

</li></ul><div class="aftermenu"></div><p>Here is some text after the menu</p>

▪ div.aftermenu {clear: both; 

}

Page 11: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

41

jonk

v@id

a

Hover Menus 6 Submenus should initially be hidden!

▪ ul.menu li ul {display: none;

}

When we hover over their parents, they should be seen▪ ul.menu li:hover ul {

display: block;} 

▪ This selector is more specific than “ul.menu li ul”, and takes precedence

42

jonk

v@id

a

Hover Menus 7 Drop‐down menus should not move other text! Achieved through CSS position attribute

▪ position: static – default▪ position: relative – at an offset from normal position▪ position: absolute – will not affect layout of other components▪ position: fixed – relative to window (does not move when scrolling)▪ ul.menu li ul {

display: none;position: absolute; 

} Also give a background color (otherwise transparent)

▪ ul.menu li ul {display: none;position: absolute;background: rgb(230, 230, 230); 

}

http://www.w3.org/TR/REC-CSS2/visuren.html#positioning-scheme

43

jonk

v@id

a

Hover Menus 8 Bad layout in Internet Explorer 6 (20% market share)! Must specify non‐default top/left coordinates…

▪ ul.menu li ul {display: none;position: absolute; top: 1em;left: 0;

} …but this looks bad in Opera!

▪ Use the ">" selector ("immediately within")▪ Opera and others understand this rule and apply it▪ IE 6 does not understand the rule – ignores it

▪ ul.menu li > ul {top: auto; left: auto;

44

jonk

v@id

a

Hover Menus 9 Still does not work in Internet Explorer 6! IE 6 only supports :hover for links (<a …></a>) Weused it for <li> attributes…

Workaround: JavaScript for IE 6 Add an alternative to :hover – the over class

▪ ul.menu li:hover ul, ul.menu li.over ul {display: block;

} Must add "over" class dynamically when hovering Must remove "over" class dynamically when not hovering

Page 12: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

45

jonk

v@id

a

Hover Menus 10 Dynamic addition/removal of classes Call suitable JavaScript functions from HTML event handlers

▪ mouseover event – add "over" classmenu shown▪ mouseout event – remove "over" classmenu hidden

Could specify mouseover / mouseout for each <li>▪ Repetitive▪ Intrusive▪ Ugly code▪ Mixes semantic markup with programming

Better: Let JavaScript analyze the DOM + add event handlers!

Step 1: Identifying the navigation list▪ <ul class="menu" id="nav">

46

jonk

v@id

a

Hover Menus 11 Step 2: Function adding event handlers

▪ startList() {// Only if IE 5+ (supports doc.all and doc.getElByID) if (document.all && document.getElementById) {

navRoot = document.getElementById("nav");for (i=0; i<navRoot.childNodes.length; i++) {

node = navRoot.childNodes[i];if (node.nodeName=="LI") {

node.onmouseover = function() {this.className+=" over";

}node.onmouseout = function() {

this.className=this.className.replace(" over", "");}

}}

}}

47

jonk

v@id

a

Hover Menus 12 Step 3: When to call this function? Not "inline"

▪ The script might be executed before the navigation menu is loaded! Use an ”onload” event handler

▪ window.onload=startList;▪ Executed immediately after the page is fully loaded

48

jonk

v@id

a

Hover Menus 13 Still an uglymenu – use CSS to improve Font settings

▪ ul.menu { font: 11pt "Myriad Web"; } Background + subtle border for line items

▪ ul.menu li {background: rgb(240,240,230);border‐bottom: 1px solid rgb(230,230,220);padding: 0.4ex;

} When hovering, use a brighter background

▪ ul.menu li:hover { background: rgb(250,250,240); } Adjust submenu for padding

▪ ul.menu li ul { margin‐top: 0.4ex; 

}

Page 13: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

49

jonk

v@id

a

Hover Menus 14 Submenu items have another color

▪ ul.menu li ul li {background: rgb(230,230,220);border‐bottom: 1px solid rgb(220,220,210);

} Hovering over submenu items

▪ ul.menu li ul li:hover {background: rgb(240,240,230);

} Links are black, not underlined

▪ ul.menu li a {text‐decoration: none;color: black;

}

50

jonk

v@id

a

Example 5

Form Input Validation(JavaScript and server‐side!)

51

jonk

v@id

a

Form Validation 1 Form validation tests constraints on valid input Users must provide an e‐mail address Enter new password twice to detect typing mistakes fields must match 

Messages must have a subject No letters in numeric fields

Server‐side validation takes time! Not much – but a complete roundtrip is required

▪ Post form data to server▪ Server validates data▪ If something is wrong: Show the same form again, with errors marked

Client‐side validation is faster / more interactive! Use JavaScript…

52

jonk

v@id

a

Form Validation 2 Immediate validation of input How?

▪ Use onChange attribute to call a validation method What to do if there is an error?

▪ Don't show a dialog window!  Intrusive, annoying…▪ Preferred: Show a text label indicating there is an error

▪ Age: 1a Error: Must be numeric▪ Age: 200 Error: Number too large

Can also use this technique to show warnings▪ Age: 105 Warning: Please check

Page 14: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

53

jonk

v@id

a

Form Validation 3 Example: Immediate input validation Need label + input field + warning field

▪ <tr><td><label for="age">Your age (years):</label></td><td><input id="age" name="age"type="text"

onchange="validateAge(this, 'inf_age', false);"maxlength="5" size="35"></input></td>

<td id="inf_age">&nbsp;</td></tr>

Need a validation method – validateAge()

54

jonk

v@id

a

Form Validation 4▪ function validateAge(valfield, // actual element to be validated

infofield, // id of element for info/error msgrequired) { // true if value required

// (omitted checking that the value is present)var age = trim(valfield.value); // Assume trim function availablevar ageRE = /^[0-9]{1,3}$/ // start – digits, 1 to 3 of them – endif (!ageRE.test(age)) {

msg(infofield, "error", "ERROR: not a valid age"); return false;}if (age>=200) {

msg(infofield, "error", "ERROR: not a valid age"); return false;}if (age>110) msg(infofield, "warn", "Older than 110: check");else {

if (age<7) msg(infofield, "warn", "Are you really that young?");else msg(infofield, "warn", "");

}return true;

}

55

jonk

v@id

a

Form Validation 5▪ function msg(fld, // id of element to display message in

msgtype, // class to give element ("warn" or "error")message) // string to display

{var elem = document.getElementById(fld);var emptyString = /^\s*$/ ;if (emptyString.test(message)) {

// setting an empty string can give problems if later set to a // non-empty string, so ensure a space (nbsp) is present.var nbsp = 160;elem.firstChild.nodeValue = String.fromCharCode(nbsp);

} else { elem.firstChild.nodeValue = message;

}elem.className = msgtype; // set CSS class to adjust appearance

}

56

jonk

v@id

a

Form Validation 6: CSS CSS code for message types Info: Black text

▪ .info { color: black; font‐weight: normal; } Warning: Dark red

▪ .warn { color: rgb(120,0,0); font‐weight: normal; } Error: Red, bold

▪ .error { color: red; font‐weight: bold } 

Page 15: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

57

jonk

v@id

a

Form Validation 7: Not only inline Inline warnings are perhaps too unobtrusive Easy to miss May also want to check errors at form submission time

▪ Warnings should be ignored▪ Errors should lead to an alert popup, stop form submission

How to stop form submission?▪ Use onsubmit handler – if it returns false, submission is cancelled▪ <FORM id="mf" onsubmit="return validateOnSubmit()"

action="…">… 

</FORM>

58

jonk

v@id

a

Form Validation 8: Validation Alert The validation function calls all individual validators Validators return false for error, true for warning/OK!

▪ function validateAge(valfield, infofield, required) {if (error) { set‐error‐message; return false; }if (warn) { set‐warn‐message; }return true;

}▪ function validateOnSubmit() {

var errs=0;  var myform = document.getElementById("…");if (!validatePhone (myform.phone, 'inf_phone', true)) errs += 1;if (!validateAge (myform.age, 'inf_age', false)) errs += 1;if (!validateEmail (myform.email, 'inf_email', true)) errs += 1;if (!validatePresent(myform.from, 'inf_from')) errs += 1;if (errs>1) alert('There are fields which need correction');if (errs==1) alert('There is a field which needs correction');return (errs==0);

};

59

jonk

v@id

a

Form Validation 9: Potential Mistakes Potential mistakes in client‐side form validation: Only client‐side validation

▪ Clients can manipulate code / turn off JavaScript▪ Must validate on the server too!

Validation that fails without JavaScript▪ Clients can turn off JavaScript / run browsers without JavaScript▪ Must be able to fall back to plain server‐side checking▪ Use a plain submit button – not a JS event handler that posts form data

Too strict validation▪ Requiring a middle initial▪ Requiring a state – but in Sweden we don't have states▪ …

Info, source and examples:▪ http://www.xs4all.nl/~sbpoley/webmatters/formval.html

60

jonk

v@id

a

Example 6

AJAX: Asynchronous JavaScript And XML

Page 16: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

61

jonk

v@id

a

AJAX 1 Different types of interactivity on the WWW: HTML/CSS + form submission + server response

▪ Fill in some information; submit; get a completely new page back▪ Batch‐oriented; calls the server – slow

HTML/CSS + plain JavaScript▪ Purely client‐based▪ Can show / hide information, if it is already on the client:set CSS ”display: none” or ”display: block”

▪ Can calculate new information, if this can be done purely on the client▪ No calls to the server

62

jonk

v@id

a

AJAX 2 What else could we want? Hover over an item show detailed info in a popup

▪ Don't reload the entire page▪ Don't keep this information in the original page,ready to be displayed – far too much information!

Forum: List of topics at the top of the page▪ Click one it is shown below the list▪ Don't reload the entire page▪ Plainly impossible to keep all topics in one web page,ready to be displayed

Dynamic search box▪ Search is performed on the server▪ Client dynamically updates search results as you type

63

jonk

v@id

a

AJAX 3 Solution: Add asynchronous server requests Use XMLHttpRequest object from JavaScript Retrieve data in XML format Set a callback function, called when the request is finished

▪ Parse XML and generate suitable HTML▪ Modify the DOM – add new information / fields

Collective name for these techniques: AJAX Asynchronous JavaScript And XML

Can also be used to fetch data in non‐XML formats… AHAH: AsynchronousHTML and HTTP Server returns HTML, not XML – no need to parse/generate

64

jonk

v@id

a

AJAX 4 Example:  Validate text field with every key press http://java.sun.com/developer/technicalArticles/J2EE/AJAX/

Page 17: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

65

jonk

v@id

a

AJAX 5 Form element calls validate() for every key press

▪ <input type="text" size="20" id="userid" name=“userid"onkeyup="validate();">

66

jonk

v@id

a

AJAX 6 An XMLHttpRequest object is created

▪ var req;function validate() {var idField = document.getElementById("userid");var url = "validate?userid=" + encodeURIComponent(idField.value);// Different class names depending on browserif (typeof XMLHttpRequest != "undefined") {

req = new XMLHttpRequest();} else if (window.ActiveXObject) {

req = new ActiveXObject("Microsoft.XMLHTTP");}req.open("GET", url, true); // true  asynchronously// Set function to be called when a reply is receivedreq.onreadystatechange = callback; // Send the request asynchronously – returns immediatelyreq.send(null);

}

Converts to URI format(space  +, 8‐bit  %XY)

67

jonk

v@id

a

AJAX 7 Alternative for POST

▪ function validate() {var idField = document.getElementById("userid");var url = "validate"; // No query info herevar req;if (typeof XMLHttpRequest != "undefined") {

req = new XMLHttpRequest();} else if (window.ActiveXObject) {

req = new ActiveXObject("Microsoft.XMLHTTP");}req.open("POST", url, true);// Tell the server how the POST data is encodedreq.setRequestHeader(

"Content‐Type", "application/x‐www‐form‐urlencoded"); req.onreadystatechange = callback; // Query info included in ”send” instead (still encoded)req.send("id=" + encodeURIComponent(idField.value));

}

68

jonk

v@id

a

AJAX 8 "/validate" is mapped to ValidateServlet ValidateServlet handles this just like any other request JSP pages can be used – but may be less efficient

▪ Important if this is called for every key press!▪ public class ValidateServlet extendsHttpServlet {

private ServletContext context;privateHashMap users = new HashMap();

public void init(ServletConfig config) throws ServletException {super.init(config);this.context = config.getServletContext();users.put("greg","account data");users.put("duke","account data");

}…

Page 18: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

69

jonk

v@id

a

AJAX 9▪ public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException{

String targetId = request.getParameter("id");

// Return XML document containing reply. Must set this content type!response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache");if ((targetId != null) && !users.containsKey(targetId.trim())) {

response.getWriter().write("<message>valid</message>"); } else {

response.getWriter().write("<message>invalid</message>"); }

}

70

jonk

v@id

a

AJAX 10 The browser listens for replies in the background Calls your callback function when the request state changes

▪ State 0 = uninitialized, 1 = open, 2 = sent, 3 = receiving,4 = loaded/done

Tells you the status of the request▪ HTTP status code: 200 = success, 401 = access denied, …

Possible callback function:▪ function callback() {

if (req.readyState == 4) {if (req.status == 200) {

// update the DOM based on whether or not message is valid}

} else …}

…But wait: How does the callback function get access to req?

71

jonk

v@id

a

AJAX 11 Alternative 1: Global variable

▪ var req;  // Declared outside functions – global variable▪ function validate() { // Called by input field on key press

req = …;…req.onreadystatechange = callback; …

}▪ function callback() { // Called by XMLHttpRequest on state change

if (req.readyState == 4) {if (req.status == 200) {

// update the DOM based on whether or not message is valid}

} else …}

▪ Problem: Fast typing  multiple requests active simultaneously,so old requests will be overwritten (never handled)

72

jonk

v@id

a

AJAX 12 Alternative 2: Callback parameter

▪ function validate() { // Called by input field on key pressvar req;  // Declared inside function – local variablereq = …;…  // Use an anonymous closure to pass on parametersreq.onreadystatechange = function() { callback(req) }; …

}▪ function callback(request) { // Called by anonymous function

if (request.readyState == 4) {if (request.status == 200) {

// update the DOM based on whether or not message is valid}

} else …}

▪ Better and cleaner solution!

Page 19: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

73

jonk

v@id

a

AJAX 13 Example callback function (for alternative 2):

▪ function parseMessageCallback(req) {var XML = req.responseXML;if (request.readyState == 4) {

if (request.status == 200) {// Get the first element named “message”var message = XML.getElementsByTagName("message")[0];// The <message> tag has a text child, child 0.// Its text (the node value) is the text inside <message>…</>.if (message.childNodes[0].nodeValue == "invalid") {

setMessage(“warn”, “Invalid User Id");} else {setMessage(“ok”, “Valid User Id");

}} else {setMessage(“warn”, “Bad Server Response");

}} else { /* We don’t have the complete reply yet */ } }

74

jonk

v@id

a

AJAX 14 Setting the message:

▪ <body> … <div id="userIdMessage"></div> … </body> Alternative 1: Use innerHTML to set the embedded HTML

▪ function setMessage(cls, message) {var mdiv = document.getElementById("userIdMessage");mdiv.innerHTML =

“<div class=\”” + cls + “\””>” +message +“</div>”;

}

75

jonk

v@id

a

AJAX 15 Alternative 2: Create elements directly: function setMessage(cls, message) {

var userMessageElement = document.getElementById("userIdMessage");

userMessageElement.style.className = cls;

var messageBody = document.createTextNode(messageText);

// If it already has a text child, we replace it (it’s from a previous call)if (userMessageElement.childNodes[0]) {

userMessageElement.replaceChild(messageBody,userMessageElement.childNodes[0]);

} else {userMessageElement.appendChild(messageBody);

}}

JavaScript and Browser Compatibility

2010-02-16Jonas Kvarnström

Page 20: 1994 1995: Wanted JavaScriptTDDI15/slides/tddi15-2010-javascript-all.pdfWeb page manipulation with JavaScript and the DOM Why JavaScript? 2 jonkv@ida 1994‐1995: Wanted interactivity

77

jonk

v@id

a

Compatibility 1 Browser support for HTML, DOM, CSS, JavaScript varies Older browsers simply do not support modern features Even newer browsers support partial standards, have bugs

How to adapt? Sometimes, functionality exists but under different names

▪ if (typeof XMLHttpRequest != "undefined") {req = new XMLHttpRequest();

} else if (window.ActiveXObject) {req = new ActiveXObject("Microsoft.XMLHTTP");

} Sometimes, you can do without certain functionality

▪ Use it when it exists▪ Otherwise, graceful degradation (features turned off, …)

Sometimes, there’s just nothing you can do with reasonable effort▪ Many are ceasing to support IE 6…

78

jonk

v@id

a

Compatibility 2: Example Example: Modern DOM uses getElementByID() Netscape 4: finds a node using document.layers IE 4/5: finds a node using document.all

▪ function getElement(name) {if (document.getElementById) {

return document.getElementById(name);} else if (document.all) {

return document.all[name];} else if (document.layers) {

return document.layers[name];}

}

79

jonk

v@id

a

Using Frameworks For all but the simplest applications: Use a framework! Hides browser differences (and there are many!) Provides higher level functionality Provides well‐tested solutions

Examples: JQuery – small (23k compressed), simple, robust

▪ $("p.surprise").addClass("ohmy").show("slow");  Prototype Dojo YUI Toolkit, from Yahoo! …

80

jonk

v@id

a

JavaScript: The End That's it for now The ideas behind the language The connection to the DOM The concept of document manipulation A number of concrete examples

Don't forget: The FireBug inspection / debugging / profiling tool