Download - 1 CS 21A Beginning JavaScript Programming Project 1 Integrating JavaScript and HTML Sonny Huang
1
CS 21A • Beginning JavaScript
Programming
Project 1 Integrating JavaScript and HTML
Sonny Huang
2
Project 1 Integrating JavaScript and HTML
Outline Discuss how to integrate JavaScript and HTML Insert SCRIPT tags on a Web page Write beginning and ending SCRIPT tags Define and use flickering to draw attention Describe the background color property of the document object Set the background color of a Web page using JavaScript Save the HTML file Test the Web page Discuss JavaScript variables
3
Project 1 Integrating JavaScript and HTML
Outline Extract the system date Use several variables to construct a message Describe the write() method of the document object Write a user-defined function that displays a message and links viewers to a new site Describe how the setTimeout() method works Use the lastModified property to display the last modified document date Print an HTML Notepad file
4
Introduction
Introduction
www.bmwusa.com.
Advanced features of JavaScript and HTML will be able to combine HTML style sheets and JavaScript to create dynamic pages.
5
Introduction
Electronic commerce(E-commerce)• Conducting business on-line. This includes, for
example, marketing, buying and selling products and services with digital cash and via Electronic Data Interchange (EDI).
• More about e-commerce: http://www.outsourcing-journal.com/issues/apr1998/insight.html
6
Introduction
Domain NameA name that identifies one or more IP addresses. For example, the domain name microsoft.com represents about a dozen IP addresses.
Domain names are used in URLs to identify particular Web pages. For example, in the URL http://www.pcwebopedia.com/index.html, the domain name is pcwebopedia.com.
Every domain name has a suffix that indicates which top level domain (TLD) it belongs to. There are only a limited number of such domains.
7
Introduction
. For example: • gov - Government agencies • edu - Educational institutions • org - Organizations (nonprofit) • mil - Military • com - commercial business • net - Network organizations • ca - Canada • th - Thailand
Because the Internet is based on IP addresses, not domain names, every Web server requires a Domain Name System (DNS) server to translate domain names into IP addresses.
8
Introduction
JavaScript(Object based language)• Uses built-in objects, but is not capable of creating
classes of objects or using inheritance features of object-oriented languages.
• Has predefined properties, methods, and event handlers
• Object is a person, place, or thing.
• Properties are attributes of objects and describe some aspect about the object.
• Methods are actions.
9
Introduction
See Page J A.7 in appendix A for a more detail list of objects
10
Introduction
An event is the result of a user’s action.
Event handlers are the way to associate that action with the set of JavaScript codes we want to execute.
J A.5 in Appendix A for a more detail list of event handlers.
11
Project One – Fun with Phonics Web Page
• Create a web page that will display a message to inform the user that the web site location has been moved.
• There will have a link to the new web sit and also, within seconds will generate a alert message to inform the user to transfer to the new location
12
Project One – Fun with Phonics Web Page
An event is the result of a user’s action.
Event handlers are the way to associate that action with the set of JavaScript codes we want to execute.
J A.5 in Appendix A for a more detail list of event handlers.
13
Project One – Fun with Phonics Web Page
14
Project One – Fun with Phonics Web Page
<HTML><HEAD> <TITLE>Fun with Phonics</TITLE><SCRIPT LANGUAGE="JAVASCRIPT"><!--Hide from old browsers function chngSite() { alert("You are about to be transported to the new site
location!") location = "http://www.scsite.com/" }//--></SCRIPT>
</HEAD>
15
Project One – Fun with Phonics Web Page
<BODY><CENTER><IMG SRC="fun.jpg" HSPACE=5
VSPACE=5 HEIGHT=64 WIDTH=129></CENTER>
<CENTER><HR Width="75%"></CENTER><SCRIPT LANGUAGE="JAVASCRIPT"><!--Hide from old browsers document.bgColor="red" document.bgColor="white" document.bgColor="blue" document.bgColor="white" document.bgColor="green" document.bgColor="white" document.bgColor="blanchedalmond"
16
Project One – Fun with Phonics Web Page
var tNow = new Date() var tlocDate = tNow.toLocaleString() var tDate = tlocDate.substring(0,10) document.write("<H2><CENTER>Welcome, today is
"+tDate+"</CENTER></H2>") var intro1 = "Hi, thanks for visiting our Web site, but
we have moved. Please make a note " var intro2 = "of our new URL (www.funphonics.com)
and notify the Webmaster about our new " var intro3 = "location. Click<A
Href='http://www.scsite.com/'> here </A> or wait 15 seconds "
var intro4 = "to be moved automatically to our new site."
var introMsg = intro1+intro2+intro3+intro4
17
Project One – Fun with Phonics Web Page
document.write("<H4><Font Color='firebrick'>"+introMsg+"</H4></FONT>")
setTimeout("chngSite()",15000) document.write("<BR><H4><CENTER>This
document was last modified "+document.lastModified+"</CENTER></H4>")
//--></SCRIPT>
</BODY></HTML>
18
Project One – Fun with Phonics Web Page
Starting Notepad
19
Project One – Fun with Phonics Web Page
Notepad Window
20
Project One – Fun with Phonics Web Page
Display the .htm files
21
Project One – Fun with Phonics Web Page
Searching the proper folder to locate fun.htm file.
22
Project One – Fun with Phonics Web Page
We will see the contents of the file as follow displayed.
23
Inserting Script Tags on a Web Page
We can place JavaScript code anywhere in the HTML code
Common Agreed:1. User-defined JavaScript functions should place at the HEAD section.2.Even handlers or other JavaScript code should place at the BODY section.
JavaScript section begins with <SCRIPT> tag and end with </SCRIPT> tag.
24
Inserting Script Tags on a Web Page
Writing the Beginning SCRIPT Tag
<SCRIPT LANGUAGE="JAVASCRIPT"><!--Hide from old browsers
Language: to define the version of JavaScript. If it is not defined, the default is JavaScript.
HTML comment line: to hide any script language that a browser may not be able to interpret.
25
Inserting Script Tags on a Web Page
Put the JavaScript tag at the BODY section.
26
Inserting Script Tags on a Web Page
Put “<SCRIPT LANGUAGE="JAVASCRIPT"><!--Hide from old browsers “ codes in the area.
27
Using a Flicker on a Web Page to Draw Attention
Using the changes of background color to capture attentions.
BGCOLOR is one of the attribute of <BODY> tag. But the background color can be set only once.
JavaScript DOCUMENT object’s BGCOLOR property can be used to change the background color.
document.bgColor = value
To set the background color to red : document.bgColor="red"
28
Using a Flicker on a Web Page to Draw Attention
Placing several of these statements in sequence will create a flicking effect.
document.bgColor="red" document.bgColor="white" document.bgColor="blue" document.bgColor="white" document.bgColor="green" document.bgColor="white" document.bgColor="blanchedalmond"
29
Using a Flicker on a Web Page to Draw Attention
Placing place two of these statements in sequence will create a flicking effect.
document.bgColor="red" document.bgColor="white" Closing the comment and SCRIPT tag as follow:
//--></SCRIPT>
30
Using a Flicker on a Web Page to Draw Attention
Closing the comment and SCRIPT tag as follow:
//--></SCRIPT>
Save it as a new name funwithphonics.htm.
31
Using a Flicker on a Web Page to Draw Attention
Run with a browser.
32
Using a Flicker on a Web Page to Draw Attention
Put more of of these statements in sequence will create a better flicking effect.
document.bgColor="blue" document.bgColor="white" document.bgColor="green" document.bgColor="white" document.bgColor="blanchedalmond“
33
Using a Flicker on a Web Page to Draw Attention
Save the file again, and try it on a browser.
34
Using a Flicker on a Web Page to Draw Attention
The final screen should look like this.
35
JavaScript Variables
var A statement that declares a variable, optionally initializing it to a value. The scope of a variable is the current function or, for variables declared outside a function, the current application.
Using var outside a function is optional; you can declare a variable by simply assigning it a value. However, it is good style to use var, and it is necessary in functions if a global variable of the same name exists.
36
JavaScript Variables
Syntax var varname [= value] [..., varname [= value] ]
Arguments varname is the variable name. It can be any legal identifier. value is the initial value of the variable and can be any legal expression.
37
JavaScript Variables
JavaScript variables are case sensitive and follow rules as in following table.
38
JavaScript Variables
•JavaScript is a loosely typed language. That means you do not have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution.
•Literals•You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. There are Integers literals (Decimal, Octal, and Hexadecimal), Floating-point literals, Boolean literals (true and false), and String literals( enclosed in double (") or single (') quotation marks.
39
JavaScript Variables
We can declare a variable in two ways: •By simply assigning it a value; for example, x = 42 •With the keyword var; for example, var x = 42
When we set a variable identifier by assignment outside of a function, it is called a global variable, because it is available everywhere in the current document.
When we declare a variable within a function, it is called a local variable, because it is available only within the function. Using var is optional, but we need to use it if we want to declare a local variable inside a function that has already been declared as a global variable.
40
Extracting the System Date
JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications.
The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.
JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00.
41
Extracting the System Date
To create a Date object: dateObjectName = new Date([parameters])
where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.
The parameters in the preceding syntax can be any of the following: •Nothing: creates today's date and time. For example, today = new Date().
•A string representing a date in the following form: "Month day, year hours:minutes:seconds."
42
Extracting the System Date
For example, Xmas95 = new Date("December 25, 1995 13:30:00"). If you omit hours, minutes, or seconds, the value will be set to zero.
•A set of integer values for year, month, and day. For example, Xmas95 = new Date(95,11,25). A set of values for year, month, day, hour, minute, and seconds. For example, Xmas95 = new Date(95,11,25,9,30,0).
43
Extracting the System Date
We can use toLocalString() to convert the un-manipulated date objects to a manipulated data string.
And using substring method to abstract the needed information.
44
Extracting the System Date
stringName.substring(indexA, indexB)
Parameters stringName is any string or a property of an existing object. indexA is any integer from zero to stringName.length - 1, or a property of an existing object. indexB is any integer from zero to stringName.length, or a property of an existing object.
Description Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1.
45
Extracting the System Date
•If indexA is less than indexB, the substring method returns the subset starting with the character at indexA and ending with the character before indexB.
•If indexA is greater than indexB, the substring method returns the subset starting with the character before indexB and ending with the character at indexA.
•If indexA is equal to indexB, the substring method returns the empty string.
46
Extracting the System Date
var tNow = new Date() var tlocDate = tNow.toLocaleString() var tDate = tlocDate.substring(0,10)
M M / D D / Y Y Y Y H H : M M : S S
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
47
Extracting the System Date
Start to insert code from the cursor point.
48
Extracting the System Date
Inserting the following codes var tNow = new Date() var tlocDate = tNow.toLocalString() var tDate = tlocDate.substring(0,10)
49
Extracting the System Date
Some methods for Date objects:
getDate Method. Returns the day of the month for the specified date.
Syntax dateObjectName.getDate()
Parameters dateObjectName is either the name of a Date object or a property of an existing object.
50
Extracting the System Date
Description The value returned by getDate is an integer between one and 31.
Examples The second statement below assigns the value 25 to the variable day, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:00")day = Xmas95.getDate()
51
Extracting the System Date
getMonth Method. Returns the month in the specified date.
Syntax dateObjectName.getMonth()
Parameters dateObjectName is either the name of a Date object or a property of an existing object.
Description The value returned by getMonth is an integer between zero and 11. Zero corresponds to January, one to February, and so on.
52
Extracting the System Date
Examples The second statement below assigns the value 11 to the variable month, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:00")month = Xmas95.getMonth()
53
Extracting the System Date
getYear Method. Returns the year in the specified date.
Syntax dateObjectName.getYear()
Parameters dateObjectName is either the name of a Date object or a property of an existing object.
Description The getYear method returns either a two-digit or four-digit year:
54
Extracting the System Date
•For years prior to 2000, the value returned by getYear is the year less 1900. For example, if the year is 1976, the value returned is 76. •For the years 2000 and beyond, the value returned by getYear is the four-digit year. For example, if the year is 2026, the value returned is 2026.
Examples The second statement below assigns the value 95 to the variable year, based on the value of the Date object Xmas95. Xmas95 = new Date("December 25, 1995 23:15:00")year = Xmas95.getYear()
55
Extracting the System Date
We can using the following codes to replace the previous codes: sysDate = new Date()newDate1 = (sysDate.getMonth()+1) + “/”newDate2 = sysDate.getDate() + “/”newDate3 = sysDate.getYear newDate = newDate1+ newDate2+ newDate3document.write("<H2><CENTER>Welcome, today is "+newDate+"</CENTER></H2>")
56
Displaying the Current System Date
writeln Method. Writes one or more HTML expressions to a document in the specified window and follows them with a newline character.
Syntax document.writeln(expression1 [,expression2], ...[,expressionN])
Parameters •expression1 through expressionN are any JavaScript expressions or the properties of existing objects.
57
Displaying the Current System Date
Description The writeln method displays any number of expressions in a document window. You can specify any JavaScript expression, including numerics, strings, or logicals.
The writeln method is the same as the write method, except the writeln method appends a newline character to the end of the output. HTML ignores the newline character, except within certain tags such as <PRE>.
Use the writeln method within any <SCRIPT> tag or within an event handler. Event handlers execute after the original document closes, so the writeln method will
58
Displaying the Current System Date
implicitly open a new document of mimeType text/html if you do not explicitly issue a document.open() method in the event handler.
Examples All the examples used for the write method are also valid with the writeln method.
window2=window.open('','window2')beginComment="\<!--"endComment="--\>"window2.document.write(beginComment)window2.document.write(" This some text inside a comment. ")window2.document.write(endComment)
59
Displaying the Current System Date
ConcatenateIt means to joint or link together strings.
document.write("<H2><CENTER>Welcome, today is "+tDate+"</CENTER></H2>")
60
Displaying the Current System Date
Put document.write("<H2><CENTER> Welcome, today is "+tDate+"</CENTER></H2>") into the body of the JavaScript
61
Using Several Variables to Construct a Message
Older browsers have a limit of 255 characters to a line. Thus it is recommended that we break up large groups of text by using several variables to construct a message.
var intro1 = "Hi, thanks for visiting our Web site, but we have moved. Please make a note “
var intro2 = "of our new URL (www.funphonics.com) and notify the Webmaster about our new “
var intro3 = "location. Click<A Href='http://www.scsite.com/'> here </A> or wait 15 seconds “
var intro4 = "to be moved automatically to our new site."
62
Using Several Variables to Construct a Message
Concatenate those variables and assign to a variable
var introMsg = intro1+intro2+intro3+intro4
63
Writing the Message on the Web Page
Using the document.write method to display the message on the document.
document.write("<H4><Font Color='firebrick'>“ + introMsg + "</H4></FONT>“ )
64
Save and Test the Web Page
Click on the File menu and Save to save the file.
65
Save and Test the Web Page
Test the Web Page in a browser.
66
Calling a JavaScript Function
JavaScript uses two methods to call function. One uses even handlers and object methods, and the other uses a logical execution point to call the user define function.
setTimeout() is one of the window object’s methods. It evaluates an expression after the specified time.
67
Calling a JavaScript Function
The chngSite(),user defined function, will be executed after 15 seconds delay.
Insert the setTimeout("chngSite()",15000) into the script.
68
Displaying the Last Modified Document Date
The lastModified is an useful document property which will display the date the document was last modified.
Using the document.write("<BR><H4><CENTER>This document was last modified "+document.lastModified+"</CENTER></H4>") to display the document last modified message.
69
Writing a JavaScript User-Defined Function
An user-defined functionA statement that declares a JavaScript function name with the specified parameters param. Acceptable parameters include strings, numbers, and objects.
To return a value, the function must have a return statement that specifies the value to return. You cannot nest a function statement in another statement or in itself.
All parameters are passed to functions, by value. In other words, the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.
70
Writing a JavaScript User-Defined Function
Syntax function name([param] [, param] [..., param]) { statements }
Arguments name is the function name. param is the name of an argument to be passed to the function. A function can have up to 255 arguments.
Examples //This function returns the total dollar amount of sales, when//given the number of units sold of products a, b, and c.function calc_sales(units_a, units_b, units_c) { return units_a*79 + units_b*129 + units_c*699}
71
Writing a JavaScript User-Defined Function
Table 1-8 is a list of JavaScript built-in functions. See Appendix A for a complete list.
72
Writing a JavaScript User-Defined Function
The general form of the user defined function.
73
Writing a JavaScript User-Defined Function
Naming conventions for functions are similar to those of variables.
74
Writing a JavaScript User-Defined Function
alert Method of window object. Displays an Alert dialog box with a message and an OK button.
Syntax alert("message")
Parameters message is any string or a property of an existing object.
75
Writing a JavaScript User-Defined Function
Description Use the alert method to display a message that does not require a user decision. The message argument specifies a message that the dialog box contains. Although alert is a method of the window object, you do not need to specify a windowReference when you call it. For example, windowReference.alert() is unnecessary.
76
Writing a JavaScript User-Defined Function
Other methods use dialog boxes.
77
Writing a JavaScript User-Defined Function
<SCRIPT LANGUAGE="JAVASCRIPT"><!--Hide from old browsers function chngSite() { alert("You are about to be transported to the new site location!") location = "http://www.scsite.com/" }//--></SCRIPT>
The location statement will be executed after finishing up the alert() method.
78
Placing User-Defined Functions in the HEAD Section
Insert the script before the end of the head tag(</HEAD>).
79
Placing User-Defined Functions in the HEAD Section
80
Placing User-Defined Functions in the HEAD Section
Save it and display on a browser.
81
Placing User-Defined Functions in the HEAD Section
Save it and display on a browser.
82
Printing the HTML File Using Notepad
83
Printing the HTML File Using Notepad