xp tutorial 10 section 1 1 programming with javascript
Post on 17-Jan-2016
222 Views
Preview:
TRANSCRIPT
XP
Tutorial 10 Section 1
1
Programming with JavaScript
XP
Sec 10.1Sec 10.1
Introducing JavaScriptHistory<script> ElementBasic JavaScript SyntaxWrite Text to a Web Page
2
XP
Introducing JavaScriptServer-side programs are placed on the
server that hosts a Web siteAdvantage: Access to databases not on
client’s computerDisadvantage: Subject to limitations placed
on server by system administratorsClient-side programming runs programs on
each user’s computerAdvantage: Not subject to server limitationsDisadvantage: Not able to access online
databases
3
XPIntroducing JavaScript
Server-Side Programming
Client-Side Programming
4
XPThe Development of JavaScriptJavaScript is a subset of JavaDifferences between Java and JavaScript:Java is a compiled languageJavaScript is an interpreted language
An interpreted language can be run directly without compiling, therefore JavaScript code can be inserted directly into an HTML or XHTML document
Not as powerful as Java, but easier to use
5
XPComparing Java and JavaScript
6
XP
The Development of JavaScript
Jscript is a version of JavaScript supported by Internet Explorer
The European Computer Manufacturers Association (ECMA) develops scripting standardsThe standard is called ECMAScript but browsers still generally call it JavaScript
7
XPWorking with the Script ElementA JavaScript program can either be placed
directly in a Web page file or saved in an external text file
Insert a client-side script in a Web page when using the script element<script type="mime-type">
script commands
</script>
8
XPInserting JavaScript into a Web Page FileEach statement—also known as a
command—is a single line that indicates an action for the browser to take
The semicolon notifies the browser that it has reached the end of the statement
9
XP
Writing Output to the Web PageAn object is any item—from the browser
window itself to a document displayed in the browser to an element displayed within the document.The document displayed in the web pageThe browser windowThe browser itself The URL of the current web pageA paragraph, a table, an imageEtc . . ..
Note from this point on you MUST remember, and adhere to, the rules of case sensitivity. Your programs will not work if you do not.
A method is a process by which JavaScript manipulates or acts upon the properties of an objectdocument.write();10
XPWriting Output to the Web Page
To write text to a Web page, use the following JavaScript commands:document.write(“text”);
You can use the document.write method to generate HTML code
11 200_pg-573-document-write.htm
XPJavaScript SyntaxJavaScript is case sensitive (Personal note: the bane of my
existance )document.write(“Hi there”); will workDocument.write(“Hi there”); will not workdocument.Write(“Hi there”); will not work etc. etc. etc.
Ignores most occurrences of extra white spaceJavaScript Rule: Do not break a statement into several
linesIf you must break lines use the continuation character: \document.write("<a
href='mailto:web2@kapple01.com'>Web2@kapple01.com</a>");
document.write("<a href='mailto:web2@kapple01.com'> " \"Web2@kapple01.com </a>");You cannot use this technique in the middle of a quote or
field12 205_pg-576-breaking-lines.htm
XP
13
•Go to my Web site and download the files for Tutorial 3
•http://www.kapple01.com/ccm/web2/home/web2_labdata.html
•Unzip the files into a work folder on your flash drive
•Go to pg 563in text book and start the in-chapter exercise.
•Stop when you get to the end of the section on page 577
XP
Tutorial 10 Sections 2 and 3
14
Programming with JavaScript-2
XP
Sec 10.2Sec 10.2
VariablesData TypesJavaScript function
15
XPDeclaring a JavaScript VariableA variable is a named item in a program that
stores information
You can declare variables with any of the following JavaScript commands:
var variable;var variable = value;variable = value;
Rules for JavaScript variable names:First character must be a letter or an underscoreRemaining characters – letters, numbers or
underscores (no spaces)Can not use “reserved words” (e.g. function, var, return )
Case Sensitive16
Creates a variable without assigning any value.
Creates a variable and assigns a value.
Creates a variable and assigns a value.
XPJavaScript Variables and DataA JavaScript variable type is determined by its
contents:
Numeric variables
String variables
Boolean variablesBoolean variables can only have two values: true or false
Null variables
If a variable is declared with one type of content and later a different type of content is assigned, the variable’s type changes. (“weakly-typed” language)
17
(has no value)
Note these are
different
XPJavaScript Syntax
The + symbol has three uses in JavaScript1. Used in arithmetic operations to perform
addition.var num1 = 5, num2 = 10, total;
total = num1 + num2;
2. Used as a literal:document.write("The value of num1 + num2 is:
", total)
3. Used to concatenate several text strings into a single text string.
var name="John Doe";
document.write("Hello there " + name + " how are you?");(Note the space after the word there and before the word how)
Another way to do this would be to use commas to separate the values
document.write("Hello there", name, "how are you?");18 206_pg-581-concatenate-strings.htm
XPJavaScript Syntax
If you need to combine a variable with a literal you need to concatenate.
What if you have five image files: file1.jpg, file2.jpg, file3.jpg, file4.jpg, file5.jpg
Now, let’s say you want to set the file name up as a variable.
var myvar = "file1";
document.write(myvar + ".jpg");
Will generate: file1.jpg
Now for a more complex example
19
207_pg-581-concatenate-variables-simple.htm
208_pg-581-concatenate-variables-complex.htm
XPJavaScript Syntax
Beyond the scope of this text so briefly:Sometimes you may need to use the + sign to
take two variables and create a new variable name:
var name=image;var num = 01;var newvar = name + num;document.write("The newvar = ", newvar);
20
209_pg-581-concatenate-to-create-new-variables.htm
XPA JavaScript Function
A function is a collection of commands that performs an action or returns a valueOther languages might use the term: subroutine, or
procedureA function name identifies a functionParameters are values used by the function
{
function commands
}The function is executed only when called by another
JavaScript command
21 210_pg-583-first-function.htm
reserved wordfunction
functionname parameters
XPJavaScript Function
22 Parameters – correspond to userName and emServer in the function definition.
call to the showEM() function
reserved wordfunction
functionname parameters
212_pg-583-function-with-parm.htm
XPJavaScript Variable ScopeA variable declared within a function has
“local” scope and can only be used inside that function.
A variable declared not inside any function has “global” scope and can be used by any script in the web page.
23
Variable loop_count has global scope. It can be used anywhere on the document
Variable my_toggle has local scope withinthe flipImages() function.. It can only be used in the flipImages() function
215_pg-589-scope.htm
XPJavaScript Returning valuesIt is very common to invoke a script that needs to
perform some kind of calculation and return a value.
For instance, what if you wanted a function that would calculate the area of a rectangle.
You might pass the function two parameters, a length and a width. The function would then calculate the area and return the answer using the return statement.function areaCalc(length, width) {
var area = length * width;return area;}document.write("area of 4x5 rectangle: " + areaCalc(4,5));
24 220_pg-588-returning-values.htm
XP
Review for Case Study – Functions and Variables
Insert a command to write the HTML code:<td>My favorite comic is: comicbook I read it every month.</td>
Where comicbook is the text string returned by the getComic() function.
The important point to understand is that comicbook is not a literal text string. It is a variable. This is standard text-book notation: words in italics, usually mean they are variables.
25
221_case-review-no-function.htm
222_case-review-function-and-variable.htm
223_case-reivew-function-no-variable.htm
XP
Review for Case Study – Functions and Variables
Taking it one step further, if you want to take a variable and concatenate it to a text string where both double and single quotes are needed, you really need to concentrate on getting the quotes right.
Let's say, instead of simply generating text output you wanted to generate an image tag like this:<img src='images/myComic.jpg' alt='myComic' />;
Where myComic is output from the getImage() function and is concatenated to .jpg
The challenge is two-fold. First the document.write() function requires double-quotes around the whole string and the src attribute requires single quotes around the src, but you CANNOT quote variables; that is, myComic cannot be quoted
26
224_case-review-concat-variable-to-literal.htm
XP
27
•Go to pg 578 in text book and continue the in-chapter exercise.
•Stop when you get to the end of the section on page 589
XP
Sec 10.3Sec 10.3
External JavaScript FileJavaScript CommentsBasic JavaScript Debugging Techniques
28
XPAccessing an External JavaScript File
The code to access an external script file is:
<head>
<script src="url" type=“text/javascript"></script>
</head>
url specifies the external file that contains the scripts
Place all script elements that reference external files in the document <head> section.
29
XP
Accessing an External JavaScript File
30
mpl.htm contains a <script> element in the head section linking it to spam.js
This allows mpl.htm to use functions and variables located in spam.js
XPCommenting JavaScript CodeJavaScript comment symbols can be like this /* … */
or like this // …
31
Marks the rest of the line as a comment
Marks the everything between the opnening and closing symbols as a comment
XPNon-JavaScript Browsers
32
Some older browsers do not support JavaScriptNon-JavaScript browsers might display the
JavaScript code as text in the browser.HTML and JavaScript comments are used to
hide JavaScript from non-JavaScript browsers
The <noscript> element can be used to display alternate content for non-JavaScript browsers:
JavaScript-capable browsers ignore this.
XP
Debugging JavaScript Errors
There are three types of errors:1. Load-time errors – interpreter can not understand
the code
2. Run-time errors – operation failed (e.g. tried to add a numeric value to a text variable.)
3. Logical errors – Load and Run OK but output is wrong (e.g. the emServer variable contains a value of “cadler” instead of “mpl.gov”) (example from in-chapter exercise)33
XPDebugging JavaScript Programs
An alert dialog box is sometimes used as a debugging aid.
34
Internet Explorer Firefox
225_pg-599-alert-dialog.htm
XP
Debugging Your JavaScript Programs
If you are running Internet Explorer 8 the debugging tools are included. If you are running IE 7 you will have to download and install the free Microsoft Script Debugger from the MS Web site.The IE 8 version seems pretty helpful, the IE 7 version, not as
helpfulIn either case, however, you will have to make sure that
Script Debugging is enabled on your browser:Tools Menu: Internet Options: Advanced Tab: Browsing Group
Make sure that “Disable Script Debugging (Internet Explorer)” and “Disable Script Debugging (other) is not checked
If you are running Firefox, when you encounter an error, you have to open the Error Console: Tools menu: Error ConsoleBetter than nothing, but not as helpful as the IE 8 debugger
35
XPDebugging Your JavaScript ProgramsMicrosoft offers the Microsoft Script
DebuggerFirefox also provides the Firefox Error
Console
36 226_pg-601-firefox-error-console.htm
XPThe End
37
top related