Copyright Penny McIntire, 2007 Things to Do with JavaScript.

Post on 28-Mar-2015

227 views 2 download

Tags:

Transcript of Copyright Penny McIntire, 2007 Things to Do with JavaScript.

copyright Penny McIntire, 2007

Things to Do with JavaScript

2

copyright Penny McIntire, 2007

Things to Do with JavaScript• Auto email with reset confirm• Auto email with data validation a

nd autofocus• Rename a button• Change background color• View URL• Set timer • Open a window

3

copyright Penny McIntire, 2007

Things to Do with JavaScript• Display date• Print page• Save and access a cookie• Sniff the browser• Data validation • Preload images• FlyoutDropdown menus

4

copyright Penny McIntire, 2007

Auto Email• You can create an html form, then

automatically email the data captured from the form…

JSAutoEmail.html

<html><head><title>Autoemail</title><script language="JavaScript"> function allowReset() { return window.confirm(“Clear the form?") }</script></head>

<body><form method=post action="mailto:pmcintire@niu.edu?

subject=Prospective Customer&body=Some standard message could go here"

onReset="return allowReset()" enctype = "text/plain">

<p>Enter your first name:</p> <input type="text" name="firstName" value = "Penny"><p> Enter your last name: <input type="text" name="lastName" value = "McIntire"><p> <input type="radio" name="gender" value = "male" checked>Male <input type="radio" name="gender" value = "female">Female <p> <input type="checkbox" name="retired">I am retired<p> <input type="reset"> <input type="submit" value = "Submit this now!"></form></body></html>

action = “mailto:…

Executes the function allowReset to double check.

7

copyright Penny McIntire, 2007

Auto Email• This confirms the reset before

clearing the form. • If the function returns true, it

resets.• If the function returns false, it does

not. • onSubmit works the same way, to

interrupt the process before sending the form to the server.

8

copyright Penny McIntire, 2007

Auto Email• “Secret” email should never be

used, and, in fact, modern versions of browsers don’t allow secret email; a window is displayed asking user permission.

• There seems to be an upper limit of 2044 characters for the content of an auto email.

9

copyright Penny McIntire, 2007

Auto Email with Editing and Autofocus

• Now let’s simplify the email part and check for empty fields as well as autofocus on appropriate fields…

JSAutoEmail2.html

<html><head><title>Auto Email with Editing and Autofocus</title>

<script language="JavaScript">function submitForm() { if (document.loginForm.firstName.value == "" && document.loginForm.lastName.value == "") {

alert( "Please enter your first and last names"); document.loginForm.firstName.focus(); return false;

} else if(document.loginForm.firstName.value == "") { alert( "Please enter your first name"); document.loginForm.firstName.focus(); return false;

} else if(document.loginForm.lastName.value == "") { alert( "Please enter your last name "); document.loginForm.lastName.focus(); return false;

} else { return true;

}} </script></head>

“Return false;” aborts the “submit” part of autosubmit.“Return true;”

submits the email.

Sets focus on empty

field.

<body onLoad="document.loginForm.firstName.focus();">

<h1>Auto Email with Editing and Autofocus</h1><form name="loginForm" method=post

action="mailto:pmcintire@niu.edu" enctype = "text/plain" onSubmit="return

submitForm()"> <p>Enter your first name:

<input type="text" name="firstName"></p> <p>Enter your last name:

<input type="text" name="lastName"></p> <input type="submit"></p></form></body></html>

onSubmit captures the submit and sends it to the function. A false return aborts the autoemail.

Sets focus on first field, when page

opens.

12

copyright Penny McIntire, 2007

Rename a Button

JSRenameButton .html

<html><head>

<script language = "JavaScript">function getButtonName(){ var newName = prompt("Rename the button, please") document.myForm.myButton.value=newName}</script></head>

<body><form name = "myForm"> <input type = "button" name = "myButton" value = “Click to rename me"

onClick="getButtonName()"></form>

</body></html>

Tracing through the DOM

Replaces the old value with the new one.

Sets up the button.

14

copyright Penny McIntire, 2007

Change Background Color

JSChangeBackground.html

<html><head><script language = "JavaScript">

function newBackColor(color) { if (color == 1) {document.bgColor="red"} if (color == 2) {document.bgColor="green"} if (color == 3) {document.bgColor="blue"}

}</script></head>

<body><h1>We love color!</h1><form> To change the background color, click on a button below:<br><br> <input type = "button" value = "red" onClick = "newBackColor(1)"> <input type = "button" value = "green" onClick = "newBackColor(2)"> <input type = "button" value = "blue" onClick = "newBackColor(3)"></form></body></html>

Changes the document property “bgColor”

16

copyright Penny McIntire, 2007

View URL

JSViewURL.html

<html><head><script language = "JavaScript">

function getURL (){

alert(“You are in document: " + document.location)}

</script></head>

<body><h1>We love URLs!</h1><form> To find out your current URL:<br><br> <input type = "button" value = "Show Me URL" onClick = “getURL()"></form></body></html>

18

copyright Penny McIntire, 2007

Timer

JSTimer.html

<html><head><script language = "JavaScript">

var myTimer function launchTimer() {

myTimer = setTimeout("alert('Sorry, your time is up!')",5000) }</script></head>

<body><h1>You must do something on this page within 5 seconds!</h1><script language = "JavaScript">launchTimer()</script>

<form name = "myForm"><input type = "button" value = “Press me to stop timer!"

onClick = “clearTimeout(myTimer)”</form></html>

5000 x 1/1000 of a second

JavaScript method

Or, <body onload="launchTimer() ">

What to do when timer fires

20

copyright Penny McIntire, 2007

Open a Window

JSOpenNewWindow.html

<html><head><script language = "JavaScript">function myNewWindow() { window.open("http://www.niu.edu",

"newWindow", "height=100,width=100,status=yes");

newWindow.focus(); }</script></head><body><h1>Open New Window</h1><form name = "myForm"> <input type = "button" value = "Open Window"

onClick = "myNewWindow()"></form></html>

(“URL”, “window name”, “parameters”)

See page 885 of DHTML.

22

copyright Penny McIntire, 2007

Display Date

JSDisplayDate.html

<html><head>

<script language = "JavaScript">

var myDate = new Date();

var myDay=myDate.getDate(), //day number in month

myDayOfWeek=myDate.getDay(), //day number in week

myMonth=myDate.getMonth(), //month number

myYear=myDate.getFullYear(); //year number

switch (myDayOfWeek) {

case 0: dayName = "Sunday"; break;

case 1: dayName = "Monday"; break;

case 2: dayName = "Tuesday"; break;

case 3: dayName = "Wednesday"; break;

case 4: dayName = "Thursday"; break;

case 5: dayName = "Friday"; break;

default: dayName = "Saturday"; break;

}

If “new Date” with no constructors, it gets

today’s date.

getYear method is unpredictable in earlier browsers because of Y2K

switch (myMonth) { case 0: monthName = "January"; break; case 1: monthName = "Februrary"; break; case 2: monthName = "March"; break; case 3: monthName = "April"; break; case 4: monthName = "May"; break; case 5: monthName = "June"; break; case 6: monthName = "July"; break; case 7: monthName = "August"; break; case 8: monthName = "September"; break; case 9: monthName = "October"; break; case 10: monthName = "November"; break; default: monthName = "December";}</script></head>

<body><script language = "JavaScript"> document.writeln("The system date looks like this..." + myDate +"<br>") document.writeln("Today's date is: " +

dayName + ", " + monthName + " " + myDay + ", " + myYear + "<br>")</script></body></html>

26

copyright Penny McIntire, 2007

Printing a Page• To print a page…<a href="#"

onClick="window.print();">Print this page

</a>

27

copyright Penny McIntire, 2007

Cookies• As your web application executes,

and perhaps links from page to page, it can be important to keep track of various pieces of information.

• For instance, a user might log in on the first page, and you might want to display that user’s name on a page he or she links to later.

28

copyright Penny McIntire, 2007

Cookies• Traditional (non-web) applications

have no trouble with this “keeping state” or handling “persistence” – they aren’t hopping from page to independent page, and even if they were, they would simply write important data out to disk.

29

copyright Penny McIntire, 2007

Cookies• It’s not so easy with web

applications.– Each document is independent and

can’t easily communicate with another document.

– “Writing out to disk” means hitting the server, which is time consuming, and it might mean storing thousands of entries on the server per day, which eats up disk space rapidly.

30

copyright Penny McIntire, 2007

Cookies• So, we have cookies.• Think of them as special, hidden

cookie jars, kept on the client, in which the client or the server can drop tidbits of information for later retrieval.

• Examples of cookie use:– When a web site remembers your

name or password. – When a shopping cart remembers

what you have already chosen as you browse from page to page.

31

copyright Penny McIntire, 2007

Cookies• There are some limitations to

cookies:– A web browser can retain a maximum

of only 300 cookies.– Only 20 may be “owned” by a given

domain (i.e., cs.niu.edu could store only 20 cookies on your machine).

– Each cookie must be under 4K in length, 2K for older browsers.

32

copyright Penny McIntire, 2007

Cookies• You can open your cookies file…

– In IE, under Temporary Internet Files

33

copyright Penny McIntire, 2007

Cookies• Cookies store:

– The domain name that created the cookie.

– Whether the server or JavaScript within the browser stored the cookie.

– Whether or not the cookie should be transported using SSL.

– The expiration date. – The name and value pair that you

want to store in the cookie…

34

copyright Penny McIntire, 2007

Cookies– For instance, if you want to save the

user’s first name, you might have a name/value pair like firstName= Penny.

35

copyright Penny McIntire, 2007

Cookies• The format of the string used to

set a cookie is as follows:document.cookie =

‘myNewCookie=value you have assigned’ + ‘expires=Friday, 30-Mar-2001 23:59:59 GMT;’

– This leaves a cookie with the name myNewCookie, with the value “value you have assigned”, which expires on March 30 at 1 second before midnight.

– Let’s look at the individual parts here…

36

copyright Penny McIntire, 2007

Cookies• ‘myNewCookie=value you have

assigned’‘name=value you have assigned’ – The value part is required.– No semicolons, commas, or blanks in the

whole “name” part, OR • Encode the value part of the pair with the

JavaScript escape() function to take care of any special characters.

• Use the unescape() function later, when retrieving the cookie, to get back to the original characters.

– If two cookies have the same name, the new one overwrites the old one.

37

copyright Penny McIntire, 2007

Cookies• ‘expires=Friday, 30-Mar-2001

23:59:59 GMT;’ – Can use the JavaScript Date object

format shown here, or use a calculation for the date and time in milliseconds since January 1, 1970, GMT.

– If this is omitted, the cookie expires automatically at the end of the session.

38

copyright Penny McIntire, 2007

Saving a Cookie• Example and code from W3C: http://www.w3schools.com/JS/

js_cookies.asp

39

copyright Penny McIntire, 2007

Sniffing the Browser and Version

• There are lots of scripts floating around to check for the browser type and version.

• If you check this, you can write completely different versions of the page for the different browsers.

• But, is this a good thing???– A maintenance nightmare to avoid

whenever possible.

40

copyright Penny McIntire, 2007

Sniffing the Browser and Version

• If you really must include something for a particular browser, if might be better to have just a single document, with small areas that check for the browser, rather than having two completely different pages.

41

copyright Penny McIntire, 2007

Sniffing the Browser and Version

• Can instead check to see if a particular feature that you’re using is supported – less of a maintenance problem.

• Example:if (document.layers) //Navigator <6.0

• In any case, there is code out there that you can download to do the sniffing. – Check www.thejavascriptsource.com .

42

copyright Penny McIntire, 2007

Data Validation• “Your task is to anticipate every

possible entry that users could make and let through only those your scripts can use.” Danny Goodman

• Also, use checkboxes and radio buttons whenever possible, to ensure that invalid data entry doesn’t occur.

43

copyright Penny McIntire, 2007

Data Validation• Verifying just before the form is

submitted:– Use the onSubmit = event on the form

to execute a function that does final validation.

• Example: checking if a field is all digits…

function isDigits(inString){ if(inString.value.length == 0)

return false;

for(i=0; i < inString.length ; i++) { char = inString.substring(i, i+1);

if (char > "9" || char < "0") return false; } return true;}

45

copyright Penny McIntire, 2007

Preloading Images• Preload images

– When a user mousesover a button for the first time, the mouseover effect could take a while to show up if it has to wait for the image to download.

– As an alternative, download all of the images for the page when the page itself downloads, so they are all ready and waiting.

– Code for this is automatically done by Dreamweaver unless you deliberately tell it not to add the code…

46

copyright Penny McIntire, 2007

Preloading Imagesfunction MM_preloadImages()

• Good luck understanding Dreamweaver’s code. Nonetheless, it works.

• Essentially, onLoad in the <body> calls the function to reference each image that doesn’t appear on the original page (like rollover images), which forces a download of the image right then, instead of waiting until the user mouseovers.

47

copyright Penny McIntire, 2007

Flyout/Drop Down Menus• Two easy (?) ways to do this:

– Go to The JavaScript Source and copy in one of their cross-browser scripts.

– Use Dreamweaver’s Show/Hide Layers; i.e., create semi-manually.

– Use Dreamweaver Window > Behaviors to create automatically. • Fairly reliable in last couple of versions?• Still need to tweak the CSS so that the

dropdowns fit with the look of your page.

48

copyright Penny McIntire, 2007

Resources• http://www.damienmjones.com/wo

rk/obfuscator.htm email address obfuscator, so that spammers can’t harvest email addresses from mailto: links.

• http://news.yahoo.com/rss/ Example of how RSS can be used.