320 likes | 502 Vues
JavaScript Global Functions and Objects II. Array String Document and Adding Cookies Forms Style, Cascading Style Sheets (CSS) and Dynamic HTML (DHTML). Name of array. c[ 0 ]. 56. c[ 1 ]. 70. c[ 2 ]. 80. c[ 3 ]. 51. c[ 4 ]. 72. index of the data value within the array.
E N D
JavaScript Global Functions and ObjectsII • Array • String • Document and Adding Cookies • Forms • Style, Cascading Style Sheets (CSS) and Dynamic HTML (DHTML)
Name of array c[ 0 ] 56 c[ 1 ] 70 c[ 2 ] 80 c[ 3 ] 51 c[ 4 ] 72 index of the data value within the array Array Objects Arrays - An arrayis a collection of data values. • Each data value in an array has an index • The first data value is the 0th value (its index is 0) • To create a new array, we can specify the size as the argument for the Array constructor: • var c = new Array(5); • c contains 5 values, with indexes : 0, 1, 2, 3, 4 • To access a specific value in an array, we write: • array_name [ index_of_value] • Why do we need Arrays? • Allow us to use one single name to refer to all values in the collection. • Easy to handle the values in the collection. var c; c = new Array(5); c[0]=56; c[1]=70; c[2]=80; c[3]=51; c[4]=72; alert("The 3rd value is " + c[2]);
Array Objects • Example 1: To hold 5 marks • /* [METHOD 1] Not using array */ • var mark1,mark2,mark3,mark4,mark5; • mark1=60; • mark2=70; • mark3=85; • mark4=68; • mark5=90; /* [METHOD 2] Using array */ var marks=new Array(5); marks[0]=60; marks[1]=70; marks[2]=85; marks[3]=68; marks[4]=90; Only need one array name Need five variable names • /* [METHOD 2] All marks in One array : var marks=new Array(500); */ • var i; • i=0; • while (i<500) • { document.write(marks[i]+"<br/>"); • i++; • } • Example 2: To display five hundred marks • /* [METHOD 1] Marks stored in 500 variables : var mark1, mark2, mark3, mark4, .. ; */ • document.write(mark1+"<br/>"); • document.write(mark2+"<br/>"); • document.write(mark3+"<br/>"); • document.write(mark4+"<br/>"); • document.write(mark5+"<br/>"); • document.write(mark6+"<br/>"); • document.write(mark7+"<br/>"); • document.write(mark8+"<br/>"); • document.write(mark9+"<br/>"); • document.write(mark10+"<br/>"); • document.write(mark11+"<br/>"); • document.write(mark12+"<br/>"); The loop is severallines only!! 500 lines of document.write(..)! [Lec09_Slide3_Array.htm]
Name of array c[ 0 ] 56 c[ 1 ] 70 c[ 2 ] 80 c[ 3 ] 51 c[ 4 ] 72 index of the data value within the array Array Objects • We may also specify the array contents during construction: • var c = new Array(56, 70, 80, 51, 72); • If only one argument is passed to the constructor, this argument specifies the size of the array. eg. var c = new Array(5); //5 elements • If two or more arguments: all arguments are treated as array contents. Eg. new Array(56, 70), or new Array(56, 70, 80).. • The .length property tells the number of values in the array. • Example: var c = new Array(56, 70, 80, 51, 72); alert(c.length);
Array Objects Application: The Random Student Picker • The page contains a global array for storing 5 values. • When the document is loaded, • (1) users will be asked to input 5 student IDs. The IDs are stored in the array immediately. • (2) the IDs are shown in the document (document.write(..)) • The pseudo-URL is displayed after the student IDs. • When being clicked, • (1) generate a random number among 0, 1, 2, 3, 4 as the array index. • (2) use this random index to refer to a value in the array ==> random student is picked.
//Ask for all IDs and //set the content in the array function setupIDs() { var i=0; while (i<5) { all[i]=prompt("Input a student ID"); i++; } } //Write all IDs to the document function writeIDsToDocument() { var i=0; while (i<5) { document.write(all[i]); document.write('<br/>'); i++; } } //Select a random student ID from the array function pickOne() { var idx=Math.floor(Math.random()*5); document.getElementById("result").innerHTML=all[idx]; } <body > <h2>Random Student Picker</h2> <SCRIPT LANGUAGE=javascript> //The global array of student IDs var all = new Array(5); setupIDs(); writeIDsToDocument(); </SCRIPT> <a href="javascript: pickOne();"> Pick a student</a> : <span id="result"></span> </body>
Strings • More about String Manipulations • Each string may contain 0 or more characters. • The .length property tells the number of characters in the string. Examples: var x='McDonald\'s'; alert(x+":"+x.length); var x=‘McDonald’; alert(x.length); • Each character in a string has an index. • The first character is located at index 0. • To get the character at a given location: • The charAt(index)method: • Returns the character at the givenindex. • If indexis wrong (eg., too large), empty string is returned. var x="Computer Programming"; var i=0; while (i<x.length) { document.write(i+": "); document.write(x.charAt(i)); document.write("<br/>"); i++; }
Strings • Search a substring inside a string: • indexOf(substring, start_index) • Searches substring starting from position start_index. • Once substringis found, its index is returned. If substring is not found, -1 is returned. • The argument start_indexis optional (if not specified, the search starts at index 0). • lastIndexOf(substring, end_index) • (Similar to indexOf) Searches for the last occurrence of substring starting from position end_index and searching toward the beginning of the string. • The argument end_indexis optional (if not specified, the search starts at the end). var x="Computer Programming"; alert(x.indexOf("o")); alert(x.indexOf("o",2)); alert(x.lastIndexOf("mm")); alert(x.lastIndexOf("mm",13));
Strings • Copy a substring from a string: • substring(start_index, end_index) • Returns a new string that is a copy of the characters from start_index up to but not including end_index in the original string. • The original string is not changed. var x="Computer Programming"; var subX=x.substring(3,6); alert(x); alert(subX); • Convert to uppercase / lowercase: • toLowerCase() and toUpperCase() • Return the result as a new string. • The original string is not changed. var x="McDonald's"; alert(x.toLowerCase()); var x="McDonald's"; alert(x.toUpperCase());
Strings Splitting and Joining Strings var words=new Array( "apple", "pineapple", "cherry"); var result=words.join(","); alert(result); (1) array method: join(separator_string) Example: To join some words together, separated by "," Original content should be an array of words (strings). Result will be one single long string. Separator (in this example) is a comma ",". Note that the original array content is not changed. (2) string method: split(separator_string) Example: To split a sentence into words: Original content should be a string. Result will be an array of words (strings). Separator (in this example)is a space. Note that the original string is not changed. var x="I like programming"; var result=x.split(" "); var i=0; while (i<result.length) { document.write(result[i]); document.write("<br/>"); i++; }
Convert Application: Automatic Formatting Change all CityU to bold and red. - The user can type the contents in the textarea and click convert, - Each "CityU" in the content is changed to bold and red. How? (1) firstly split by "CityU" to obtain several short sections (2) then join the short sections with <b><font color=red>CityU</font></b> <BODY> <h2> Automatic Formatting</h2> <form name="F1"> <textarea name="t1" cols=40 rows=10></textarea> </form> <a href="javascript: var x= document.F1.t1.value; var sections=x.split('CityU'); /*obtain short sections: section[0], section[1],..*/ var result=sections.join('<b><font color=red>CityU</font></b>'); document.getElementById('result').innerHTML=result; void(0);">Convert</a> <p id="result"></p> </BODY> alert(sections[0]); alert(sections[1]); alert(sections[2]); alert(result);
Strings • Character Unicode • Unicode is a set of characters that represents a large portion of the world's languages. • Contains ASCII codes as a subset: • 'a'-'z' : 97-122 'A'-'Z': 65-90 '0'-'9': 48-57 • Space: 32 • new line: 10 • Common punctuations and math operators: 33-47, 58-64, 91-96, and 123-126 • charCodeAt(index) • Returns the unicode of a character within a string according to its index in the string. • Example: var x="abcdefg McDonald's"; • alert(x.charCodeAt(0)); //Gives 97 (‘a’) • alert(x.charCodeAt(1)); //Gives 98 (‘b’) • alert(x.charCodeAt(2)); //Gives 99 (‘c’) • alert(x.charCodeAt(16)); //Gives 39 (what is this?) • fromCharCode(c) • Returns a new string containing the character according to the given unicode c. • fromCharCode does not need an existing string object (just like Math methods). • Example: var x=String.fromCharCode(65); • alert(x); // Gives 'A'. We can use a loop to show a range of characters.[See Lec09_Slide12_ShowPunctuations.htm]
Strings 'A‘ 'B' 'B' 'C' .. 'H' 'I' .. 'Z' '[' 'a' 'b' Application: Simple Cryptography //Encrypt a string with 5 characters var x="Happy"; var code0, code1, code2, code3, code4; var newCode0, newCode1, newCode2, newCode3, newCode4; var result; code0 = x.charCodeAt(0); //Unicode of 'H' code1 = x.charCodeAt(1); //Unicode of 'a' code2 = x.charCodeAt(2); code3 = x.charCodeAt(3); code4 = x.charCodeAt(4); newCode0=code0+1; //Unicode of 'I' (next of 'H') newCode1=code1+1; //Unicode of 'b' (next of 'a') newCode2=code2+1; newCode3=code3+1; newCode4=code4+1; result= String.fromCharCode(newCode0)+ //'I' String.fromCharCode(newCode1)+ //'b' String.fromCharCode(newCode2)+ String.fromCharCode(newCode3)+ String.fromCharCode(newCode4); alert(result); "Happy" Encryption
Strings Application: Simple Cryptography Rewrite the encryption code to create a useful function: //Convert input string to encrypted string function encrypt(input) { var code; var newCode; var result=""; var i=0; while (i<input.length) { code=input.charCodeAt(i); newCode=code+1; result+=String.fromCharCode(newCode) i++; } return result; } encrypt("Happy") "Ibqqz"
//Convert input string to encrypted string function encrypt(input) { var code; var newCode; var result=""; var i=0; while (i<input.length) { code=input.charCodeAt(i); newCode=code+1; result+=String.fromCharCode(newCode) i++; } return result; } <form name="F1"> <textarea name="t1" cols=40 rows=10></textarea> </br> <input type="button" value="encrypt" onclick="document.getElementById('result').innerHTML=encrypt(document.F1.t1.value)"/> </form> <span id="result"></span> • Your exercise: • Add one button to restore an input encrypted string back to original string. (Add another function, function restore(input), for this purpose.)
Document • More about Document • Each window object has a document property. • The document property refers to a document object that represents the HTML document displayed in the window. • Common Document methods: • open() : Begin a new document, erasing all existing content and reset each property. • Actually, it is often used just for resetting the contents. • write( ) : Append text to the currently open document. • close( ) : Actually not much used. • Once a document has finished loading (<body>..</body>), if you make a single call to document.write(), the call will automatically clear old content and write new content to the page. • ie. Old contents will be cleared first!! Note: onload happens just AFTER <body>..</body>!! • So, to write dynamic contents by JavaScript, you should call document.write() within loading of <body>..</body>. Don’t use document.write() upon pseudo-URL, onload, onclick etc.. (unless you allow current contents to be cleared). Recall week 2 lecture: To add new but keeping current content, use innerHTML!! (not document.write)
Document • More about Document • Common Document properties: • bgColor, fgColor (ie. text) : corresponds to the bgcolor and text attributes in <body>. • linkColor : color of unvisited hyperlinks. • vlinkColor : color of visited links. • alinkColor : color of a link while the user is clicking on it. • title : the content between <title> and </title>. • lastModified : the modification date of the document.
Document Cookies A cookie is a small amount of named data stored by the web browser. A common usage of cookies is to recall user preferences across web browsing sessions. We can create, read, modify, and delete a cookie through the document.cookie property. A typical location of cookies stored in the computer: • Internet Explorer • Tools menu • Internet Options • General: Temporary Internet Files - Settings
Document Session cookies and persistent cookies Session cookie: Automatically deleted when the user exits the browser. To create or modify a session cookie: document.cookie = "name=value" For example: document.cookie = "imagesPerPage=6" Persistent cookie: Assigned an expiration date/time, after that the cookie will be deleted. Stored in the computer's hard disk. To create or modify a persistent cookie, we need to set the expiration date: document.cookie = "name=value;expires=UTCDate" For example: var expireDate=new Date(2010,11,31); document.cookie = "imagesPerPage=6;expires=" + expireDate.toUTCString();
Document • Deleting Cookies • Session cookies are automatically deleted when the browser session ends.Persistent cookies are automatically deleted when it is expired. • To remove a cookie manually, we may set its expiration date to a date earlier than today, ie. forces the browser to delete the cookie. • Reading Cookies • Cookies can be retrieved by JavaScript by referring to the document.cookie property. • document.cookie contains information in one of the following forms: (1) "" (empty): if no cookie is stored. (2) "name=value": if there is only one cookie. (3) "name1=value1; name2=value2; ..": if there are 2 or more cookies stored by the website. Example: Suppose the cookies for 2 values: height=180 and imagesPerPage=2 are stored. To get the values, we may apply the string methods like split, substring, indexOf, etc.. alert(document.cookie)
Application: Store image height and page size settings using cookies [Refer to Lec09_Slide19to22_GalleryWithCookies.html] <BODY onload="loadCookies();makeHtmlOfImages()"> … <input type='button' value='increase height' … onclick=" imgHeight+=10; recordHeightCookie(); makeHtmlOfImages()" /> <input type='button' value='decrease height' … onclick=" imgHeight-=10; recordHeightCookie(); makeHtmlOfImages()" /> <input type='button' value='set number of images per page' … onclick=" page_size=parseInt(prompt('New number of images per page:',page_size)); recordPageSizeCookie(); currentStartImageNum=1; makeHtmlOfImages()" />
//Store a cookie for the page size //(number of images per page) function recordPageSizeCookie() { //Set expire date var expireDate=new Date(2010,11,31); document.cookie = "imagesPerPage=" + page_size + ";" + "expires=" + expireDate.toUTCString(); } //Store a cookie for the image height setting function recordHeightCookie() { //Set expire date var expireDate=new Date(2010,11,31); document.cookie = "height=" + imgHeight + ";" + "expires=" + expireDate.toUTCString(); } //Recall settings from cookies function loadCookies() { var idxHeight; //index of "height=" in the cookie string var idxImagePerPage; //index of "imagesPerPage=" in the cookie string //Find the values of idxHeight and idxImagePerPage idxHeight=document.cookie.indexOf('height='); idxImagePerPage=document.cookie.indexOf('imagesPerPage='); //If "height=" exists in the cookies (ie. idxHeight is not -1), set the value of imgHeight if (idxHeight!=-1) imgHeight=parseInt(document.cookie.substring(idxHeight+7,99)); /*99 means up to the 99th position in the cookie string (parseInt will only extract the starting numeric contents in this substring)*/ //If "imagesPerPage=" exists in the cookies (ie. idxImagePerPage is not -1), set the value of page_size if (idxImagePerPage!=-1) page_size=parseInt(document.cookie.substring(idxImagePerPage+14,99)); }
<input type="checkbox"/> Big images <input type="password"/> <textarea cols=40 rows=10></textarea> <input type="radio" name="fruit"/>Apple <input type="radio" name="fruit"/>Orange <input type="radio" name="fruit"/>Pear <input type="radio" name="fruit"/>Grape Forms • More about Forms • Common HTML form elements: • Button <input type="button"> • Checkbox <input type="checkbox"> • Password <input type="password"> • Select/Option <select> and <option> • Radio button <input type="radio"> • Text <input type="text"> • Textarea <textarea> <select name="op"> <option value="apple"/>Apple <option value="orange"/>Orange <option value="pear"/>Pear <option value="grape"/>Grape </select>
[Refer to Lec09_Slide24_form.html] <form name="F1"> <input type="checkbox" name="cb"/> Big images <br/> <input type="password" name="pw"/> <br/> <textarea cols=40 rows=10 name="tb"></textarea> <br/> <select name="op"> <option value="apple"/>Apple <option value="orange"/>Orange <option value="pear"/>Pear <option value="grape"/>Grape </select> <br/> <input type="radio" name="fruit"/>Apple <input type="radio" name="fruit“ checked=true/>Orange <input type="radio" name="fruit"/>Pear <input type="radio" name="fruit“/>Grape </form> <a href="javascript: alert( document.F1.cb.checked+'\n'+ document.F1.pw.value+'\n'+ document.F1.tb.value+'\n'+ document.F1.op.value+'\n'+ document.F1.fruit[0].checked+'\n'+ document.F1.fruit[1].checked+'\n'+ document.F1.fruit[2].checked+'\n'+ document.F1.fruit[3].checked+'\n' );">show all values</a> For preparation of test / exam: Just need to understand, No need to memorize.
Forms • Elements in a form can be accessed as a form elements array: • document.form_name.elements[ ] • Example: An array of 4 textboxes: <form name="F1"> Please input the names:<br/> <input type="text"/></br> <input type="text"/></br> <input type="text"/></br> <input type="text"/></br> </form> alert( document.F1.elements[0].value+ document.F1.elements[1].value+ document.F1.elements[2].value+ document.F1.elements[3].value)
Forms • Checkboxes: • A small square that the user can select or deselect by clicking. • Useful properties: • checked: a boolean value that specifies whether a checkbox is currently checked. • disabled: a boolean value that specifies whether the checkbox is disabled and is unavailable for user input. <body onload="showDate()"> <form name="F1"> <input type="checkbox" name="choice" onclick="showDate()"/> US Date format </form> Date is: <span id="display"></span> </body> //Show date in the format according to the US Date format checkbox function showDate() { var x=new Date; if (document.F1.choice.checked==true) document.getElementById("display").innerHTML=(x.getMonth()+1)+'/'+x.getDate()+'/'+x.getFullYear(); else document.getElementById("display").innerHTML=x.getDate()+'/'+(x.getMonth()+1)+'/'+x.getFullYear(); }
10 checkboxes will be handled as document.F1.elements[..] count the selected checkboxes, ie. if document.F1.elements[..].checkedequals true set all document.F1.elements[..].checkedto false Application – Array of checkboxes A list of attractions in Hong Kong Disneyland. • <form name="F1"> • <input type="checkbox" />Festival of the Lion King</br> • <input type="checkbox" />Jungle River Cruise</br> • <input type="checkbox" />Rafts to Tarzan Island</br> • <input type="checkbox" />Liki Tikis</br> • <input type="checkbox" />Dumbo the Flying Elephant</br> • <input type="checkbox" />Mad Hatter Tea Cups</br> • <input type="checkbox" />Cinderella Carousel</br> • <input type="checkbox" />Golden Mickeys at Theater</br> • <input type="checkbox" />Space Mountain</br> • <input type="checkbox" />Buzz Lightyear Blasters</br> • </form> 2 pseudo-URLs <a href="javascript:showSelectionCount();">Show count of selected games</a> : <span id="count"></span> <a href="javascript:cancelAllSelections();">Reset Selections</a>
Demo: Array of checkboxes document.FormName.elements[..].checked • <form name="F1"> • <input type="checkbox" />Festival of the Lion King</br> • <input type="checkbox" />Jungle River Cruise</br> • … • </form> <a href="javascript:showSelectionCount();">Show count of selected games</a> : <span id="count"></span> <a href="javascript:cancelAllSelections();">Reset Selections</a> //Display the count of selected choices function showSelectionCount() { var i=0; var tot=0; while (i<10) { if (document.F1.elements[i].checked==true) tot++; i++; } document.getElementById("count").innerHTML=tot; } //Reset all checkboxes function cancelAllSelections() { var i=0; while (i<10) { document.F1.elements[i].checked=false; i++; } } Exercise: Add a pseudo-URL for selecting all choices.
Demo: Array of checkboxes document.FormName.elements[..].disabled Add a Young Visitor checkbox: 3 games are disabled for young visitors: document.F1.elements[4] document.F1.elements[5] document.F1.elements[8] <form name="FGroup"> <input type="checkbox" name="Young" onclick="updateForm()"/>Young Visitor </form> //Update form according to the Young Visitor checkbox function updateForm() { if (document.FGroup.Young.checked==true) { document.F1.elements[4].disabled=true; document.F1.elements[5].disabled=true; document.F1.elements[8].disabled=true; document.F1.elements[4].checked=false; document.F1.elements[5].checked=false; document.F1.elements[8].checked=false; } else { document.F1.elements[4].disabled=false; document.F1.elements[5].disabled=false; document.F1.elements[8].disabled=false; } }
Cascading Style Sheets and Dynamic HTMLStyle– CSS property of HTML Elements • Cascading Style Sheets (CSS) • CSS: a standard for specifying the visual presentation of HTML documents. • Example in HTML: • <img id="img1" src="monster1.gif" style="position: absolute;top:100;left:0;" /> • Other commonly used styles: • background-color, font-size, height, width, z-index • Dynamic HTML (DHTML) • We can use JavaScript to dynamically change colors, position of elements and even to hide and show them, by setting their styleproperties. • Examples in JavaScript: • document.getElementById("img1").style.left=300; document.getElementById("guess_color_bar").style.backgroundColor=0xFFFF00; • Many CSS style attributes contain hyphens, eg. font-size. But hyphens are interpreted as minus in JavaScript. • Therefore their names in JavaScript are slightly different: • If a CSS attribute name contains any hyphen, its name in JavaScript is formed by removing the hyphen and capitalizing the letter following the hyphen, eg. font-size fontSize.
Application: 10 textboxes to count random numbers • Random numbers (0-9) are generated every 100 ms. • Their occurrences are shown in 10 text boxes: • (1) The count is shown as the value in the text boxes • (2) The width of text boxes are changed correspondingly (width = count * 10) • <body onload="setInterval('newRandom()',100);"> • <h2>Animation of Random Numbers (0-9)</h2> • <form name="F1"> • Count of 0: <input type="text" style="width:0" value="0"/><br/> • Count of 1: <input type="text" style="width:0" value="0"/><br/> • Count of 2: <input type="text" style="width:0" value="0"/><br/> • Count of 3: <input type="text" style="width:0" value="0"/><br/> • Count of 4: <input type="text" style="width:0" value="0"/><br/> • Count of 5: <input type="text" style="width:0" value="0"/><br/> • Count of 6: <input type="text" style="width:0" value="0"/><br/> • Count of 7: <input type="text" style="width:0" value="0"/><br/> • Count of 8: <input type="text" style="width:0" value="0"/><br/> • Count of 9: <input type="text" style="width:0" value="0"/><br/> • </form> • </body> //Generate a random number between 0 and 9 and update the counter: function newRandom() { var x=Math.floor(Math.random()*10); document.F1.elements[x].value=parseInt(document.F1.elements[x].value)+1; document.F1.elements[x].style.width=document.F1.elements[x].value*10; }
Summary • Array • Application: Random Student Picker • String: index, length, searching, substrings, case conversion, split and join • Application: Automatic Formatting • Character <-> Unicode • Application: Simple Cryptography • Document: open, write, close, title, lastModified, bgColor, ... • Cookies Added to My Picture Gallery (Using strings and arrays) • Forms: more input types, elements array, using Checkboxes • Application: A List of Attractions in Hong Kong Disneyland. • Style / Cascading Style Sheets (CSS) and Dynamic HTML (DHTML) • Application: 10 textboxes to count random numbers