Week 10 - PowerPoint PPT Presentation

About This Presentation
Title:

Week 10

Description:

(not dependent on Internet and Web Server) ... value='Show Current Time' / input type='text' ... You can specify the data/time when you create the object. ... – PowerPoint PPT presentation

Number of Views:59
Avg rating:3.0/5.0
Slides: 51
Provided by: david677
Category:
Tags: week

less

Transcript and Presenter's Notes

Title: Week 10


1
JavaScript
  • Week 10
  • A World Wind Tour of JavaScript

2
Objectives
  • World wind tour of JavaScript
  • JavaScript Its Beginnings
  • Advantages and disadvantages
  • How differs from PHP
  • Working with JS and HTML tags.
  • Running onload, when done, on an event
  • Using JS objects
  • Objects and forms (validating)
  • Rollovers

3
JavaScript Its Beginnings
  • JavaScript developed by Netscape initially
    called livescript.
  • After Java  came out, Netscape cut a deal with
    Sun to rename it to JavaScript (12/95).
  • They are separate, distinct languages. (Though
    JavaScript is simpler).
  • Microsoft
  • Came out with their own flavor of JavaScript
    called Jscript.
  • They also added support for VBScript in IE.
    Differences are minor.
  • Eventually standardized
  • JavaScript has been turned over to the European
    Computer Manufactures Association, and is now
    officially called ECMAScript
  • Both Netscape IE4.0 and Netscape implement
    ECMAScript standard.

4
The goods on JavaScript
  • JavaScript can be used to
  • 1. perform simple client-side computations
  • For example, add up total costs of shopping cart
    before it is submitted.
  • 2. facilitate dynamic and interactive Web page
    creation
  • For example, do image roll overs, pop up windows
    on click, expand a menu.
  • 3. Verify HTML forms enhance HTML forms with data
    collections and form validation
  • 4. manipulate user cookies -

5
The not so goods on JavaScript
  • JavaScript runs completely on Client machine
  • It does NOT have
  • 1. Any graphic capabilities
  • E.g., cannot show a graph of survey results.
  • 2. Access to client (you PC) resources
  • Cannot print, modifying PC files, or launching
    client applications.
  • 3. Access to any Web server resources
  • E.g., cannot send email, write to file, write to
    database.

6
PHP/JavaScript Similarities and Differences
  • What they have in common. Both languages can
  • Be embedded in HTML documents
  • Cause dynamic content to be displayed (e.g., the
    current date)
  • Can be placed in external files and included
    into html files
  • Look more like a programming language than HTML
  • What they DONT have in common
  • The big difference JavaScript runs 100 on
    client (i.e., PC). This means
  • JavaScript stuff runs noticeably faster
  • (not dependent on Internet and Web Server)
  • PHP has access to Web Server resources (mail,
    databases, files)
  • Using differences
  • Writing JavaScript does NOT require a Web Server
    (but more concern about browser implementation
    differences).
  • PHPs syntax is easier to write and understand
    for beginners.

7
How PHP Pages are Run
JavaScript does not run here
JavaScript is run here by the browser but just
before HTML
8
Objectives
  • World wind tour of JavaScript
  • JavaScript Its Beginnings
  • Advantages and disadvantages
  • How differs from PHP
  • Working with JS and HTML tags.
  • Running onload, when done, on an event
  • Using JS objects
  • Objects and forms (validating)
  • Rollovers

9
Adding JavaScript to HTML pages
  • JavaScript is added to HTML pages using the
    ltscriptgt tag.
  • usually placed in the HEAD or BODY  of the
    document
  • ltscript srcURL languageJavaScriptgtlt/scriptgt
  • ltscript languageJavaScriptgt
  • lt!--
  • Javascript code
  • //--gt
  • lt/scriptgt

If link to an external file (use .js suffix)
If embed JS within HTML
10
A Simple example
  • ltHTMLgt ltHEADgt ltTITLEgt A Beginning Script
    lt/TITLEgt lt/HEADgt ltBODYgt ltSCRIPT
    LANGUAGE"JavaScript"gt    document.write
    ("Welcome to the wonderful world of JavaScript")
    lt/SCRIPTgt lt/BODYgt lt/HTMLgt

Its a little like PHP. These statements are run
before HTML document interpreted by browser
http//condor.depaul.edu/dlash/extra/javascript/s
tartingout.htm
11
Where do you put it?
  • Can add JavaScript to head or body of html
    document
  • Functions are usually added to the head section
  • assures that the functions OK (parsed) by the
    time they are called.
  • Non-functions usually put in body
  • then can call and functions in head

12
Objectives
  • World wind tour of JavaScript
  • JavaScript Its Beginnings
  • Advantages and disadvantages
  • How differs from PHP
  • Working with JS and HTML tags.
  • Running onload, when done, on an event
  • Using JS objects
  • Objects and forms (validating)
  • Rollovers

13
When does it run?
  • It can run
  • as the page loads
  • as soon as the page is finished loading
  • in response to user input (remember the form
    button?)

14
JavaScript that Runs as Page Loads
Normal HTML code
ltHTMLgtltHEADgtltTITLEgtDocument Objectlt/TITLEgt lt/HEADgt
ltBODY bgColorccccffgt ltCENTERgt ltH2gtDocument
Object lt/H2gt ltSCRIPT languageJavaScriptgt
document.writeln("This page was last modified on
document.lastModified) lt/S
CRIPTgt lt/CENTERgtlt/BODYgtlt/HTMLgt
Enter JavaScript. Within the html body (in this
case)
document.write like print. Get lastModified
browser vrbl. . The is catenation.
Calls function to get current date and output date
http//condnor.depaul.edu/dlash/extra/javascript/
lastmodifiedworks.htm
15
JavaScript output (onload) is HTML input
  • . The output of JavaScript statements is taken as
    HTML input...
  • ltHTMLgt ltHEADgt ltTITLEgt A Beginning Script
    lt/TITLEgt lt/HEADgt ltBODYgt
  • ltSCRIPT languageJavaScriptgt
  • document.write ("ltFONT Size4gtJavaScript
    commands are interpreted firstlt/FONTgt")
  • document.write ("ltBRgt ltFONT COLORBLUEgtJS output
    often generates HTMLlt/FONTgt")
  • lt/SCRIPTgt
  • lt/BODYgtlt/HTMLgtlt/HTMLgt
  • http//condor.depaul.edu/dlash/extra/javascript/s
    econdjs.htm

16
JavaScript that Runs when Loading Complete
lthtmlgt ltheadgt lttitlegt Java Example 2 lt/titlegt
lt/headgt ltbody onloadwaitLittle()gt ltfont size4
colorbluegt welcome to my page lt/fontgt ltbrgtHere
is my stuff ltbrgt ltbrgt ltscript language"JavaScrip
t"gt function waitLittle() setTimeout(
"alertMe()", 5000 ) function alertMe()
alert('test') lt/scriptgt This is some text
over here. ltimg src"../donald.gif"gt lt/bodygt
lt/htmlgt
Execute this function call after 5000 miliseconds
Create a pop-up box with test as text
http//condor.depaul.edu/dlash/javascript//javasc
ript2.html
17
JavaScript that Runs in Response to User Input
lthtmlgtltheadgt ltscript language"JavaScript"gt lt!-- f
unction showTime() document.forms"getDa
te".curTime.value (new
Date()).toLocaleString() function alertme()
alert("Don't Do that") //--gt lt/scriptgt lt
/headgt ltbody style"background-color
fffff0"gt ltform name"getDate"gt ltinput
type"button" name"getTime" onClick"showTime()"
value"Show Current Time"
/gt ltinput type"text" name"curTime" size"40"
onClick"alertme()"/gt lt/formgt
Set the value of the form variable curTime to
the current time
When click call showtime
If they click generate an alert
http//nwswww.ih.lucent.com/dlash/perlcourse/java
script/javascript3.htm
18
Dealing with Browsers that dont Support
JavaScript
You may have noticed something a little strange
about the examples so far. ltscript
languageJavaScriptgt lt!-- Javascript
code //--gt lt/scriptgt This makes the script
invisible to browsers that dont support
JavaScript by commenting it out. In addition,
you can provide some page content that only
displays when the browser DOESNT handle
JavaScript ltnoscriptgt Your browser doesnt
support Javascript lt/noscriptgt The only
limitation with this is that this will NOT be
displayed by NS if the user has JavaScript just
disabled.
19
Some Important Aspects of JavaScript
  • Case Sensitive Variable names, functions you
    use
  • - (e.g., Date not date )
  • Space Insensitive - generally ignored, except in
    strings
  • Statements end in semicolon Except JS will
    assume you meant to semicolon at the end of the
    line if the statement appears to be complete.

20
Objectives
  • World wind tour of JavaScript
  • JavaScript Its Beginnings
  • Advantages and disadvantages
  • How differs from PHP
  • Working with JS and HTML tags.
  • Running onload, when done, on an event
  • Using JS objects
  • Objects and forms (validating)
  • Rollovers

21
JavaScript And Objects ...
  • JavaScript is object-oriented (Just a thing you
    can access)
  • Objects have
  • properties - are variables or other objects
    describing the object.
  • (like document.lastmodified).
  • In general these are accessed by
    ObjectName.ProperyName
  • methods - behaviors or built-in functions you use
  • accessed my ObjectName.MethodName()

document.lastmodified
Object name
Property of object
22
Using JavaScript Objects
  • Lots of useful properties available g
  • Here are some properties for window object
  • document.lastModified (read-only property)
    gives the document last changed date
  • document.URL  - (read-only property) gives the
    URL of the document source code file.
  • window.referrer (read-only property) gives the
    URL of the calling document. (It is an empty
    string, if user does not reach the URL by
    clicking a link.
  • window.title (read-only property) gives the
    value in the ltTITLEgt ... lt/TITLEgt tag.

23
Printing out one of these
  • Can use the plus sign () to attach
  • string output with
  • propert output
  • document.write("last modified
  • document.lastModified
  • "ltPgt")

Write the following out.
Print out this string
Attach to the string this property
Attach to the entire string this html tag
24
For example
  • ltHTMLgt ltHEADgt ltTITLEgtDocument Information
    Propertieslt/TITLEgt lt/HEADgt ltBODYgt ltSCRIPT
    LANGUAGE"JavaScript"gt document.write("Referring
    link was
  • document.referrer)
    "ltBRgt") document.write("Document URL is
    document.URL "ltBRgt") document.write("The title
    is " document.title "ltBRgt") document.
    write("last modified
  • document.lastModified
    "lt/Pgt") lt/SCRIPTgt ltHRgt This is my web site.
    It is my Web Site all by myself. lt/BODYgt
    lt/HTMLgt

http//condor.depaul.edu/dlash/extra/javascript/D
ocumentInformationProperties.htm
25
The Math Object
An example JavaScript object.
Math.abs(number) Math.sin(number) Math.cos(number)
Math.round(number) Math.ceil(number) Math.floor(n
umber) Math.log(number) Math.sqrt(number) Math.ra
ndom(number)
absolute value sine of an angle (expressed in
radians) cosine of an angle (expressed in
radians) closest integer value rounds up to next
integer value rounds down to next integer
value natural log of the number square root of
the number returns a floating point number that
is gt 0.0 but lt 1.0
Other methods include tangent, arc tangent, arc
sine, arc cosine, tangent, power, angle of polar
coordinates, maximum, and minimum. Also has
constant definitions for values like pi and e
(natural log base).
26
The Date Object
The Date object to access time and date
information. Unlike the Math object, need to
create a Date object first var dateObj new
Date() You can specify the data/time when you
create the object. xmasObj new Date(December,
25, 2002) Can print out current date via
document.write ( new Date().toLocaleString())
Creates new date object
27
Objectives
  • World wind tour of JavaScript
  • JavaScript Its Beginnings
  • Advantages and disadvantages
  • How differs from PHP
  • Working with JS and HTML tags.
  • Running onload, when done, on an event
  • Using JS objects
  • Objects and forms (validating)
  • Rollovers

28
Document objects
Getting access to page contents requires document
object. Everything on the page is associated
with an object. Some of these objects contain
other objects. The object hierarchy is
window
link
frame
anchor
navigator
history
form
location
element
document
29
JavaScript is Event Driven
  • Event-driven When event occurs then take some
    action.
  • JavaScript supports several events such as
  • onLoad
  • onUnload
  • onFocus
  • onBlur
  • onMouseOver
  • onMouseOut
  • onChange
  • onSelect
  • lttdgtltinput type"text" name"total"
    OnClick"genAlert()"gtlt/tdgt

When click this form element then do this
JavaScript function
30
Example of Events and Forms
  • Consider the following Form with 3 text boxes.
  • Onclick either first 2 text fields adds them up.
  • If click last on create a pop-up

First num
Second num
Total
http//condor.depaul.edu/dlash/extra/javascript/m
yform.htm
31
Document objects (cont.)
Uses an external javascript file.
lthtmlgtltheadgt lttitlegt my form lt/titlegt lt/headgt
ltbodygt ltscript src"total.js"
language"javascript" type"TEXT/JAVASCRIPT"gt
lt/scriptgt ltform name"totals"gt lttablegt lttrgt
lttdgtValue1lt/tdgt lttdgtltinput type"text"
name"first" value0 onClick"calcTotals()"gtlt/tdgt
lt/trgt lttrgt lttdgtValue2lt/tdgt
lttdgtltinput type"text" name"second" value0
OnClick"calcTotals()"gtlt/tdgt lt/trgt lttrgt
lttdgtTotallt/tdgt lttdgtltinput type"text"
name"total" OnClick"genAlert()"gtlt/tdgt lt/trgt
lt/trgt lt/tablegt lt/formgt lt/bodygt lt/htmlgt
Form named totals
onClick call calcTotals() function
Text box names first, second, total
onClick call genAlert() function
32
Document objects (cont.)
The following would be in the file total.js
function genAlert() message"Error Do not
change total score value. It will be filled in by
the Web Application" alert( message
) function calcTotals()
fdocument.totals f.total.value
parseInt(f.first.value) parseInt(f.second.value)

Call form document.totals f
Add the form element called first with the
element called second
It would be useful to check if valid number but
it works for what it does.
33
A simple variation ..
  • lthtmlgtltheadgt lttitlegt my form lt/titlegt lt/headgt
  • ltbody onLoad"calcTotals()" gt
  • ltscript src"total.js" language"javascript"
    type"TEXT/JAVASCRIPT"gt
  • lt/scriptgt
  • ltform name"totals"gt
  • lttablegt
  • lttrgt
  • lttdgtValue1lt/tdgt
  • lttdgtltinput type"text" name"first" value3
    onClick"calcTotals()"gtlt/tdgt
  • lt/trgt
  • lttrgt
  • lttdgtValue2lt/tdgt
  • lttdgtltinput type"text" name"second" value4
    OnClick"calcTotals()"gtlt/tdgt
  • lt/trgt
  • lttrgt
  • lttdgtTotallt/tdgt
  • lttdgtltinput type"text" name"total"
    OnClick"genAlert()"gtlt/tdgt
  • lt/trgt
  • lt/trgt

Call calcTotal() onload.
Call give initial values to textboxes.
Not a submit button but when hit button call
calctotals also.
http//condor.depaul.edu/dlash/extra/javascript/m
yform2.htm
34
Form Validation
To validate forms need control onSubmit of
form window.document.forms"inputValues".submit
() To block submission of a form when the
submit button is clicked, we define the onsubmit
event for the form onsubmitreturn
checkitout() a value of false will stop submit
35
Form Validation (cont.)
Example, ltform name"inputValues methodpost
actionURL, onsubmitreturn inputValid()
gt We would then define the function function
inputValid() if (everthingIsOk) return
true else return false
36
Example using onSubmit()
  • lthtmlgtltheadgt lttitlegt my form lt/titlegt lt/headgt
  • ltbody onLoad"calcTotals()" gt
  • ltscript src"total2.js" language"javascript"
    type"TEXT/JAVASCRIPT"gt
  • ltform name"totals" method"post"
    action"savevalues.php"
  • onSubmit"return inputValid()" gt
  • lttablegt
  • lttrgt
  • lttdgtValue1lt/tdgt
  • lttdgtltinput type"text" name"first" value3
    onClick"calcTotals()"gtlt/tdgt
  • lt/trgt
  • lttrgt lttdgtValue2lt/tdgt
  • lttdgtltinput type"text" name"second" value4
    OnClick"calcTotals()"gtlt/tdgt
  • lt/trgt
  • lttrgt
  • lttdgtTotallt/tdgt
  • lttdgtltinput type"text" name"total"
    OnClick"genAlert()"gtlt/tdgt

Action set onSubmit set
Changed to submit button type.
http//condor.depaul.edu/dlash/extra/javascript/m
yform3.htm
37
Example using onSubmit() total2.js
  • function genAlert()
  • message"Error Do not change total score
    value. It will be filled in by the
  • Web Application"
  • alert( message )
  • function calcTotals()
  • fdocument.totals
  • f.total.value parseInt(f.first.value)
    parseInt(f.second.value)
  • function inputValid()
  • fdocument.totals
  • calcTotals()
  • if ( parseInt(f.total.value) gt 50 )
  • return true
  • else
  • alert("Please Continute until hit
    50")
  • return false

Re-calculate totals
New function checks if total gt 50.
38
Accessing Other Form Elements
  • Can access and validate things like
  • select (including ones with the MULTIPLE
    attribute)
  • password (the real value, not the line of
    asterisks)
  • radio buttons
  • checkboxes
  • textarea
  • hidden fields
  • Getting these is beyond scope of class but can
    give an example

39
Example Getting Radio and select buttons
  • lthtmlgtltheadgt lttitlegt my form lt/titlegt lt/headgt
  • ltbody onLoad"calcTotals()" gt
  • ltscript src"total4.js" language"javascript"
    type"TEXT/JAVASCRIPT"gt
  • lt/scriptgt
  • ltform name"survey1"gt
  • lttablegt
  • lttrgt
  • lttdgtPick a buttonlt/tdgt
  • lttdgtltinput type"radio" name"first" value1gt
    One
  • ltinput type"radio" name"first" value2gt
    Two
  • ltinput type"radio" name"first" value3gt
    Three lt/tdgt
  • lt/trgt
  • lttrgt
  • lttdgtSelect an Optionlt/tdgt
  • lttdgt ltselect name"second" gt
  • ltoption value1gt One lt/optiongt
  • ltoption value2 selectedgt Two lt/optiongt

http//condor.depaul.edu/dlash/extra/javascript/m
yform4.htm
40
Example Getting Radio and select buttons
  • function genAlert()
  • message"Error Do not change total score
    value. It will be filled in by the Web
    Application"
  • alert( message )
  • function get_radio_value( form, button )
  • var RadioButton documentformbutton
  • for (i0 iltRadioButton.length i )
  • if (RadioButtoni.checked)
  • return RadioButtoni.valu
    e
  • return 0
  • function getSelectValue( formname, selectname )
  • var theMenu documentformnameselectnam
    e
  • var selectedItem theMenu.selectedIndex
  • if ( selectedItem -1 )
  • return 0

For each radio button in the group
If it is checked then return its value
41
Accessing Other Form Elements (cont.)
But reading the form elements is not the only
thing you can do. You can also alter them var
formObj window.document.forms"sample" formObj.
elements"textBox".value "Random
Text" formObj.elements"passwrd".value
"rosebud" formObj.elements"checkbox4"1.checke
d true formObj.elements"checkbox4"0.checked
false formObj.elements"checkbox1".value
"Citizen_Kane" formObj.elements"checkbox1".check
ed true formObj.elements"checkbox2".checked
false formObj.elements"checkbox3".checked
false formObj.elements"radio1"3.checked
true formObj.elements"select1".selectedIndex
2 formObj.elements"select1".options2.text
"Gioachino Rossini" formObj.elements"select1".o
ptions2.value "Rossini" formObj.elements"sel
ect2".options4.text "William
Tell" formObj.elements"select2".options4.valu
e "WillTell" formObj.elements"select2".option
s4.selected true formObj.elements"select2".
options2.selected true formObj.elements"sele
ct2".options1.selected false
42
One More Example
  • htmlgtltheadgt lttitlegt my form lt/titlegt lt/headgt
  • ltbodygt
  • ltscript src"total_regexpr.js" language"javascrip
    t" type"TEXT/JAVASCRIPT"gt
  • lt/scriptgt
  • ltform name"totals" method"post"
    action"savevalues2.php" onSubmit"return
    inputValid()" gt
  • lttablegt
  • lttrgt
  • lttdgtEnter Soc Securitylt/tdgt
  • lttdgtltinput type"text" name"soc"gtlt/tdgt
  • lt/tablegt
  • ltinput type"submit" value"submit"gt
  • lt/formgt
  • lt/bodygt lt/htmlgt

43
One More Example (Cont.)
  • function inputValid()
  • fdocument.totals
  • inSoc (f.soc.value)
  • social /(\d9\d3-\d2-\d4)/
  • var matchIndex inSoc.search(social)
  • if ( matchIndex gt 0 )
  • return true
  • else
  • alert("Please enter 9 digits")
  • alert(matchIndex)
  • return false

http//condor.depaul.edu/dlash/extra/javascript/
44
Objectives
  • World wind tour of JavaScript
  • JavaScript Its Beginnings
  • Advantages and disadvantages
  • How differs from PHP
  • Working with JS and HTML tags.
  • Running onload, when done, on an event
  • Using JS objects
  • Objects and forms (validating)
  • Rollovers

45
Creating Rollovers
  • You can create a crude rollover mechanism by
    changing src properities of a file.
  • Not the way best way to do this (since will not
    be downloaded until you mouse over the image.)

http//condor.depaul.edu/dlash/extra/javascript/R
olloverBeethoven.htm
46
The Source
  • lthtmlgtltheadgtlttitlegtRollover Beethovenlt/titlegtlt/hea
    dgt
  • ltbody bgcolor"white"gt
  • ltdiv align"center"gt
  • lth1gtRollover Beethovenlt/h1gt
  • lt!--Callout The Anchor tag responds to mouseover
    and
  • mouseout events.--gt
  • lta href"" onmouseover "document'beethoven'.sr
    cRolloverBeethoven_files/beethovenon.jpg'"
  • onmouseout "document'beethoven'.src'Roll
    overBeethoven_files/beethovenoff.jpg'"gt
  • ltimg src"RolloverBeethoven_files/beethovenoff.jpg
    " width"250" height"70" name"beethoven"
  • border"0" alt"Picture of Beethoven"gtlt/agt
  • lt/divgt
  • lt/bodygt
  • lt/htmlgt

The ltagt tag responds to mouseover and mouseout
events. It is set to null value.
Set the image src property
The default image
Border0 prevents image border from appearing.
47
One more thing debug
If type javascript In netscape only will create
debug console http//condor.depaul.edu/dlash/ext
ra/javascript/lastmod_error.htm
48
Summary
  • World wind tour of JavaScript
  • JavaScript Its Beginnings
  • Advantages and disadvantages
  • How differs from PHP
  • Working with JS and HTML tags.
  • Running onload, when done, on an event
  • Using JS objects
  • Objects and forms (validating)
  • Rollovers

49
Overall Summary
  • We have looked at many things
  • HTML Great for static text, images, forms
  • Links, font tags, lists, tables, forms, frames.
  • Design Think through how site looks
  • Talk with site owner
  • Consistent navigation
  • Graphic design use photo editing software
  • CSS Allows greater control of text, gt 1
    developers, common format
  • PHP Create dynamic content, run on WebServer,
    receive form input
  • JavaScript Run on browser, validate forms, roll
    overs, pop ups, menu elements.

50
Overall Summary
  • A real Site might include all of these
  • Html to display content.
  • Design photo-editor
  • CSS to control look and feel
  • PHP to send email, save to database
  • JavaScript to validate forms, control certain
    elements
  • A real web developer would have much more
    experience with
  • PHP (or some other script) Databases, other
    things
  • JavaScript
  • Frontpage type of software
  • Hopefully you found information valuable and help
    take some of the magic out of Websites and
    website design
Write a Comment
User Comments (0)
About PowerShow.com