Title: JavaScript
1JavaScript
- Making Web pages come alive
2Objectives
- Be able to read JavaScript scripts
- Be able to write JavaScript scripts
3To See Examples
- Open text editor
- Create HTML page
- Type in each example, save and view with browser
4Static vs. Dynamic
- Static
- page appears exactly as it was encoded, nothing
changes - only HTML
- Dynamic
- page changes (possibly in response to users
actions) - Cant be only HTML
- Scripts
5Scripts server-side vs. client-side
- Server-side
- the first type possible on the Web
- action occurs at the server
- Client-side
- handles user interaction
- generally easier to implement
- may be prepared and implemented offline
- action occurs on the client side (browser)
- JavaScript is the most common example
6DHTML
- HTML-Document description-we did
- JavaScript- Client-side interaction-will do
- CSS- Style definition-beyond
- Dynamic HTML HTML CSS scripts
7JavaScript
- Developed by Netscape to be simple, cross-browser
scripting language for Web - Syntax based on C - a good starting point to
learn other programming languages - JavaScript is not Java
- ltscript type"text/javascript"gt lt/scriptgt
enclose a JavaScript script
8Write()
- JavaScripts output statement
- document.write (Text)
- Inside the ltscriptgt tag, we must output HTML
- document.write (ltpgtTextltbr/gttextlt/pgt)
9Hello World
- lthtmlgt
- ltheadgtlttitlegthello javascriptlt/titlegtlt/headgt
- ltbodygt
- ltscript gt
- document.writeln ("Hello, World!")
- lt/scriptgt
- lt/bodygt
- lt/htmlgt
- Output?
10What is the output?
- lthtmlgt
- ltheadgtlttitlegthello javascriptlt/titlegtlt/headgt
- ltbodygt
- ltscript gt
- document.write ("Hello,\n World")
- document.write ("Hello,ltbr/gt2 the
nbspnbspnbspWorld") - lt/scriptgt
- lt/bodygt
- lt/htmlgt
11Why?
- Hello, WorldHello,2 the World
- the document.writeln() method preserves any line
breaks in the text string.
12JavaScript
- Statements end with
- Can often get away with omitting
- Character strings enclosed in or
- Can include an external source file with the src
attribute - ltscript srcfile_name.jsgtlt/scriptgt
13 JavaScript Comments
- // Ignore rest of line
- / Ignore everything
- enclosed
- /
- Dont forget to end the comment
14Objects
- JavaScript is an Object Oriented Language.
- Objects are thingsnouns
- They have attributes---adjectives
- We call the attributes properties
- They have actions---verbs
- We call the actions methods use ()
15Objects
- Use dot-notation to indicate that a method or a
property belongs to an object. - Car analogy
- document.write()
- document.bgColor
- Recall methods have ()
16Objects
- JavaScript objects include the HTML elements,
window, document - lastModified is a property of the document
object.
17JavaScript
- A variable stores a value.
- Declare a variable with the keyword var
- Assignment variable value
- adds numbers
- concatenates strings of characters
- e.g. ab cd is abcd
- lastModified is a property of the document
object.
18Example
- lthtmlgt
- ltheadgtlttitlegtLast Modifiedlt/titlegtlt/headgt
- ltbodygt
- ltscriptgt
- var date
- datedocument.lastModified
- document.writeln ("This page was last
modified date) - lt/scriptgt
- lt/bodygt
- lt/htmlgt
- Will automatically update. Output?
19Output
- This page was last modified 01/25/2005 124018
- Note
- var datedocument.lastModified
- could have been in one line
- See new window 2.html
20Window
- The document object is contained within a window
object. - window has methods
- Alert ()
- Confirm ()
- Prompt ()
- window is assumed so
- alert () is equivalent to window.alert ()
21Alert()
- Alert (some string) pops up a message box
containing its string. - It is a method of the (assumed) window object.
22Alert()
- lthtmlgt
- ltheadgtlttitlegthello alertlt/titlegtlt/headgt
- ltbodygt
- ltscriptgt
- alert ("Hello, World!")
- lt/scriptgt
- lt/bodygt
- lt/htmlgt
- Output alert box. Run it to see.
23Confirm
- Confirm uses if-else logic. true/false. Can I
assume? - Declare a variable.
- Confirm returns a value which you assign to a
variable. O.K. button sends true. Cancel sends
false. - Test the variable
24Confirm
- ltscriptgt var x confirm ("Are you sure you are
ok?") if (x) alert ("Good!") else alert
("Too bad")lt/scriptgt
25Prompt()
- Prompt() method returns the text
- ltscriptgt
- var yprompt
- ("please enter your name")document.writeln
(Hello, y) - lt/scriptgt
26Prompt()
- You assign the result to a variable.
- You use the value.
- Optional Second parameter to Prompt()
- Is the default value.
27Equality
- tests for equality
- AB has the value true when A and B are the
same false otherwise. - ! tests for inequality
28Password
- ltheadgt
- ltscript gt
- var guess var passwordfool
guessprompt(' enter password ') - if (password!guess) locationforbidden.html
- lt/scriptgt
- lt/headgt
- Why fool?
29Because
- Password is in source which may be viewed .
- I must admit that I couldnt view it!!
30Events
- Usually, user actions generate events that belong
to objects. - mouseover
- load
- click
31Event Handlers
- Event handlers-respond to users actions
- onmouseover
- onmouseout
- onload
- onunload
- Event handlers are put inside corresponding HTML
tags. - Not inside ltscriptgtlt/scriptgt
32Case
- onClick"alert ('You clicked the button!')"
- The underlined parts are HTML
- The quoted string is JavaScript
- onClick
- The Java naming convention is easier to read.
- This is fine in HTML, but an error if it occurs
in JavaScript. JavaScript is case sensitive. HTML
is not . - Please note Since we have a quoted string inside
another quoted string, we need both single and
double quotes.
33Event Handlers
- Most HTML elements have the following event
handlers - onClick -- the form element is clicked
- onDblClick -- the form element is clicked twice
in close succession - onMouseDown -- the mouse button is pressed while
over the form element - onMouseOver -- the mouse is moved over the form
element - onMouseOut -- the mouse is moved away from the
form element - onMouseUp -- the mouse button is released while
over the form element - onMouseMove -- the mouse is moved
- In JavaScript, these should be spelled in all
lowercase
34Change Color
- lthtmlgt
- ltheadgtlttitlegtChange the Background
Colorlt/titlegtlt/headgt - ltbody gt
- lth3gtlta href"" onMouseover"document.bgColorb
lue'" onMouseout "document.bgColor'white'"gt - Move your cursor over this link to change
background color to blue.lt/agtlt/h3gt - lt/bodygt lt/htmlgt
35OnMouseover
- lta href"" onMouseover"alert ('Ouch! I asked
you not to click this link!')"gt - Don't click this link!lt/agt
- Whats the first thing youll do? ?
- Aside I typed this twice. One worked. One
didnt. I never figured out difference.
36Status (skip)
- The window object has the property status whose
value is displayed in the status bar. - Change it only briefly cause need the info.?
- lta href" onMouseover"status'Hi there!'
return true" onMouseout"status' ' return
true"gt - Place your mouse here!lt/agt
37Push Button
- Object that has some effect when it is pushed
- e.g. doorbell
- except traffic light
- User defined (as opposed to which?)
- Has no default behavior. (what was.)
- May have client side scripts associated with its
event attributes. When an event occurs (e.g., the
user presses the button, releases it, etc.), the
associated script is triggered.
38Buttons are contained in forms
39Button
- type"button"This command declares the input to
be a button. - value"Click Me"This will be the text people
will see on the button. Write whatever you want
your visitors to see. - name"button1"You can give the button a name so
you can refer to it.
40Button event handler
- ltformgt ltinput type"button" value"See Some
Text" name"button2" onClick"alert ('Some
Text')"gt - lt/formgt
- Recall window is the assumed object.
41Color buttons
- ltformgt ltinput type"button" value"Change to
Yellow!" name"buttonY" onClick"document.bgColor
'yellow"gt - ltinput type"button" value"Change to White!"
name"buttonW" onClick"document.bgColorwhite"
gt - lt/formgt
42open
- open( ) is a method of the window object.
- It opens a new window.
- open(URL)
- You can use it inside an event handler.
- I had to use window.open(). I dont know why.
43Open
- ltformgt
- ltinput type"button" name"button1"
value "new" onClick "window.open('forbidden.html
')"gt - lt/formgt
- lta href"" onClick "window.open('forbidden.html'
)"gt - open sesamelt/agt
44Full featured window
- window.open('http//www.blah.com/blah',
- title','width400,height200,toolbaryes,
locationyes,directoriesyes,statusyes,menubarye
s,scrollbarsyes,copyhistoryyes, resizableyes')
45Functions
- A function is a named piece of code that performs
a task. Has () - Functions are put in ltheadgt so they are loaded
before the page displays. - Are executed only when invoked.
- Body enclosed in (called a block)
- May have parameters in () (values used by the the
function to do its task).
46Functions
- Methods are similar to functions that belong to
an object. - Functions are similar to methods that belong to
the script. Placed in head so they are loaded
before they are called. - An event handler should be very short
- Many handlers call a function to do their job
(delegate).
47Examples
- Function_wo_param
- Simple calculator.html
- Bgcolor_buttons_func.html
- On slide, too
- Mixed up
- On slide, too
48lt! -- bgcolor_buttons what will happen?
--gt lthtmlgtltheadgt ltscriptgt function
yellow()document.bgColor'yellow' function
white()document.bgColor'white'
lt/scriptgt lt/headgt ltbodygt ltformgt ltinput
type"button" value"Change toYellow"
name"buttonY onClickyellow()"gt ltinput
type"button" value"Change to White"
name"buttonW onClick"white()"gt
lt/formgt lt/bodygtlt/htmlgt
49lt! -- mixed up. what will happen?
--gt lthtmlgtltheadgt ltscriptgt function
yellow()document.bgColor'yellow' function
white()document.bgColor'white'
lt/scriptgt lt/headgt ltbodygt ltformgt ltinput
type"button" value"Change toYellow"
name"buttonY onClick"white()"gt ltinput
type"button" value"Change to White"
name"buttonW onClick"yellow()"gt
lt/formgt lt/bodygtlt/htmlgt
50Script in Head
- ltheadgt lttitlegtwelcome!lt/titlegt ltscript
gt alert (Welcome!') lt/scriptgt - lt/headgt
- This will display the alert before the page
starts loading. Itll disappear when page loads.
A function would be called from the body and
executed.
51Debugging Your JavaScript Programs
- Three types of errors
- Load-time errors (occurs when the script is
loading) - Run-time errors (occurs when the being executed)
- Logical errors (free from syntax and structural
mistakes, but result in incorrect results)
52Common Mistakes
- You need to debug your program fix the mistakes
w/o adding new ones. - Common mistakes include
- Misspelling a variable name
- Mismatched parentheses or braces
- Mismatched quotes
- Missing quotes
- Using ( instead of or
- Using in place of
53Tips for Writing Good JavaScript Code
- Use good layout to make your code more readable.
Indent command blocks to make them easier to read
and to set them off from other code - Use descriptive variable names to indicate the
purpose of your variables - Be careful how you use uppercase and lowercase
letters in your code, because JavaScript commands
and names are case-sensitive
54Tips for Writing Good JavaScript Code
- Add comments to your code to document the purpose
of each script - Initialize all variables at the top of your
script and insert comments describing the purpose
and nature of your variables - Create customized functions that can be reused in
different scripts. Place your customized
functions in external files to make them
available to your entire Web site
55Summary
- Objects
- Properties
- Methods
- Variables
- Push buttons
- Events and handlers-inside HTML tags
- functions
56Summary
- Given an HTML file containing a script, you
should be able to show the corresponding web
page. - Given a web page, you should be able to show the
corresponding HTML file.