02 Javascript
02 Javascript
Tonight
A little more with arrays Logical Operators and Flow Control Functions Regular Expressions
There's really no difference, since the number work as labels, but you can use the distinction.
An Array of Days
Here, we make a date object and pass it's properties into some variables
var dateObj = new Date(document.lastModified); var wday = days[dateObj.getDay() + 1]; var lmonth = months[dateObj.getMonth() + 1]; var date = dateObj.getDate(); var fyear = dateObj.getFullYear();
<!-- Original source for this script from http://javascript.internet.com/page-details/last-modified.html#source Modifications (mainly deletions!) by bil hays var days = new Array(8); days[1] = "Sunday"; days[2] = "Monday"; days[3] = "Tuesday"; days[4] = "Wednesday"; days[5] = "Thursday"; days[6] = "Friday"; days[7] = "Saturday"; var months = new Array(13); months[1] = "January"; months[2] = "February"; months[3] = "March"; months[4] = "April"; months[5] = "May"; months[6] = "June"; months[7] = "July"; months[8] = "August"; months[9] = "September"; months[10] = "October"; months[11] = "November"; months[12] = "December"; var dateObj = new Date(document.lastModified); var wday = days[dateObj.getDay() + 1]; var lmonth = months[dateObj.getMonth() + 1]; var date = dateObj.getDate(); var fyear = dateObj.getFullYear(); document.write('<small>') document.write("Last Modified: " + wday + ", " + lmonth + " " + date + ", " + fyear); document.write('<br />Author: <a href="mailto:SPAM_BLOCKbil_hays@unc.edu">bil hays</a> (remove the SPAM_BLOCK from the address!)'); document.write('</small>');
from general_functions.js
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
Example:FAQs
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?)
Logical 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)
= != == != ===
= assigns values == denotes equivalence (eg. values are the same) === denotes identity (eg. values AND type are the same)
If Statements
Most basic branch Also if/else and if/else if/else Can be nested
For 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 (count=1;count<=50;count=count + 5) { document.write("The count is " + count + "<br>"); document.write("Around the loop again!<br>") }
While loops
While condition is met, loop continues Use brackets to enclose multiple statements Make sure the condition will be met!
count = 1 while (count <=15) { document.write("The count is " + count + "<br>"); count++; }
Break command: when a condition is met, the loop is broken and control passes out of the loop
<SCRIPT LANGUAGE=JavaScript> count = 1; while( count<= 15) { count++ if (count == 10) break; document.write("The count is " + count + "<br>"); } </SCRIPT>
Continue command: when a condition is met, the loop is broken but control passes to the top of the loop
<SCRIPT LANGUAGE=JavaScript> count = 1; while( count<= 15) { count++ if (count == 10) continue; document.write("The count is " + count + "<br>"); } </SCRIPT>
Switch
count = 1; while( count<= 15) { switch(count) { case 5: document.write("We reached 5!<br>"); break; case 10: document.write("Now 10!<br>"); break; case 15: document.write("Finally, 15, Done!<br>"); break; default: document.write("The count is " + count + "<br>"); } count++; }
Functions
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
Functions: 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 + "."; }
<FORM ACTION="" METHOD=POST name="date_in_bar"> <INPUT TYPE=button NAME="date_in_bar_button" VALUE="Put Date in Status Bar" onclick="dateinbar()"> </FORM>
Functions: mouseout_test
25
Silly 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
Functions: Slideshow
<img alt="slide 1" src="data/Slide1.jpg" style="width: 720px; height: 540px;" name="main_slide"><br> <img alt="Navigation Previous" src="nav_previous.gif" style="width: 30px; height: 30px;" onclick="change_slide('prev')"> <img alt="Navigation Next" src="nav_next.gif" style="width: 30px; height: 30px;" onclick="change_slide('next')"><br>
Functions: Slideshow
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
var slides = new Array() var data_dir = './data'; slides[1] = data_dir + '/Slide1.jpg'; // This, for troubleshooting // alert(slides[1]); slides[2] = data_dir + '/Slide2.jpg'; slides[3] = data_dir + '/Slide3.jpg'; slides[4] = data_dir + '/Slide4.jpg'; slides[5] = data_dir + '/Slide5.jpg'; slides[6] = data_dir + '/Slide6.jpg'; slides[7] = data_dir + '/Slide7.jpg'; slides[8] = data_dir + '/Slide8.jpg';
<form action="" method="POST" name="buttons"> <div id="buttons" style="text-align: center;"> <input type="button" name="start" value="Start" onclick="slide_number = 1 ; document.slide.src=slides[1];"> <input type="button" name="previous" value="Previous Slide" onclick="slide_number-- ; document.slide.src=slides[slide_number];"> <input type="button" name="next" value="Next Slide" onclick="slide_number++ ; document.slide.src=slides[slide_number];"> </div> </form>
slide_show01.html
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 < total_slides) { slide_number++; document.slide.src= slides[slide_number].src; document.text_input_box.text_box1.value = slides[slide_number].src; } } slide_show02.html
Things 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
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
Write_titles()
function write_titles() { var open_a = "a"; document.write('<form action="" name="title_list" \ onchange="goto_slide(document.title_list.value)">'); for (slide_number = 1; slide_number<= total_slides; slide_number++) { if (titles[slide_number] != null) { document.write('<input type="radio" name="radio_button" value="' + slide_number + '" onclick="goto_slide(' + slide_number + ')">' + titles[slide_number] + '<br>'); } else { document.write('<input type="radio" name="radio_button" value="' + slide_number+ '" onclick="goto_slide(' + slide_number + ')">' + "Slide Number " + slide_number + '<br>'); } } document.write('</form>'); }
Still requires that you put in the number of slides, and build an array of titles.
Regular 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?
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
Building 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 method re = new RegExp("abc"); Use the latter with user input or where the expression will change
Example of test
function testRegEx(string, expression) { re = new RegExp(expression) if (re.test(string)) { document.write("<p>A match is found!</p>"); } else { document.write("<p>No Match</p>"); } } RegularExpressions.html
Special 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
Special Characters
\ is also used for indicating nonprintable ascii \n is a new line \r is a carriage return \t is a tab \s is a single white space
Special Characters
+ matches the preceding char 1 or more times, thus /do+m/ matches "dom" and "doom" * matches the preceding char 0 or more times . matches any single character ? matches the preceding character 0 or 1 time
Example in a form
Regular_Expression_Form03.html
Greedy Expressions
Expressions are "greedy" by default, and try to match the maximum number of times