Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus

Similar presentations


Presentation on theme: "JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus"— Presentation transcript:

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

2 JavaScript 2 © November 11University of Greenwich2 xmasTimer.html

3 JavaScript 2 © November 11University of Greenwich3 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

4 JavaScript 2 © November 11University of Greenwich4 Xmas countdown Days Hours Minutes Seconds <input type="text" name="txtDays" size="4" onfocus="blur()"/> <input type="text" name="txtHours" size="4" onfocus="blur()"/> <input type="text" name="txtMins" size="4" onfocus="blur()"/> <input type="text" name="txtSecs" size="4" onfocus="blur()"/> Do not allow editing of the text

5 JavaScript 2 © November 11University of Greenwich5 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

6 JavaScript 2 © November 11University of Greenwich6 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()"/>

7 JavaScript 2 © November 11University of Greenwich7 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? <!-- var time = 2000; function hello() { setTimeout("alert('hello chum')", time); time += 5000; } // -->

8 JavaScript 2 © November 11University of Greenwich8 Images in JavaScript The images[] property of a document is an array of the images included in the page using the 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

9 JavaScript 2 © November 11University of Greenwich9 rollover.html

10 JavaScript 2 © November 11University of Greenwich10 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; }

11 JavaScript 2 © November 11University of Greenwich11 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; }

12 JavaScript 2 © November 11University of Greenwich12 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"; }

13 JavaScript 2 © November 11University of Greenwich13 rollover.html <img src="/~mk05/images/hot_off.gif" alt="lightning bolt"/> 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

14 JavaScript 2 © November 11University of Greenwich14 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

15 JavaScript 2 © November 11University of Greenwich15 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

16 JavaScript 2 © November 11University of Greenwich16 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

17 JavaScript 2 © November 11University of Greenwich17 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)

18 JavaScript 2 © November 11University of Greenwich18 Properties of the navigator object document.write('appName = ' + navigator.appName + ' '); document.write('appVersion = ' + navigator.appVersion + ' '); document.write('userAgent = ' + navigator.userAgent + ' '); document.write('appCodeName = ' + navigator.appCodeName + ' '); document.write('language = ' + navigator.language + ' '); document.write('platform = ' + navigator.platform + ' '); document.write(' mimeTypes = '); for ( var i=0; i < navigator.mimeTypes.length; i++ ) { document.write(' ' + navigator.mimeTypes[i].type + ' '); } document.write(' plugins = '); for ( i=0; i < navigator.plugins.length; i++ ) { document.write(' ' + navigator.plugins[i].name + ' '); } navigator.html

19 JavaScript 2 © November 11University of Greenwich19 navigator.html

20 JavaScript 2 © November 11University of Greenwich20 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

21 JavaScript 2 © November 11University of Greenwich21 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?

22 JavaScript 2 © November 11University of Greenwich22 Animation - walkingDog.html repeatedly cycles through 4 static gif images: dog0.gif, dog1.gif, dog2.gif, dog3.gif

23 JavaScript 2 © November 11University of Greenwich23 walkingDog.html <!— // 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

24 JavaScript 2 © November 11University of Greenwich24 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; } // --> setTimeOut returns a reference to the timer

25 JavaScript 2 © November 11University of Greenwich25 walkingDog.html <input type="button" value="Stop" onclick="clearTimeout(timer); going = false"/> <input type="button" value="Go" onclick="if (!going){going = true; ShowNext()}"/> the first frame of the animation is loaded into the tag clearTimeOut stops the timer event

26 JavaScript 2 © November 11University of Greenwich26 walkingDog.html <!-- // Example of very simple browser sniffing // get userAgent info var 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 upwards var 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(); } // --> sniff the navigator report back to the user

27 JavaScript 2 © November 11University of Greenwich27 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

28 JavaScript 2 © November 11University of Greenwich28 prairieDog.html

29 JavaScript 2 © November 11University of Greenwich29 prairieDog.html Animation 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 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}

30 JavaScript 2 © November 11University of Greenwich30 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.html Animation with Styles and Sniffing Detect old navigators Decide how to refer to the dog And how big the window is Set the dog coordinates

31 JavaScript 2 © November 11University of Greenwich31 prairieDog.html Animation 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); }

32 JavaScript 2 © November 11University of Greenwich32 prairieDog.html Animation with Styles and Sniffing <input type="button" value="Walk the dog" onclick="(isOldNav) ? walkDogOldNav() : walkDog()" /> <input type="button" value="Stop the dog" onclick="clearTimeout(timer)" /> onClick event handler decides which function to use onLoad event triggers browser sniffing

33 JavaScript 2 © November 11University of Greenwich33 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); }

34 JavaScript 2 © November 11University of Greenwich34 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

35 JavaScript 2 © November 11University of Greenwich35 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

36 JavaScript 2 © November 11University of Greenwich36 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

37 JavaScript 2 © November 11University of Greenwich37 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?

38 JavaScript 2 © November 11University of Greenwich38 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?

39 JavaScript 2 © November 11University of Greenwich39 mailingList.html - Input Validation

40 JavaScript 2 © November 11University of Greenwich40 mailingList.html - User Conformation

41 JavaScript 2 © November 11University of Greenwich41 mailingList.html - Server Response

42 JavaScript 2 © November 11University of Greenwich42 <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?')"> Title Initials Surname Email Your computer platform(s): Windows 95/98 Windows NT Windows 2000 Windows XP Unix/Linux Apple Macintosh <input type="submit" value="Add Details" name="Sub" onclick="return Validate(this.form)"/> mailingList.html

43 JavaScript 2 © November 11University of Greenwich43 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

44 JavaScript 2 © November 11University of Greenwich44 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.

45 JavaScript 2 © November 11University of Greenwich45 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

46 JavaScript 2 © November 11University of Greenwich46 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

47 JavaScript 2 © November 11University of Greenwich47 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";

48 JavaScript 2 © November 11University of Greenwich48 loginForm.html Error messages appear in the page

49 JavaScript 2 © November 11University of Greenwich49 loginForm.html Email Password <input type="text" name="email" size="20" onblur="validateEmail(this.value)"/> <input type="password" name="passwd" size="20" onblur="validatePassword(this.value)"/> <input type="submit" value="Log in" onclick="return validate(this.form)"/> onClick event validates the whole form onBlur event validates individual text inputs id to identify elements for the error messages

50 JavaScript 2 © November 11University of Greenwich50 loginForm.js // test for a valid email entry function 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

51 JavaScript 2 © November 11University of Greenwich51 loginForm.js // test for a valid password entry function 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

52 JavaScript 2 © November 11University of Greenwich52 loginForm.js // validate the entire form function 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 string function 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

53 JavaScript 2 © November 11University of Greenwich53 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 element the message the number of times to flash what is in f?

54 JavaScript 2 © November 11University of Greenwich54 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

55 JavaScript 2 © November 11University of Greenwich55 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

56 JavaScript 2 © November 11University of Greenwich56 AJAX

57 JavaScript 2 © November 11University of Greenwich57 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'); ?>

58 JavaScript 2 © November 11University of Greenwich58 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

59 JavaScript 2 © November 11University of Greenwich59 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?

60 JavaScript 2 © November 11University of Greenwich60 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!

61 JavaScript 2 © November 11University of Greenwich61 Any Questions?


Download ppt "JavaScript 2 JavaScript 2 Timers, Images, Sniffing and Validation Dr Kevin McManus"

Similar presentations


Ads by Google