Title: Javascript, The Movie
1Javascript, The Movie
2Tonight
- A little more with arrays
- Logical Operators and Flow Control
- Functions
- Regular Expressions
3Arrays can be indexed or associative 20array.html
var myfisharray "goldfish", "betta",
"cichlid", "tuna" document.write(myfisharray0
"ltbr /gt") document.write(myfisharray3
"ltbr /gt") var myotherarray new
Array() myotherarray"sam" "Sam lives
here" myotherarray"susie" "Susie lives
here" document.write(myotherarray"sam" "ltbr
/gt") document.write(myotherarray"susie" "ltbr
/gt")
There's really no difference, since the number
work as labels, but you can use the distinction.
4Using Arrays A Decent Last Modified
- We looked at the date() method with the
lastModified property of the document - We can use this approach with arrays to make a
custom last modified time stamp for web pages - If you put this in an external script, you can
use the same script to write a custom footer for
a web site (as I have)
5An Array of Days
- Make an array of day names
var days new Array(8)days1
"Sunday"days2 "Monday"days3
"Tuesday"days4 "Wednesday"days5
"Thursday"days6 "Friday"days7
"Saturday"
6An object and some variables
- Here, we make a date object and pass it's
properties into some variables
var dateObj new Date(document.lastModified)var
wday daysdateObj.getDay() 1var lmonth
monthsdateObj.getMonth() 1var date
dateObj.getDate()var fyear dateObj.getFullYear
()
7lt!-- Original source for this script from
http//javascript.internet.com/page-details/last-m
odified.htmlsource Modifications (mainly
deletions!) by bil haysvar days new
Array(8)days1 "Sunday"days2
"Monday"days3 "Tuesday"days4
"Wednesday"days5 "Thursday"days6
"Friday"days7 "Saturday"var months new
Array(13)months1 "January"months2
"February"months3 "March"months4
"April"months5 "May"months6
"June"months7 "July"months8
"August"months9 "September"months10
"October"months11 "November"months12
"December"var dateObj new Date(document.lastMo
dified)var wday daysdateObj.getDay()
1var lmonth monthsdateObj.getMonth()
1var date dateObj.getDate()var fyear
dateObj.getFullYear()document.write('ltsmallgt')d
ocument.write("Last Modified " wday ", "
lmonth " " date ", " fyear)document.writ
e('ltbr /gtAuthor lta href"mailtoSPAM_BLOCKbil_hay
s_at_unc.edu"gtbil hayslt/agt (remove the SPAM_BLOCK
from the address!)')document.write('lt/smallgt')
from general_functions.js
8Arrays and External Scripts
- One way to use arrays is to make an external
javascript with just the data, and a second
external javascript with your program to build
the page. - This means you can have different data for
different pages, each controlled by a single
program - The basic technique is chunking code
- One Option
- Reference the program script as an absolute URL
- Reference the data array as a relative URL
9ExampleFAQs
- faq_build.js is the script that builds the page
- faq_data.js holds the data
- faq.html references both
- Starting with this and expanding it would be a
fine project if you're getting started (what
could you add?)
10Logical Operators
- "and" expressed with
- "or" expressed with
- "not" expressed with !
- Thus
- true true true
- true false false
- true false true
- !true false
- Example
if (var1 1 var2 2)
11 ! !
- assigns values
- denotes equivalence (eg. values are the same)
- denotes identity (eg. values AND type are the
same)
12If Statements
- Most basic branch
- Also if/else and if/else if/else
- Can be nested
if (class "INLS") if (section "668")
document.write("hooray!")
else document.write("too bad!")
13For loops
- Loop is run for x times, where x is defined
- Brackets for more than one statement
- Good for where the variable can be used for more
than just the loop
for (count1countlt50countcount 5)
document.write("The count is " count
"ltbrgt") document.write("Around the loop
again!ltbrgt")
14While loops
- While condition is met, loop continues
- Use brackets to enclose multiple statements
- Make sure the condition will be met!
count 1 while (count lt15) document.write("The
count is " count "ltbrgt") count
15Incrementing and Decrementing
- Use to increment
- Use -- to decrement
- count is the same as countcount1
16Breaking the loop
- Break command when a condition is met, the loop
is broken and control passes out of the loop
ltSCRIPT LANGUAGEJavaScriptgt count 1 while(
countlt 15) count if (count 10)
break document.write("The count is " count
"ltbrgt") lt/SCRIPTgt
17Breaking the loop
- Continue command when a condition is met, the
loop is broken but control passes to the top of
the loop
ltSCRIPT LANGUAGEJavaScriptgt count 1 while(
countlt 15) count if (count 10)
continue document.write("The count is "
count "ltbrgt") lt/SCRIPTgt
18Switch
count 1 while( countlt 15) switch(count)
case 5 document.write("We
reached 5!ltbrgt") break case
10 document.write("Now 10!ltbrgt")
break case 15 document.write("Finall
y, 15, Done!ltbrgt") break default
document.write("The count is " count
"ltbrgt") count
19Other control structures
- do while
- throw, try, catch
- for in
20Functions
- Good for an action that will be repeated
- In a way, building a custom method
- Functions can accept parameters
- Variable for functions can be local or global
- Local variables are known only within the
function - Local variables are declared with a "var"
statement - Variables declared otherwise are global
- Global variables are available throughout the
document
21Functions An Example
function dateinbar() var d new Date() var y
d.getFullYear() var m d.getMonth() 1
var d d.getDate() var t m '/' d '/'
y ' ' defaultStatus "You arrived at the
page on " t "." ltFORM ACTION""
METHODPOST name"date_in_bar"gt ltINPUT
TYPEbutton NAME"date_in_bar_button"
VALUE"Put Date in Status Bar" onclick"dateinbar(
)"gt lt/FORMgt
22Functions mouseout_test
- A simple function, called bywindow.onmouseout
out_text
function out_text() if (alert_messagex)
window.moveTo(0, 0)
window.resizeTo(window.screen.availWidth,
window.screen.availHeight)
alert(x alert_messagex)
window.focus() x
25
23Silly Stuff
- Browsers can detect a lot of events
- onblur detects when you leave something behind,
see 26_blur_test.html - You can also manipulate, to an extent, windows,
although security is closing in there, see
27_window_manipulation.html
24Functions Slideshow
- Simple event handler in HTML
ltimg alt"slide 1" src"data/Slide1.jpg"
style"width 720px height 540px"
name"main_slide"gtltbrgt ltimg alt"Navigation
Previous" src"nav_previous.gif"
style"width 30px height 30px"
onclick"change_slide('prev')"gt ltimg
alt"Navigation Next" src"nav_next.gif"
style"width 30px height 30px"
onclick"change_slide('next')"gtltbrgt
25Functions Slideshow
- Simple function in Javascript, this is a very
simple manipulation of a DOM object
var x "1" function change_slide(y) if (y
"next") x if (y
"prev") x-- document.main_slide
.src"data/Slide" x ".jpg"
slide_show00.html
26More than one way
- You could also build an array.
var slides new Array() var data_dir
'./data' slides1 data_dir
'/Slide1.jpg' // This, for troubleshooting //
alert(slides1) slides2 data_dir
'/Slide2.jpg' slides3 data_dir
'/Slide3.jpg' slides4 data_dir
'/Slide4.jpg' slides5 data_dir
'/Slide5.jpg' slides6 data_dir
'/Slide6.jpg' slides7 data_dir
'/Slide7.jpg' slides8 data_dir
'/Slide8.jpg'
27More than one way
- and walk that with events
ltform action"" method"POST" name"buttons"gt ltdiv
id"buttons" style"text-align center"gt
ltinput type"button" name"start" value"Start"
onclick"slide_number 1
document.slide.srcslides1"gt ltinput
type"button" name"previous" value"Previous
Slide" onclick"slide_number--
document.slide.srcslidesslide_number"gt
ltinput type"button" name"next" value"Next
Slide" onclick"slide_number
document.slide.srcslidesslide_number"gt lt/divgt
lt/formgt
slide_show01.html
28Problems with this slideshow?
29Problems with this slideshow?
- Forward and Back, and Up?
- How many slides?
- Titles?
- Skip Slides?
- Only one way to navigate
30Additions and Updates
- See a var for the total number of slides to
control position (this is a hack!), don't fall
off the edge - Multiple functions for actions
- And a text box with the path to the slide
function next_slide() if
(slide_number lt total_slides)
slide_number document.slide.src
slidesslide_number.src
document.text_input_box.text_box1.value
slidesslide_number.src
slide_show02.html
31Things to Notice
- I'm using two arrays, slides and titles in
parallel (I could do this with objects) - I've established a convention for naming
32But I also wanted
- Some sort of index of slides with names
- More flexibility in moving around
- Aha! Radio buttons, and click on slide
- So, what I did was
- Write some pure html form with radio buttons
- Got that working
- Then put in a titles array and
- Wrote some javascript to output that html with
the data from the titles array - Put an event handler on the form to move to any
of the slides, and one on the img, to move
forward one
slide_show03.html
33Write_titles()
function write_titles() var open_a
"a" document.write('ltform action""
name"title_list" \ onchange"goto_slide(d
ocument.title_list.value)"gt') for
(slide_number 1 slide_numberlt total_slides
slide_number) if
(titlesslide_number ! null)
document.write('ltinput type"radio"
name"radio_button" value"'
slide_number '" onclick"goto_slide('
slide_number ')"gt'
titlesslide_number 'ltbrgt')
else
document.write('ltinput type"radio"
name"radio_button" value"'
slide_number '" onclick"goto_slide('
slide_number ')"gt' "Slide
Number " slide_number 'ltbrgt')
document.write('lt/formgt'
)
34Then a cleaner Version
- slide_show04 is pretty much the same
- but the event handler for the radio buttons is
moved to the button from the form - the radio buttons move with slide selection
- Still requires that you put in the number of
slides, and build an array of titles.
35Regular Expressions
- Very arcane
- Very powerful
- Allows pattern matching for strings
- Used in string searches, replacements,
comparisons - Javascript regex are like perl
- We'll look at some simple examples tonight
- What would you use these for?
36Methods associated with regex
- exec A RegExp method that executes a search for
a match in a string. It returns an array of
information. - test A RegExp method that tests for a match in a
string. It returns true or false. - match A String method that executes a search for
a match in a string. It returns an array of
information or null on a mismatch. - search A String method that tests for a match in
a string. It returns the index of the match, or
-1 if the search fails. - replace A String method that replaces the
matched substring with a replacement substring. - split A String method that uses a regular
expression or a fixed string to break a string
into an array of substrings.
from http//www.websina.com/bugzero/kb/regexp.html
37Building an Expression
- Enclosed in / characters
- /abc/ represents the string "abc"
- The expression is an object, created one of two
ways - By assignment (note no quotes!)re /abc/
- With the RegExp methodre new RegExp("abc")
- Use the latter with user input or where the
expression will change
38Example of test
function testRegEx(string, expression) re
new RegExp(expression) if
(re.test(string))
document.write("ltpgtA match is found!lt/pgt")
else document.write("ltpgtNo
Matchlt/pgt")
RegularExpressions.html
39Special Characters
- is used to match the beginning of a string
thus /The/ matches "The fox" - matches at the end thus /fox/ matches "The
fox" - Square brackets are used to match any one of the
characters listed thus aeiou matches vowels - \ is used for escaping special characters
40Special Characters
- \ is also used for indicating non-printable ascii
- \n is a new line
- \r is a carriage return
- \t is a tab
- \s is a single white space
41Special Characters
- matches the preceding char 1 or more times,
thus /dom/ matches "dom" and "doom" - matches the preceding char 0 or more times
- . matches any single character
- ? matches the preceding character 0 or 1 time
42Example in a form
- Regular_Expression_Form03.html
43Greedy Expressions
- Expressions are "greedy" by default, and try to
match the maximum number of times