Title: Programming with JavaScript Tutorial 10
1Programming with JavaScriptTutorial 10
2Agenda
- Learn about fundamentals of client-side scripting
with JavaScript - Standards
- Where to put it
- Variables and data
- expressions and operators
- conditional statements
- program loops
- JavaScript functions
- Using hands-on labs as we go
3JavaScript is Client-Side Program
- Functionality that doesnt require server
- Test data locally before uploading to server
- Object-based but not object-oriented
- Interpreted high-level language (like HTML)
- Supposedly interpreted line-by-line but browser
reads ahead stops loading page if too many
JavaScript errors - Developed by Microsoft Netscape after Java
- Many users fear security of downloading applets
- JavaScript subset of Java
- IE supports JScript -slightly different version.
- Therefore need to test scripts on both IE
Firefox
4Comparison of Java JavaScript
5JavaScript standards NOT W3C but ECMAScript
- European Computer Manufacturers Association
(ECMA) responsible standard - ECMA standard called ECMAScript
- though browsers still refer to it as JavaScript.
- ECMA-262, is supported by the major browsers.
- http//www.ecma-international.org/publications/sta
ndards/Ecma-262.htm - Standards document http//www.ecma-international.
org/publications/files/ECMA-ST/Ecma-262.pdf - http//en.wikipedia.org/wiki/ECMAScript
- W3C has section on scripts http//www.w3.org/TR/h
tml4/interact/scripts.html
6Elements of JavaScript
- Variables and their values
- Expressions manipulate those values
- Control structures, which modify how statements
are performed - Functions, which execute a block of statements
- Objects and arrays, which are ways of grouping
related pieces of data together
7Working with Variables Data
- A variable is a named element in a program that
stores information. - Variables can store information created in one
part of a program for use in another part of the
program. - variable names
- case-sensitive
- Start with a letter or underscore character ( _ )
- rest can be letters, numbers, underscore
characters - No spaces in var name
- NO JavaScript reserved words, such as
- for
- length
- while
8Variable Value types
- Number any numeric value
- String characters inside quotes
- Boolean true or false
- Null empty meaningless
- Object any value associated with the object
- Function value returned by a function
9Declare a Variable in several ways (including bad
spelling)
- Before you can use a variable in your program,
you need to create it also known as declaring a
variable. - using the var command with or without assigning a
value - Var month
- var month December
- OR by assigning the variable a value somewhere on
page - .Month December
10JavaScript variable Operators
11Variable Assignment Operators
- xy sets x y
- x x y sets x to x plus y
- xy same as x xy
- cab sets c equal to a b
- cay sets c equal to a times y
- ay same as a a times y
- a/y divides a on left by y assigns result to
same as aa/y - ca y sets c modulus of a divided by y
- a/y same as a modulus of a/y
12Comparison Operators
- xy returns true if x and y are equal
- x!y returns true if x and y are not equal
- xgty returns true if x is great than y
- xlty returns true if x is less than y
- xlty returns true if x is less than or equal to
y - xgty returns true if x is greater than or equal
to y - xy returns true if both x and y are true
- xy returns true if either x or y is true
- !x returns true if x is false
13Where to put scripts?
- Within HTML page within ltscriptgt tags
- Within ltheadgt tags preferred - easiest to find
- Anywhere on page
- Hide script from old browsers
- ltscript languageJavaScript type"text/javascrip
t"gt - lt!- Hide from non-JavaScript browsers
- JavaScript commands
- // Stop hiding from older browsers-gt
- lt/scriptgt
- External JavaScript file in .js file
- Prevents users from seeing script
14Syntax for ltscriptgt Tag calling external js file
- ltscript src"external.js" language"Javascript"
type"text/javascript"gt - lt!-- Hide script from old browsers
- function imgOver()
- function imgOut()
- // End hiding script --gt lt/scriptgt
- src location of external js document contains
program code - Required only if external JavaScript file
- Code for functions is contained in external js
file - language -- language written in Jscript is
default - Type is required for XHTML
- lt! Comment so page loads in earlier browsersgt
- Comment inside JavaScript // JavaScript comment
15Script intro Create feedback Alert Box
- Download javascript template, save, and type in
JavaScript below http//www.csupomona.edu/llsoe/
311/examples/javascriptemplate.htm - ltheadgtltscript language"Javascript"
type"text/javascript"gt lt!-- Hide script from
old browsers alert("Welcome to my JavaScript
page!") // End hiding script from old browsers
--gt lt/scriptgt - lt/headgt
- ltbodygt
- ltnoscriptgt
- lth2gtThis page requires JavaScript.lt/h2gt
- lt/noscriptgt
- lt/bodygt
- Save page, view in browser, validate for XHTML
16Conditional Operators Program Control Flow
If...Else Statement
- The If statement runs set of commands if
condition is true. - May run another set of commands if condition is
false - The general syntax is
- if (condition)
- JavaScript Commands if true
- else
- JavaScript Commands if false
-
- condition is an expression that is either true or
false, and one set of commands is run if the
expression is true, and another is run if the
expression is false
17Using if .. Else statement confirming users
choice use javascripttemplate.htm
- Type in this script within script tags
- if (confirm("Are you sure you want to do that?"))
- alert("You said yes")
-
- else
- alert("You said no")
-
- confirm() method takes one parameter returns
true or false, depending on users response - Alert displays message depending on results
returned by confirm() method - Curly braces not required but help structure
code
18Using if .. Else statement to prompt users
input use javascripttemplate.htm
- Uses a string var named ans which is declared
inside the JavaScript - Type in this script within script tags within
ltheadgt tags - ans prompt("Are you sure you want to do
that?","") - if (ans)
- alert("You said "ans)
-
- else
- alert("You refused to answer")
-
- Prompt() method passes 2 parameters
- question for user default answer
- returns users response or returns null under
these circumstances - user clickscancel
- there is no default and user clicks OK when
user clears default answer and clicks OK
19JavaScript Methods document.write() and
document.writeIn()
- Method is action applied to something existing on
a Web page or in the Web browser. - document is an object (page Web browser is
accessing) - write() or writeIn() are methods
- DHTML html code written by JavaScript on the fly
- Usually use document.write() method
- document.writeIn() method attaches a carriage
return to the end of each text string sent to the
Web page. - relevant only when text string is formatted with
the ltpregt tag for which the browser recognizes
the existence of carriage returns - document.write(lth3gtNews Flash!lt/h3gt)
20document.write() example
- Use one of your previous examples
- Add this script inside the body tag
- lth1gt
- ltscript language"Javascript" type"text/javascri
pt"gt - lt!-- Hide script from old browsers
- document.write("Hello, world!")
- // End hiding script from old browsers --gt
- lt/scriptgt
- lt/h1gt
21Program Control Loops that test for conditions
Do Loops...
- Repeats a block of statements while a condition
is True or until it becomes True. - Do While Until conditionstatements Exit
Dostatements - Loop OR
- Do    statements Exit Do  statements
- Loop While Until condition
22Annoying do while example
- Insert script into JavaScript template
- Loop works until user enters ans
- ltscript language"Javascript" type"text/javascri
pt"gt - lt!-- Hide script from older browsers
- do
- ans prompt("Tell me your name","")
-
- while (!ans)
- alert("Hello, " ans)
- // End hiding script from older browsers --gt
- lt/scriptgt
23Program Control For Loop repeats certain number
of times
- For loop uses a counter that tracks the number of
times command block has run. - Set an initial value for the counter
- each time the command block is executed, the
counter changes in value (up or down). - When the counter reaches a value above or below a
certain stopping value, loop ends. - Syntax
- for (counterstart condition updatecounter)
- JavaScript Commands
-
- For loop Plug-in detection on next slide searches
client for plug-ins and prints a table of the
ones it finds. - Closing lttablegt tags are written lt\/tablegt so
browser does not think script tag is being closed
24- ltscript language"Javascript" type"text/javascrip
t"gt - lt!-- Hide script from older browsers
- if (navigator.plugins navigator.plugins.length
gt 0) - document.write("You have the following plugins
lttable cellspacing'4' cellpadding'4'gt") - document.write("lttrgtltth bgcolor'CCCCCC'gtNamelt\/
thgtltth bgcolor'CCCCCC'gtFilenamelt\/thgtltth
bgcolor'CCCCCC'gtDescriptionlt\/thgtlt\/trgt") - for (i0 iltnavigator.plugins.length i)
- thisPlugin navigator.pluginsi
- document.write("lttr valign'top'gtlttd
bgcolor'CCCCCC'gt" thisPlugin.name) - document.write("lt\/tdgtlttd bgcolor'CCCCCC'gt"
thisPlugin.filename) - document.write("lt\/tdgtlttd bgcolor'CCCCCC'gt"
thisPlugin.description "lt\/tdgtlt\/trgt") -
- document.write("lt\/tablegt")
-
- else
- document.write("JavaScript couldn't find any
plugins") -
- // End hiding script from older browsers --gt
- lt/scriptgt
25Script explanations
- if (navigator.plugins navigator.plugins.length
gt 0) - if both values are true, continue
- document.write("You have the following plugins
lttable cellspacing'4' cellpadding'4'gt") - writes opening table tag
- for (i0 iltnavigator.plugins.length i)
- Loops through each installed plugins
- thisPlugin navigator.pluginsi
- temporary variable that holds value of plugin it
finds - document.write("lttr valign'top'gtlttd
bgcolor'CCCCCC'gt" thisPlugin.name) - writes opening row cell tags, and plugin name
- Next line writes plugin file name within table
cell tags - Next line writes plugin description closes
table cell row tags
26Events can trigger actions
- Window Events triggers
- Mouse Events Triggers
- Form Events Triggers
- These events can be used to call functions
- Functions are usable sets of code that do
something - Can write your own functions
- Can call built-in functions (e.g., sin, cos, log,
min, max, round, sqrt
27Window Events triggers
- window.onload when user opens page
- window.onunload when user leaves page
- window.onresize forces page to reload
- window.onmove when window is moved
- window.onabort when user cancels image loading,
not supported by all browsers - window.onerror when javascript error occurs.
After several errors, page stops loading - window.onfocus or onblur
- when page moves in and out of focus on
display
28Mouse Events Triggers
- onmousedown
- onmouseclick
- onmouseup when user releases button
- onmousemove when user moves mouse over an area,
such as a rollover image - onmouseout when user rolls off rollover image or
area - ondblclick when user double clicks
- onclick when user presses mouse button down
29Form Events Triggers
- onsubmit when user presses submit button
- onreset when user presses reset button
- onchange when user changes a form field
- onselect when user selects text in an input or
textarea form field - onclick when user clicks a checkbox or radio
button - onblur when user tries to leave a form field (can
force user to input data before proceeding) - onfocus when user tabs to a field
30Key Events Triggers
- Key events allow user to control page using key
strokes, such as the right and left arrow keys - Can also assign key sequences to different
functions for disabled users - onkeydown, onkeyup, onkeypress
31Creating JavaScript Functions
- A function is a series of commands that performs
an action or calculates a value. - A function consists of the
- function name, which identifies it used to call
function - parameters. values used by the function ()
- a set of commands that are run when the function
is used. - general syntax of JavaScript function
- function saySomething(parameters)
- common block of JavaScript commands
-
- Not all functions require parameters, but require
() even if no parameters. - The group of commands set off by the curly braces
is called a common block.
32Creating JavaScript Functions
- Function names are case-sensitive.
- function name must
- begin with a letter or underscore ( _ )
- cannot contain any spaces.
- no limit to the number of function parameters
that a function may contain. - The parameters must be
- placed within parentheses
- () follow function name
- parameters must be separated by commas.
33Placing a Function in an HTML File
- Place of function in HTML file is important.
- function definition must be before the command
that calls the function. - Preferred programming convention is to place all
of the function definitions inside the ltheadgt and
lt/headgt tags. - A function is executed only when called by
another JavaScript command.
34Create Function to display msg in alert box, when
called by buttons on a form
- Insert this script within head tags in your
javascripttemplate - ltheadgtltscript language"Javascript"
type"text/javascript"gt - lt!-- Hide script from older browsers
- function sayIt(message)
- alert(message)
-
- // End hiding script from older browsers --gt
- lt/scriptgt
- lt/headgt
35Call the function by buttons on a form pass msg
text to function
- lth1gtFamous Presidential Quoteslt/h1gt
- ltform action""gt
- ltinput type"button" value"Lincoln"
onclick"sayIt('Four score and seven years
ago...')" /gt - ltinput type"button" value"Kennedy"
onclick"sayIt('Ask not what your country can do
for you...')" /gt - ltinput type"button" value"Nixon"
onclick"sayIt('I am not a crook!')" /gt - lt/formgt
36Returning a Value from a Function
- Download jpg mov files to your cis311 folder
- http//www.csupomona.edu/llsoe/311/images/day.jpg
- http//www.csupomona.edu/llsoe/311/images/FIRECAM
.MOV - Function yesquicktime checks whether browser has
QuickTime player - If check returns true, it plays the mov file
- If check returns false, it displays the image
file - The function is called from the body of the HTML
page when it loads.
37Insert Function within ltheadgt tags of JavaScript
template
- ltscript language"Javascript" type"text/javascrip
t"gt - lt!-- Hide script from older browsers
- function yesquicktime()
- for (i0 iltnavigator.plugins.length i)
- if (navigator.pluginsi.name.indexOf("Qu
ickTime") gt 0) - return true
-
-
- return false
-
- // End hiding script from older browsers --gt
- lt/scriptgt
38Call yesquicktime function from HTML
pageJavaScript-- result determines what is
displayed
- lth1 align"center"gtA movie worth waiting for . .
.ltbr /gt - ltscript language"Javascript" type"text/javascri
pt"gt - lt!-- Hide script from older browsers
- if (yesquicktime())
- document.write("ltembed src'../images/FIRE
CAM.MOV' width'320' height'250'gtlt\/embedgt") -
- else
- document.write("ltimg src'../images/day.jpg'
alt'clouds' width'320' height'208' \/gt") -
-
- // End hiding script from older browsers --gt
- lt/scriptgt
- lt/h1gt
39Create an image rollover
- Download two images into 311 folder
- http//www.csupomona.edu/llsoe/311/images/lightho
use2.jpg - http//www.csupomona.edu/llsoe/311/images/lightho
use.jpg - Create a new page from your javascript template
- Javascript in head tags
- Creates image variables
- loads images into image variables
- lta href tag loads one of images
- Onmouseover event displays 2nd rollover image
40Script within ltheadgt tags preloads images in cache
- ltscript language"Javascript" type"text/javascrip
t"gt - lt!-- Hide script from old browsers
- if (document.images)
- lighthouse1 new Image
- lighthouse2 new Image
- lighthouse1.src "lighthouse.jpg"
- lighthouse2.src "lighthouse2.jpg"
-
- else
- lighthouse1 ""
- lighthouse2 ""
- document.lighthouse ""
-
- // End hiding script from old browsers --gt
- lt/scriptgt
41Link within ltbodygt switches images
- lth1 align"center"gt
- lta href"http//www.csupomona.edu/"
- onmouseover"document.lighthouse.srclighthouse1.s
rc" onmouseout"document.lighthouse.srclighthouse
2.src"gt - ltimg src"lighthouse.jpg" width"201"
height"134" border"0" name"lighthouse"
alt"lighthouse" /gtlt/agt - lt/h1gt
42Arrays
- Array - ordered collection of values referenced
by a single variable name. - The syntax for creating an array variable is
- var pics new Array(3)
- var pics new array(pic1, pic2, pic3)
- pics is the name of the array variable
- size number of elements in the array (optional)
- pic1, etc., are array members members size
43Cycling banner array of pictures
- Download picturesopen folder
http//www.csupomona.edu/llsoe/42101/images/ - Download cpp1.jpg, cpp2.jpg, cpp3.jpg, cpp4.jpg,
cpp5.jpg, cpp6.jpg, cpp7.jpg, cpp8.jpg, cpp9.jpg - This example requires
- Declaration of array in ltheadgt
- Declaration of function rotate() in ltheadgt which
rotates images writes image to image tag in
body. Uses computer timer to time image swaps. - Call to function to display images in array from
ltbodygt tag onload event - image loaded in ltbodygt as placeholder to display
array
44Declaration of Array function in ltheadgt
ltheadgt ltscript language"JavaScript"
type"text/javascript"gt lt!-- Hide script from
old browsers cppImages new Array("cpp1.jpg","ccp
2.jpg","cpp3.jpg","cpp4.jpg","cpp5.jpg","cpp6.jpg"
,"cpp7.jpg","cpp8.jpg", "cpp9.jpg") thisPic
0 imgCt cppImages.length function rotate()
if (document.images) thisPic if
(thisPic imgCt) thisPic
0 document.cppBanner.srccppImagesthisPic
setTimeout("rotate()", 3 1000)
// End hiding script from old browsers
--gt lt/scriptgt
45ltbodygt onload event, img src tag
- ltbody bgcolor"FFFFFF" onload"rotate()"gt
- ltdiv align"center"gt
- lth1gtWelcome to the Cal Poly Animal Banner!lt/h1gt
- ltpgtltimg src"cpp1.jpg" alt"Cal Poly Animal
Banner" name"cppBanner" width"100" height"100"
id"cppBanner" /gtlt/pgt - lt/divgt
- lt/bodygt
46Wrap Around Slide Show
- In ltheadgt tag ltscriptgt
- Declare and populate (same) image array
- function chgSlide(direction) goes to next image
or previous image, based on function call from
link - next link increments image counter
- Previous link decrements image counter
- In ltbodygt tag
- First image loaded
- Previous and next links call function, pass
direction (-1 or 1)
47ltheadgt ltscriptgt
- cppImages new Array("cpp1.jpg","ccp2.jpg","cpp3.
jpg","cpp4.jpg","cpp5.jpg","cpp6.jpg","cpp7.jpg","
cpp8.jpg", "cpp9.jpg") - thisPic 0
- imgCt cppImages.length - 1
- function chgSlide(direction)
- if (document.images)
- thisPic thisPic direction
- if (thisPic gt imgCt)
- thisPic 0
-
- if (thisPic lt 0)
- thisPic imgCt
-
- document.myPicture.srccppImagesthisPic
-
-
-
48ltbodygt code
- ltbody bgcolor"FFFFFF" gt
- ltdiv align"center"gt
- lth1gtWelcome to the Cal Poly Animal
Slideshow!lt/h1gt - ltpgtltimg src"cpp1.jpg" name"myPicture"
id"myPicture" width"100" height"100" alt"Cal
Poly Pomona Animal Slideshow" /gtlt/pgt - ltpgtltstronggtlta href"javascriptchgSlide(-1)"gtlt
lt Previouslt/agt lta href"javascriptchgSlide(1)
"gtNext gtgt lt/agtlt/stronggtlt/pgt - lt/divgt
- lt/bodygt
49Create a pop-up window
- Function in ltheadgt ltscriptgt
- function newWindow()
- pigWindow window.open("cpp1.jpg", "pigWin",
"width200,height200") -
- HTML code in body calls function
- ltdiv align"center"gt
- lth1gtBehold! the Pig!lt/h1gt
- lth2gtClick on the word PIG to behold the PIG in
all his glory!lt/h2gt - lth1gtlta href"javascriptnewWindow()"gtPIGlt/agtlt/h1gt
- lt/divgt
50Dr. Hwangs Javascript Examples
- http//www.cisdept.csupomona.edu/hwang/cis311/dh31
1js_samples.htm - A Clock
- A Searchable Client-side Database
- External Font
- Alternating Images
- View Different Images in Another Window
51Working with Dates
- JavaScript does not provide a date data type.
- JavaScript allows you to create a date object,
which is an object containing date information. - There are two ways to create a date object
- variable new Date(month, day, year,
hoursminutes seconds) or - variable new Date(month, day, year, minutes,
seconds) - variable is the name of the variable that
contains the date information - month, day, year, hours, minutes, and seconds
indicate the date and time
52Retrieving the ThisDay Value
- JavaScript stores dates times as the number of
milliseconds since 6 p.m on 12/31/69. - Built-in JavaScript date methods calculate
- to get ThisDay, apply the getDate() method. The
general syntax is - DayValue DateObject.getDate()
- DayValue is variable that contains the day of the
month - DateObject is date variable that contains the
complete date and time information
53Retrieving the Month Value
- getMonth() method extracts value of current
month. - JavaScript counts months with 0 for January
- may want to add 1 to the month number returned by
the getMonth() method. - JavaScript code extracts the current month
number, increases it by 1, and stores it in a
variable named ThisMonth - ThisMonth Today.getMonth()1
- for a date of August 8, the ThisMonth variable
would have a value of _____?
54Retrieving the Year Value
- The getFullYear() method extracts the year value
from the date variable. - The following code shows how you would store the
value of the current year in a variable you name
ThisYear - ThisYear Today.getFullYear()
- if the date stored in August 8, 2005, the value
of the getFullYear variable is 2005
55Values of the getYear() method from 1998 to 2000
values of the getYear() method from 1998 to
2000. The getYear() method returns only the last
two digits of the year for years prior to 2000.
56Date Methods in JavaScript assume
date(November 20, 2006, 122528)
57JavaScript built-in Math Objectsand Math Methods
-- syntax
- value Math.method(variable)
- method is the method youll apply to a variable
- value is the resulting value
- Example calculate the absolute value of a
variable named NumVar, using the abs method - AbsValue Math.abs(NumVar)
- the value of the AbsValue variable is set to the
absolute value of the NumVar variable
58Comparison, Logical, Conditional Operators
- To create a condition in JavaScript, you need one
of three types of operators - a comparison operator
- compares value of one element with that of
another, - creates Boolean expression that is either true or
false - a logical operator
- connects two or more Boolean expressions
- a conditional operator
- tests whether a specific condition is true
- returns one value if the condition is true and a
different value if the condition is false
59An Example of Boolean Expressions
- Here are two examples of Boolean expressions
- x lt 100
- if x is less than 100, this expression returns
the value true however, if x is 100 or greater,
the expression is false - y 20
- the y variable must have an exact value of 20 for
the expression to be true - comparison operator uses a double equal sign ()
rather than a single one (a single equal sign is
an assignment operator and is not used for making
comparisons)
60Logical Operators. Assume x20, y25
61Nesting a For Loop
This figure shows code used to write a table
containing three rows and four columns.
62Specifying Counter Values in a For Loop
The For loop is not limited to incrementing the
value of the counter by 1. This figure shows
examples of other ways of incrementing the
counter in a For loop.
63The While Loop
- The While loop runs a command group as long as a
specific condition is met - it does not employ any counters.
- The general syntax of the While loop is
- while (condition)
- JavaScript Commands
-
- condition is a Boolean expression that can be
either true or false
64Creating a While Loop
This figure shows how you can create a set of
table cells using a While loop.
65Nesting a While Loop
66Next
- Due Monday, Week 10, 745 pm
- Tutorial 10, Case 3, p. 575, Butler Community
Center--Javascript calendar - Use JavaScript to create calendar - use tutorial
content. - Upload two of JavaScript labs we are doing in
class this week to the labs folder of your
website each worth 5 points. - They should be XHTML valid
- They should work
- Link to both of them from your toc.htm
- Dont need to upload grading sheet
- Week 10
- new technologies uses of Internet, Security
Ethics - Computer forensics speaker on Monday
- How people use computers throughout the world
- Lab Internet treasure hunt prep for final exam
- Finals Wednesday, 3/14/07, 810 PM
Comprehensive Final Exam MOST will be on class
content since midterm exam.