61
JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus http://staffweb.cms.gre.ac.uk/~mk05/web/JavaScript/Ja vaScript2.html

JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

  • View
    233

  • Download
    0

Embed Size (px)

Citation preview

Page 1: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

JavaScript 2

JavaScript 2

Timers, Images, Sniffing and Validation

Dr Kevin McManushttp://staffweb.cms.gre.ac.uk/~mk05/web/JavaScript/JavaScript2.html

Page 2: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 2

JavaScript 2

xmasTimer.html

Page 3: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 3

JavaScript 2

function calcRemaining(theForm) { var now = new Date(); var year = now.getUTCFullYear(); var xmas = new Date("December 25, " + year + " 00:00:00"); var difference = parseInt((xmas.getTime() - now.getTime()) / 1000);

var secs = difference % 60; difference = parseInt(difference / 60); var minutes = difference % 60; difference = parseInt(difference / 60); var hours = difference % 24; var days = parseInt(difference / 24);

theForm.txtDays.value = days; theForm.txtHours.value = hours; theForm.txtMins.value = minutes; theForm.txtSecs.value = secs; setTimeout("calcRemaining(document.forms[0])", 250); }

Execute this function

In ¼ seconds time

Page 4: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 4

JavaScript 2

<body onload="calcRemaining(document.forms[0])"><form action="dummy"><table> <tr> <th colspan="4">Xmas countdown</th> </tr> <tr> <td>Days</td> <td>Hours</td> <td>Minutes</td> <td>Seconds</td> </tr> <tr> <td><input type="text" name="txtDays" size="4" onfocus="blur()"/></td> <td><input type="text" name="txtHours" size="4" onfocus="blur()"/></td> <td><input type="text" name="txtMins" size="4" onfocus="blur()"/></td> <td><input type="text" name="txtSecs" size="4" onfocus="blur()"/></td> </tr> </table></form></body>

Do not allow editing of the text

Page 5: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 5

JavaScript 2

Things to notice about xmasTimer.html

• The clock now automatically updates itself every ¼ of a second• This is achieved by calling setTimeout() at the end of the

function CalcRemaining()

setTimeout("CalcRemaining(document.forms[0])", 250);

• This will cause a timer to be set that will call calcRemaining() after 250 milliseconds.

• This is NOT a recursive call• if it were the browser would run out of stack space eventually

• calcRemaining() will exit after executing this statement• the timer will then cause it to be called again after the specified delay.

• setTimeout() calls the function once only.• JavaScript 1.2 introduced the setInterval() method which

calls a function repeatedly rather than calling it only once

Page 6: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 6

JavaScript 2

Things to notice about xmasTimer.html

• Use of a table to lay out a form

• The use of the onFocus event handler and the blur() method to prevent the user entering data into the text boxes.

<input type="text" name="txtDays" size="4"

onfocus="blur()"/>

Page 7: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 7

JavaScript 2

Quick Quiz

Given the following piece of code what will happen if the user clicks the button twice as soon as the page is loaded?

<head> <script type="text/javascript"><!-- var time = 2000; function hello() { setTimeout("alert('hello chum')", time); time += 5000; } // --></script> </head><body> <input type="button" value="pressme" onclick="hello()"/> </body>

Page 8: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 8

JavaScript 2

Images in JavaScript• The images[] property of a document is an array of

the images included in the page using the <img /> tag

• To change an image currently on display you can assign the URL of the new image to the src property

document.images[0].src = "townPlan.gif"

• Images may take a noticeable time to load so a common technique is to preload images that will eventually be used on a page

Page 9: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 9

JavaScript 2

rollover.html

Page 10: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 10

JavaScript 2

rollover.html• Function to activate images

function imgOn(i){ switch (i) { case 0 : document.images[i].src='/~mk05/images/hot_on.gif'; break; case 1 : document.images[i].src='/~mk05/images/direct_on.gif'; break; case 2 : document.images[i].src='/~mk05/images/web_on.gif'; break; }}

Page 11: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 11

JavaScript 2

rollover.html• Function to deactivate images

function imgOff(i){ switch (i) { case 0 : document.images[i].src='/~mk05/images/hot_off.gif'; break; case 1 : document.images[i].src='/~mk05/images/direct_off.gif'; break; case 2 : document.images[i].src='/~mk05/images/web_off.gif'; break; }}

Page 12: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 12

JavaScript 2

rollover.html• Function to preload the rollover images

• instance images to hold the rollover images• only call this once after the page has loaded

function getRollovers(){ var image0 = new Image(); var image1 = new Image(); var image2 = new Image(); image0.src="/~mk05/images/hot_on.gif"; image1.src="/~mk05/images/direct_on.gif"; image2.src="/~mk05/images/web_on.gif";}

Page 13: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 13

JavaScript 2

rollover.html<snip><body onload="getRollovers()"><p><a href="/~mk05/hotlist.html" title="hotlist" onmouseover="imgOn(0)" onmouseout="imgOff(0)" onfocus="imgOn(0)" onblur="imgOff(0)"><img src="/~mk05/images/hot_off.gif" alt="lightning bolt"/></a> &nbsp;<a href="/~mk05/directions.html" title="directions for visitors" onmouseover="imgOn(1)" onmouseout="imgOff(1)" onfocus="imgOn(1)" onblur="imgOff(1)"><img src="/~mk05/images/direct_off.gif" alt="pointing finger"/></a> &nbsp;</snip>

title attribute gives the the tool tip

onLoad event preloads the rollover images

alt attribute should describe the image

mouse events onFocus and onBlur

events provide keyboard control

Page 14: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 14

JavaScript 2

rollover.html• The function imgOn(0) is called by the

onMouseOver and onFocus events

• The function imgOff(0) is called by the onMouseOut and onBlur events

• These event handlers are triggered in the anchor tag• allows both mouse and keyboard control of

the page

Page 15: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 15

JavaScript 2

Browser Compatibility• Incompatibility between browsers was a major

problem with the use of client-side JavaScript• Code that worked when executed by one

browser would fail on another. • There are several approaches to this:

• don't use JavaScript at all (do your really need it?)• use only JavaScript that should work on a very wide

range of browsers (as these lecture examples do)• don't worry about any but the latest versions of the

browsers• the people you want on your site always use the latest

technology!!• use browser sniffing

Page 16: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 16

JavaScript 2

Browser Sniffing

• Detect the browser type and version at the server end and serve up an appropriate page for the browser

• Detect the browser at the client end and execute code appropriate to that browser

• Use a combination of several strategies• When using JavaScript you should always:

• ask yourself if it is really necessary• do the benefits outweigh the disadvantages?• could you use some other technology?

• plan your strategy• test on a wide range of browsers and platforms

Page 17: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 17

JavaScript 2

Client-Side Browser Sniffing• Use properties of the navigator object…• navigator.appName - name of the

browser• navigator.appVersion - version

number• navigator.userAgent - all the

necessary information

• Lots more properties (and methods)

Page 18: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 18

JavaScript 2

<body><h1>Properties of the navigator object</h1><p><script type="text/javascript">document.write('appName = ' + navigator.appName + '<br />');document.write('appVersion = ' + navigator.appVersion + '<br />');document.write('userAgent = ' + navigator.userAgent + '<br />');document.write('appCodeName = ' + navigator.appCodeName + '<br />');document.write('language = ' + navigator.language + '<br />');document.write('platform = ' + navigator.platform + '<br />');

document.write('<br /><strong>mimeTypes</strong> =<br />');for ( var i=0; i < navigator.mimeTypes.length; i++ ) { document.write(' &nbsp; ' + navigator.mimeTypes[i].type + '<br />');}document.write('<br /><strong>plugins</strong> =<br />');for ( i=0; i < navigator.plugins.length; i++ ) { document.write(' &nbsp; ' + navigator.plugins[i].name + '<br />');}</script></p></body>

navigator.html

Page 19: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 19

JavaScript 2

navigator.html

Page 20: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 20

JavaScript 2

Client-Side Browser Sniffing

• Watertight browser sniffing is very tricky• many traps for the unwary• best to copy the experts rather than try to create

your own.

http://www-archive.mozilla.org/docs/web-developer/sniffer/browser_type.html

• Adherence to standards has significantly reduced compatibility problems

• Perhaps it is time to move on and only support relatively recent browser versions• difficult to get old browser versions for testing

Page 21: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 21

JavaScript 2

Quick Quiz• When using client-side browser sniffing using

JavaScript what will happen in the case of browsers that don't understand JavaScript at all?

• When designing or using browser sniffing code you are likely to take past versions of the browsers into account. What else do you need to consider?

• How could you use client-side browser sniffing to get around HTML, CSS and DOM compatibility issues?

Page 22: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 22

JavaScript 2

Animation - walkingDog.html

repeatedly cycles through 4 static gif images:

dog0.gif, dog1.gif, dog2.gif, dog3.gif

Page 23: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 23

JavaScript 2

walkingDog.html

<script type="text/javascript"><!— // global variables

var count = 1; var speed = 500; // 500 millisecs - initial speed var timer = null; // to store the timer-id var going = false; // to keep track of dog state

// preload the images into an array to speed initial use

var dogs = new Array(4);

for ( var i=0; i < dogs.length; i++ ) { dogs[i] = new Image(); dogs[i].src = "dog" + i + ".gif"; }

Note the parentheses

Page 24: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 24

JavaScript 2

walkingDog.html

function ShowNext() { // cycle through the images document.images[0].src = dogs[count].src; count++; if ( count == dogs.length ) count = 0; timer = setTimeout("ShowNext()",speed);}

function Faster() { if ( speed > 50 ) speed -= 50;}

function Slower() { if ( speed < 2000 ) speed += 50;}// --></script>

setTimeOut returns a reference to the timer

Page 25: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 25

JavaScript 2

walkingDog.html

<body><p><img src="dog0.gif" alt="animation of a walking dog"/> </p><p><input type="button" value="Faster" onclick="Faster()"/><input type="button" value="Slower" onclick="Slower()"/> <input type="button" value="Stop" onclick="clearTimeout(timer); going = false"/> <input type="button" value="Go" onclick="if (!going){going = true; ShowNext()}"/> </p>

the first frame of the animation is loaded into the <img> tag

clearTimeOut stops the timer event

Page 26: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 26

JavaScript 2

walkingDog.html<script type="text/javascript"><!-- // Example of very simple browser sniffing

// get userAgent infovar agt=navigator.userAgent.toLowerCase();// get major version e.g "4"var is_majorVersion = parseInt(navigator.appVersion);// work out if navigator 3 upwards or IE 4 upwardsvar is_nav = ((agt.indexOf("mozilla")!=-1) &&

(agt.indexOf("compatible") == -1));var is_nav3up = (is_nav && (is_majorVersion >= 3));var is_ie = (agt.indexOf("msie") != -1);var is_ie4up = (is_ie && (is_majorVersion >= 4));

if (!is_nav3up && !is_ie4up) { alert ("Sorry this page only works with Navigator 3.0 \n" + "or Microsoft Internet Explorer 4.0 upwards.\n"); history.back();}// --></script></body>

sniff the navigator

report back to the user

Page 27: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 27

JavaScript 2

walkingDog.html• Images are preloaded into an array

• No attempt to handle older browsers

var dogs = new Array(4);for (var i=0; i < dogs.length; i++) { dogs[i] = new Image(); dogs[i].src = "dog" + i + ".gif";}

if (!is_nav3up && !is_ie4up) { alert ("Sorry this page only works with Navigator 3.0 \n" + "or Microsoft Internet Explorer 4.0 upwards.\n"); history.back();}

Each array entry is an image

Page 28: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 28

JavaScript 2

prairieDog.html

Page 29: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 29

JavaScript 2

prairieDog.htmlAnimation with Styles and Sniffing

• Styles are used here to arrange the images on the page• z-index controls the depth• rules apply to the HTML tag with the

matching id attribute value

<style type="text/css"> body {background:#FFFF99} #dogpic {position:absolute; top:200px; left:0px; z-index:2} #cactus1 {position:absolute; top:10px; left:200px; z-index:3} #cactus2 {position:absolute; top:30px; left:400px; z-index:1}</style>

Page 30: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 30

JavaScript 2

var dog;var winwidth;var isOldNav;var timer;

function initDog() { isOldNav = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5); dog = (isOldNav) ? document.dogpic : document.getElementById('dogpic').style; winwidth = (isOldNav) ? window.innerWidth : document.body.offsetWidth; dog.left = (isOldNav) ? 0 : "0px";}

prairieDog.htmlAnimation with Styles and Sniffing

Detect old navigators Decide how to

refer to the dog

And how big the window is

Set the dog coordinates

Page 31: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 31

JavaScript 2

prairieDog.htmlAnimation with Styles and Sniffing

• One function for old navigators and one for new

function walkDog() { dog.left = (25 + parseInt(dog.left)) + "px"; if ( parseInt(dog.left) > winwidth ) dog.left = "-200px"; timer = setTimeout("walkDog()", 500);}

function walkDogOldNav() { dog.left = 25 + dog.left; if ( dog.left > winwidth ) dog.left = -200; timer = setTimeout("walkDogOldNav()", 500);}

Page 32: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 32

JavaScript 2

prairieDog.htmlAnimation with Styles and Sniffing

<body onload="void initDog()"><form action="dummy"> <!-- Needed for NN4 --><p><input type="button" value="Walk the dog" onclick="(isOldNav) ? walkDogOldNav() : walkDog()" /><input type="button" value="Stop the dog" onclick="clearTimeout(timer)" /></p></form><div id="dogpic"><img src="doganim.gif" alt="dogpic" /></div><div id="cactus1"><img src="cactus1.gif" alt="cactus1" /></div><div id="cactus2"><img src="cactus2.gif" alt="cactus1" /></div></body>

onClick event handler decides which function to use

onLoad event triggers browser sniffing

Page 33: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 33

JavaScript 2

Things to notice about prairieDog.html

• A timer calls walkDog() which moves the animated gif dog image from left to right• the image moves back to the left when it reaches the

end of the browser window

• Note that the dog moves behind one cactus and in front of the other.

function walkDog() { dog.left = (25 + parseInt(dog.left)) + "px"; if ( parseInt(dog.left) > winwidth ) dog.left = "-200px"; if (walking) setTimeout("walkDog()", 500);}

Page 34: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 34

JavaScript 2

Things to notice about prairieDog.html

• This page is XHTML 1.1• so the document must contain a DOCTYPE.

• Use of a DOCTYPE causes the browser to use standard rendering so units of measurement must be specified for positioning• with IE and Opera positioning defaults to pixels• Mozilla browsers (Netscape, Firebird, etc) will not.• old Netscape browsers do not want units

• Without a DOCTYPE the browser will use quirk rendering which impersonates IE rendering• but then you can’t be strict

Page 35: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 35

JavaScript 2

Things to notice about prairieDog.html• Simple browser sniffing

• based on the properties of the navigator• Handle browser variation by testing the DOM

implementation instead of browser sniffing function initDog() { if ( document.body.offsetWidth ) { // modern browsers winwidth = document.body.offsetWidth; dog = document.getElementById('dogpic').style; dog.left = '0px'; } else if ( window.innerWidth ) { // old NN browsers winwidth = window.innerWidth; dog = document.dogpic; dog.left = 0; } else { //flag an error }}

prairieDogDomSniff.html

Page 36: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 36

JavaScript 2

Input Validation• HTML forms are used to gather user input.

• data is usually passed to server side applications• but not always

• Use JavaScript to validate user input• before it is sent to the server

• avoids unnecessary communication• reduces load on the server• provides rapid feedback to the user

• Test the data to see if it matches some pattern• so that it meets the data expectations of the

application

Page 37: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 37

JavaScript 2

Input Validation• Three aims of validation

1. protect the system• from accidental or deliberate misuse

2. filter the data• prevent incorrect data from being entered

• improve the quality of the input data

3. help the user• nobody likes filing in forms

• so provide as much help as possible

• All three should be implemented at both the client and the server

• why?

Page 38: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 38

JavaScript 2

Quick Quiz

• Why do we validate input data?

• What is the primary objective for client side validation?

• What is the primary objective for server side validation?

Page 39: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 39

JavaScript 2

mailingList.html - Input Validation

Page 40: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 40

JavaScript 2

mailingList.html - User Conformation

Page 41: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 41

JavaScript 2

mailingList.html - Server Response

Page 42: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 42

JavaScript 2

<form method="get" action="http://staffweb.cms.gre.ac.uk/~mk05/cgi-bin/mlist1.pl" onsubmit="return confirm ('Ready to submit information')" onreset="return confirm('Really clear the form?')"><p>Title <input type="text" name="Title" size="8" maxlength="8"/>Initials <input type="text" name="Initials" size="6" maxlength="6"/>Surname <input type="text" name="Surname" size="25" maxlength="25"/></p><p>Email <input type="text" name="Email" size="30" maxlength="40"/></p><p>Your computer platform(s):</p><p><input type="checkbox" name="Platforms" value="Win98"/>Windows 95/98<br /><input type="checkbox" name="Platforms" value="WinNT"/>Windows NT<br /><input type="checkbox" name="Platforms" value="Win2000"/>Windows 2000<br /><input type="checkbox" name="Platforms" value="WinXP"/>Windows XP<br /><input type="checkbox" name="Platforms" value="Unix"/>Unix/Linux<br /><input type="checkbox" name="Platforms" value="MacOS"/>Apple Macintosh<br /></p><p><input type="submit" value="Add Details" name="Sub" onclick="return Validate(this.form)"/><input type="reset" value="Reset Form"/></p><hr /></form> mailingList.html

Page 43: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 43

JavaScript 2

function Validate(theForm) { var missing = ""; if (theForm.Title.value == "") missing += "Title\n"; if (theForm.Initials.value == "") missing += "Initials\n"; if (theForm.Surname.value == "") missing += "Surname\n"; if (theForm.Email.value == "") missing += "Email\n";

var platSelected = false; for ( var i = 0; i < theForm.Platforms.length; i++ ) { if (theForm.Platforms[i].checked) platSelected = true; }

if (!platSelected) missing += "Platform\n"; if (missing != "") { alert("You missed the following essential elements\n" + missing + "Please complete and resubmit"); return false; } else return true;}

Input Validation

Page 44: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 44

JavaScript 2

Validating the Form<input type="submit" value="Add Details" name="Sub" onclick="return Validate(this.form)"/>

• The validation function Validate() is triggered when the user clicks the submit button.

• The submission will only go ahead if the onClick event handler returns true

• Validate() checks that• the Title, Initials, Surname, and Email text input boxes are not empty• at least one platform checkbox has been checked.

• Validate() builds up a list of any missing elements in the string variable missing.

• If the string is not empty then something essential is missing so it• it outputs a message in an alert box and returns false• otherwise it returns true.

Page 45: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 45

JavaScript 2

User Confirmation<form method="get" action="/~mk05/cgi-bin/mlist1.pl" onsubmit="return confirm ('Ready to submit information')" onreset="return confirm('Really clear the form?')">

• If the form passes the submission validation the onSubmit event handler will be invoked causing a confirmation prompt to appear• If the user then selects “OK” from the confirmation prompt it

returns true and the form will be submitted otherwise it won’t

• Similarly when the user clicks the reset button the form’s onReset event handler will be invoked.• If the user selects “OK” from the confirmation prompt it returns

true and the reset will go ahead otherwise it won’t

Page 46: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 46

JavaScript 2

Quick Quiz

• How could you improve the user input validation in this example?

• Test the input strings for illegal characters

• Check that the input strings look sensible• do they match a pattern?

• Use regular expressions

Page 47: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 47

JavaScript 2

Quick Quiz• Below is the JavaScript code that checks that

at least one platform has been selected. How could you change it to validate that ALL the platforms have been selected?

var anyPlatSelected = false; for (i = 0; i < theForm.Platforms.length; i++) { if (theForm.Platforms[i].checked) anyPlatSelected = true; } if (!anyPlatSelected) missing += "Platform\n";

Page 48: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 48

JavaScript 2

loginForm.html

Error messages appear in the page

Page 49: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 49

JavaScript 2

loginForm.html<form method="post" action="auth.php"><table><tr><td id="eMess">Email</td><td id="pMess">Password</td></tr><tr><td><input type="text" name="email" size="20" onblur="validateEmail(this.value)"/></td><td><input type="password" name="passwd" size="20" onblur="validatePassword(this.value)"/></td></tr><tr><td colspan="2"><input type="submit" value="Log in" onclick="return validate(this.form)"/></td></tr></table></form>

onClick event validates the whole form

onBlur event validates individual text inputs

id to identify elements for the error messages

Page 50: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 50

JavaScript 2

loginForm.js

// test for a valid email entryfunction validateEmail(emailString) { var valid = true;

if ( emailString == '' ) { feedback('eMess','Enter your email address here',7); valid = false; } else if ( !validEmailString(emailString) ) { feedback('eMess','Not a valid email address',7); valid = false; } else feedback('eMess','Email',1);

if ( valid ) return true; else return false;}

test for an empty field

feedback() used to handle messages to the user

test for a valid string

Page 51: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 51

JavaScript 2

loginForm.js

// test for a valid password entryfunction validatePassword(passwordString) { var valid = true;

if ( passwordString == '' ) { feedback('pMess','Enter your password here',7); valid = false; } else if ( passwordString.length <= 5 ){ feedback('pMess','Password too short',7); valid = false; } else feedback('pMess','Password',1);

if ( valid ) return true; else return false;}

test for an empty field

feedback() used to handle messages to the user

test for a valid string

Page 52: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 52

JavaScript 2

loginForm.js

// validate the entire formfunction validate(theForm) { var valid = true; if ( !validateEmail(theForm.email.value) )valid = false; if ( !validatePassword(theForm.passwd.value) )valid = false; if ( valid ) return true; else return false;}

// test for a valid email stringfunction validEmailString(emailString) { // regular expression works for most email strings var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (filter.test(emailString)) return true; else return false;}

regular expression does a reasonable job of trapping

invalid email strings

Page 53: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 53

JavaScript 2

loginForm.js

function feedback(item,mess,count) { // set the message text document.getElementById(item).innerHTML = mess;

// set it's colour if ( count%2 == 1 ) { document.getElementById(item).style.color = 'black'; } else { document.getElementById(item).style.color = 'white'; }

// set a timer to call this function again in 300ms count--; var f = 'feedback(\'' + item + '\',\'' + mess + '\',' + count + ')'; if ( count > 0 ) setTimeout(f,300);}

three arguments:the id of the HTML elementthe messagethe number of times to flash

what is in f?

Page 54: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 54

JavaScript 2

loginForm.html

• JavaScript can do things that are not possible with server side scripts

• React to errors as they occur• in this example using onBlur

• Even greater control is possible• could use onKeyPress to prevent illegal

characters from being entered• could force user focus back to the point of

validation failure

Page 55: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 55

JavaScript 2

AJAX• Asynchronous JavaScript and XML (AJAX)

• not a technology in itself• a "new" approach combining a number of existing

technologies• XHTML• CSS• JavaScript• DOM• XML• XSLT• XMLHttpRequest object

• Web applications that make incremental updates• without reloading the entire browser page• faster and more responsive to user actions

Page 56: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 56

JavaScript 2

AJAX

Page 57: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 57

JavaScript 2

AJAX• This example does not use XML or JSON to

communicate• Plain text is returned from checkName.php

• input is a GET parameter ‘n’• output is either ‘tooShort’, ‘taken’ or ‘available’

<?php header('Content-type: text/plain'); $userName = $_GET['n']; if ( strlen($userName) < 6 ) exit('tooShort'); $names = file('names.txt' ); foreach($names as $v) { if ( $userName == rtrim($v) ) exit('taken'); } exit('available'); ?>

Page 58: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 58

JavaScript 2

AJAX• Use an XMLHttpRequest object to check the

user input on every keypress

function CheckName(uname) { if ( window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } var httpURL = "checkName.php?n=" + uname; xhttp.open( "GET", httpURL, false); xhttp.send(); return xhttp.responseText;}

URL of the postback handler

Instantiate an XMLHttpRequest

object

Page 59: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 59

JavaScript 2

Quick Quiz

• What can you do with JavaScript that is not possible (or easy) with server side scripts ?

• What can you do with server side scripts that is not possible (or easy) with JavaScript?

Page 60: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 60

JavaScript 2

Summary• Timers used to create dynamic pages

• animation used to draw attention• Preloading rollover images

• providing visual cues to the user• Client-side form validation

• improve the user experience• reduce load on the server• do things which server scripts cannot do

• Interrogation of the navigator to cater for browser compatibility issues• being standard compliant and catering for older

browsers can get messy!

Page 61: JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus mk05/web/JavaScript/JavaScript2.html

© November 11 University of Greenwich 61

JavaScript 2

Any Questions?