1 / 43

Javascript, The Movie

Javascript, The Movie. Tonight. A little more with arrays Logical Operators and Flow Control Functions Regular Expressions. Arrays can be indexed or associative: 20array.html. var myfisharray = ["goldfish", "betta", "cichlid", "tuna"]; document.write(myfisharray[0] + "<br />");

elsie
Download Presentation

Javascript, The Movie

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Javascript, The Movie

  2. Tonight • A little more with arrays • Logical Operators and Flow Control • Functions • Regular Expressions

  3. Arrays can be indexed or associative: 20array.html var myfisharray = ["goldfish", "betta", "cichlid", "tuna"]; document.write(myfisharray[0] + "<br />"); document.write(myfisharray[3] + "<br />"); var myotherarray = new Array(); myotherarray["sam"] = "Sam lives here"; myotherarray["susie"] = "Susie lives here"; document.write(myotherarray["sam"] + "<br />"); document.write(myotherarray["susie"] + "<br />"); There's really no difference, since the number work as labels, but you can use the distinction….

  4. 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) Using Arrays: A Decent Last Modified

  5. Make an array of day names… An Array of Days 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";

  6. Here, we make a date object and pass it's properties into some variables An object and 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();

  7. <!-- Original source for this script from http://javascript.internet.com/page-details/last-modified.html#source Modifications (mainly deletions!) by bil haysvar 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

  8. Arrays 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

  9. 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?)

  10. 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)

  11. = != == != === • = assigns values • == denotes equivalence (eg. values are the same) • === denotes identity (eg. values AND type are the same)

  12. If 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!"); } }

  13. 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>") }

  14. 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++; }

  15. Incrementing and Decrementing • Use ++ to increment • Use -- to decrement • count++ is the same as count=count+1

  16. Breaking the loop • 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>

  17. Breaking the loop • 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>

  18. 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++; }

  19. Other control structures • do while • throw, try, catch • for in

  20. 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 • Global variables are available throughout the document

  21. 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>

  22. Functions: mouseout_test • A simple function, called by:window.onmouseout = out_text; function out_text() { if (alert_message[x]) { window.moveTo(0, 0); window.resizeTo(window.screen.availWidth, window.screen.availHeight); alert(x + alert_message[x]); window.focus(); x++; } } 25

  23. 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

  24. Functions: Slideshow • Simple event handler in HTML: <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>

  25. Functions: 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

  26. More than one way • You could also build an array…. 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';

  27. More than one way • …and walk that with events <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

  28. Problems with this slideshow?

  29. Problems with this slideshow? • Forward and Back, and Up? • How many slides? • Titles? • Skip Slides? • Only one way to navigate

  30. Additions 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 < 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

  31. 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

  32. But 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

  33. 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>'); }

  34. Then 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….

  35. 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?

  36. Methods 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

  37. 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 methodre = new RegExp("abc"); • Use the latter with user input or where the expression will change

  38. 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

  39. 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

  40. Special 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

  41. 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

  42. Example in a form • Regular_Expression_Form03.html

  43. Greedy Expressions • Expressions are "greedy" by default, and try to match the maximum number of times

More Related