1 / 67

ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2. Dr. Faisal Al-Qaed. Note using ID attributes.

maisie-cook
Télécharger la présentation

ITCS373: Internet Technology Client Side Processing using JavaScript – Part 2

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. ITCS373: Internet TechnologyClient Side Processing using JavaScript – Part 2 Dr. Faisal Al-Qaed

  2. Note using ID attributes • As you have experienced before, using document.write will overwrite the current webpage by new one, to avoid this issue, you can add id attributes in your HTML tags (i.e. span, div, b, i, etc) and then follow these simple steps to write in your id section: • Add id attribute to your tag i.e. <div id=“mytxt”></div> • In your JavaScript code, you can displays any text or html contents like formatting text, tables, images, forms, etc as follows: • mytxt.innerHTML=“<b>welcome</b>”; • document.getElementById(“mytxt”).innerHTML =“<b>welcome</b>”;

  3. Example <script type="text/javascript"> function changeText3(){ var oldHTML = document.getElementById('para').innerHTML; var newHTML = "<span style='color:#ffffff'>" + oldHTML + "</span>"; document.getElementById('para').innerHTML = newHTML; } </script> <p id='para'>Welcome to the site <b id='boldStuff3'>Bold</b> </p> <form> <input type='button' onclick='changeText3()' value='Change Text'/> </form>

  4. Show/Hide Div Example <html><head><script language-'javascript'> <!-- function hideMe() { document.getElementById('d1').style.visibility='hidden'; } function showMe() { document.getElementById('d1').style.visibility='visible'; } --> </script></head> <body> <a href='javascript:hideMe()'>Hide Score</a> <a href='javascript:showMe()'>Show Score</a> <div id='d1'> <h1>BestScore:</h1> <h3>97 seconds</h3> </div> </body></html>

  5. Collapsible Div • <a href="javascript:;" onmousedown="toggleDiv('mydiv');">Toggle Div Visibility</a> • <script language="javascript">  function toggleDiv(divid){if(document.getElementById(divid).style.display == 'none')       document.getElementById(divid).style.display = 'block'; else        document.getElementById(divid).style.display = 'none';  } </script> • <div id=‘mydiv’>My Div Section</div>

  6. Use Div as Alert Message: Example <html><head> <script language='javascript'> function showDiv(){ document.getElementById("myDiv").style.top=100; document.getElementById("myDiv").style.left=100; } </script></head><body onload='showDiv()'> <h1>Welcome to Div Control</h1> <h1>Try this example to learn How</h1> <h1>to position Div</h1> <h1>Click on Show and Hide</h1> <div id="myDiv" style="position:absolute;border:groove;width:250px;height:100px;background-color:yellow" ><h3>Alert Message</h3></div> <h1 onClick="javascript:document.getElementById('myDiv').style.display='block';"><i>Show Msg </i></h1> <h1 onClick="javascript:document.getElementById('myDiv').style.display='none';"><i>Hide Msg</i></h1> </body></html>

  7. Can You Create This Alert Message?

  8. <html><body> <h1>Welcome to Div Control</h1> <h1>Try this example to learn How</h1> <h1>to position Div</h1> <h1>Click on Show</h1> <div id="myMsg" style="top:200;left:100;position:absolute;border:groove;width:250px;height:120px;background-color:blue" > <h3 align='center'>Alert Message</h3> <div id="myDiv" style="top:22;left:-4;position:absolute;border:groove;width:250px;height:100px;background-color:grey" > <br /><b>&nbsp;&nbsp;Invalid Username or Password</b> <p align='center'><form><input style='color:grey;background-color:blue' type='button' onclick="javascript:document.getElementById('myMsg').style.display='none';" value="Close" /></form></p> </div></div> <h1 onClick="javascript:document.getElementById('myMsg').style.display='block';"><i>Show Div Msg </i></h1> </body></html>

  9. Arrays in JavaScript

  10. Arrays in JavaScript • JavaScript treats arrays as objects • to create an array you must use the keyword new • var a = new Array(); //empty array • var b = new Array(10); //array of size 10 • var c = new Array(2,5,34); //array of size 3, values= 2,5,34

  11. var myArray=new Array(5); //size=5 • myArray[0] = "blue"; • myArray[1] = "red"; • myArray[4] = "purple"; • myArray[“red”]=“gold” which is equivalent to myArray[1]=“gold”

  12. var musicArray = new Array(); //size=0 • musicArray[7] = "Close to the Edge"; //size=8 • musicArray[222] = "Yessongs"; //size=223

  13. var myArray1 = new Array("blue", "red", "purple", "lime", "yellow"); • document.write(myArray1[0]); which would render the following output: blue • document.write(myArray1); which would render the following output, noting that JavaScript does not store the optional space between Elements, but it does store the comma separator: blue,red,purple,lime,yellow

  14. for (var i=0; i < myArray1.length; i++) { document.write(myArray1[i] + "<BR />");} - Output: blue red purple lime yellow

  15. 2-Dimensions array example <SCRIPT LANGUAGE="JavaScript1.2"> <!-- a1 = new Array(2); for (var i=0; i<2; i++) { //creates a new Array in each Element of Array a1 a1[i] = new Array(5); for (var j=0; j<5; j++) { //assigns a value to each Element of the second dimension Array a1[i][j] = i + ", " +j; //displays the values for the first dimension Array of Arrays document.write(a1[i] + "&nbsp;&nbsp;&nbsp; First Dimension Array <BR>"); //displays the values for the second dimension Array Elements document.write(a1[i][j] + "&nbsp;&nbsp;&nbsp; Second Dimension Array Element <BR><BR>") } } --></SCRIPT>

  16. Arrays methods • concat() Combines two Arrays and returns a new Array that's "one level deep". • join() Takes all Elements of an Array and converts them into one String where each Element is separated by a comma or, optionally, your own separator. • pop() Removes and returns the last Element of an Array, changing its length. • push() Adds Element(s) to the end of an Array, returns the new length of the Array. • reverse() Reverses the physical order of the Elements in an Array. • shift() Extracts the first Element of an Array and returns that Element. • slice() Extracts a selectable portion of an Array and returns a new Array. • splice() Optionally adds, removes, or adds and removes Elements from an Array. • sort() Sorts the Elements of an Array lexicographically or by your Function. • toString() Returns a String that represents the calling Array Object or Element. • unshift() Adds one or more Elements before the first Element of an Array. It returns nothing.

  17. <HTML><HEAD> <SCRIPT LANGUAGE="JavaScript1.2"> <!-- a1 = new Array("blue", "red", "purple", "lime", "yellow"); a2 = ["green", "gray", "black", "white", "olive"]; //---Note that a2 is an Array created with literal notation. --> </SCRIPT> </HEAD> <BODY> <!-- ************************************************ --> <SCRIPT LANGUAGE="JavaScript"> <!-- var str = ""; str += '<P>Array a1 has these Elements: <B>' + a1 + '</B></P>'; str += 'Array a2 has these Elements: <B>' + a2 + '</B><BR>'; str += '<P>Array a1 concat a2: <B>' + a1.concat(a2) + '</B></P>';

  18. str += '<P>Array a1 with the Join Method: <B>' + a1.join(', ') + '</B></P>'; str += 'Array a2 with the Join Method: <B>' + a2.join(', ') + '</B><BR><BR>'; str += '<P>Array a1 Lexicographically Sorted is: <B>' + a1.sort() + '</B><BR>'; str += 'Array a1 Lex. Sorted and Joined is: <B>' + a1.join(', ') + '</B><BR><BR>'; str += 'Array a1 Sorted and Reversed is: <B>' + a1.reverse() + '</B><BR>'; str += 'Array a1 Sorted, Reversed and Joined is: <B>' + a1.join(', ') + '</B></P>'; str += 'Array a2 with the Push Method: <B>' + a2.push('cyan', 'maroon') + '</B><BR>'; str += 'Array a2 after the Push Method: <B>' + a2 + '</B><BR><BR>'; str += '<H3>-----Note that the Unshift Method '; str += 'returns the number of Elements in the Array</H3>'; str += 'Array a2 with the Unshift Method: <B>' + a2.unshift('navy',"violet") + '</B><BR>'; str += 'Array a2 after the Unshift Method: <B>' + a2 + '</B><BR><BR>'; str += 'Array a2 with the Pop Method: <B>' + a2.pop() + '</B><BR>'; str += 'Array a2 after the Pop Method: <B>' + a2 + '</B><BR><BR>'; str += 'Array a2 with the Shift Method: <B>' + a2.shift() + '</B><BR>'; str += 'Array a2 after the Shift Method: <B>' + a2 + '</B><BR><BR>';

  19. str += 'Array a2 with the Slice Method: <B>' + a2.slice(2,5) + '</B><BR>'; str += '<H3>-----Note that the Slice Method does not alter '; str += 'the Array but returns a new Array</H3>'; str += 'Array a2 after the Slice Method: <B>' + a2 + '</B><BR><BR>'; str += 'Array a2 with the Splice Method: <B>' + a2.splice(3,2, 'gold','darkblue') + '</B><BR>'; str += '<H3>-----Note that the colors gold and darkblue are '; str += 'added in place of black and white</H3>'; str += 'Array a2 after the Splice Method: <B>' + a2 + '</B><BR><BR>'; str += 'Array a2 with the Splice Method: <B>' + a2.splice(1,4) + '</B><BR>'; str += '<H3>-----Note that since no new colors are specified, '; str += 'Elements are simply removed</H3>'; str += 'Array a2 after the Splice Method: <B>' + a2 + '</B><BR><BR>'; str += 'using toString method for a2 <B>'+ a2.toString() +'</B>'; document.write(str); --> </SCRIPT> </BODY> </HTML>

  20. Random Number Generator Example • <html> • <body> • <script language="javascript"> • <!-- • no=Math.random()*10; //random() returns a random number between 0 and 1 • document.write(Math.round(no)); • --> • </script> • </body> • </html>

  21. Exercise: write a random number generator (between 0 and 100) scripts? Note: The Math object's properties and methods are described in www.w3schools.com

  22. Array Sort Function Assume we have an array named: a1 • To Sort Alphabetically in ascending order: a1.sort(); • To Sort Alphabetically in descending order: a1.sort(); a1.reverse(); • To sort numerically in ascending order: a1.sort( function(a,b) { return a-b; } ); • To sort numerically in descending order: a1.sort(function(a,b) { return b-a; } ); • To sort in random order: a1.sort( function() { return 0.5-Math.random(); } );

  23. Strings in JavaScript • Javascript treats strings as objects • to create a string you must use the keyword new • after a String object has been created then there is a plethora of methods that can be invoked from that object • var a = new String(“test”); • Var a=“test”;

  24. myString = new String("DreamPlay"); Equivalent to: • myString[0] = "D"; • myString[1] = "r"; • myString[2] = "e"; • myString[3] = "a"; • myString[4] = "m"; • myString[5] = "P"; • myString[6] = "l"; • myString[7] = "a"; • myString[8] = "y“;

  25. Some String properties and methods • length • concat() // s1.concat(s2) is equivalent to s1=s1+s2 • split(regexp or string) //Splits the source string into an array of strings (tokens) where its string argument specifies the delimiter

  26. The Split Method • <SCRIPT LANGUAGE="JavaScript1.2"> • var str = "The Characters 1 & 2 & E & 3"; • var splitArray=new Array(); • splitArray = str.split("&"); • document.write("<B>" + splitArray + "<\/B><P>"); • document.write(“the Length of the array is ” + splitArray.length + “<BR>”); • document.write(splitArray[0] + "<BR>"); • document.write(splitArray[1] + "<BR>"); • document.write(splitArray[2] + "<BR>"); • document.write(splitArray[3] + "<BR>"); • </SCRIPT>

  27. Slide Show Example <html> <script language="JavaScript"> <!-- var myPix = new Array("ball1.gif","ball2.gif","ball3.gif"); var thisPic = 0; function doPrevious() { if (document.images && thisPic > 0) { thisPic--; document.myPicture.src=myPix[thisPic]; } } function doNext() { if (document.images && thisPic < myPix.length) { thisPic++; document.myPicture.src=myPix[thisPic]; } } --> </script><body> <p align="center"> <img name="myPicture" src="ball1.gif" width="100" height="57"> <br><a href="javascript:doPrevious()">Previous</a><a href="javascript:doNext()">Next</a> </body></html>

  28. More examples <html> <body> <A HREF="mypage.html" onMouseOver="window.status='Hi there!'; return true;" onMouseOut="window.status=' '; return true;">Place your mouse here!</A> </body> </html>

  29. Example 2 <FORM><INPUT type=”button” value=”Go Back” name=”backbutton” onClick=”history.back()”> </FORM> In the same way, you can take a user forward instead of backward. Just change the code. Use onClick=”history.forward()”Now you can also take a user back or front not in a step of one, i.e. the last page, but you can take him 4 pages back or 5 pages forward directly. Use the following code for it. onClick=”history.go(-4)” This is used to tell the browser to take the user 4 pages back.onClick=”history.go(5)” This is used to tell the browser to take the user 5 pages front.

  30. Example 3 <FORM name="guideform"> <SELECT name="guidelinks" onChange="window.location=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value"> <OPTION SELECTED value="samepage.html”>--Choose--<OPTION value="page1.html">Page 1 <OPTION value="page2.html">My Cool Page </SELECT> </FORM>

  31. Other JavaScript Objects

  32. The Date-object • this object lets you work with time and date. • Example: displays the actual time. • var today= new Date() • This creates a new Date-object called today. If you do not specify a certain date and time when creating a new Date-object the actual date and time is used. This means after executing today= new Date() the new Date-object today represents the date and time of this specific moment.

  33. The Date-object offers some methods which can now be used with our object today. This is for example getHours(), setHours(), getMinutes(), setMinutes(), getMonth(), setMonth() • Please note that a Date-object does only represent a certain date and time. It is not like a clock which changes the time every second or millisecond automatically.

  34. In order to get another date and time we can use another constructor (this is the Date() method which is called through the new operator when constructing a new Date-object): • today= new Date(1997, 0, 1, 17, 35, 23) • This will create a Date-object which represents the first of january 1997 at 17:35 and 23 seconds. So you specify the date and time like this: • Date(year, month, day, hours, minutes, seconds)

  35. Example • <script language="JavaScript"> • <!-- • var now= new Date(); • document.write("Time: " + now.getHours() + ":" + now.getMinutes() + "<br>"); • document.write("Date: " + (now.getMonth() + 1) + "/" + now.getDate() + "/" + (now.getYear())); • --> • </script>

  36. Output Time: 17:53 Date: 12/19/2008

  37. Timer Functions TOid = setTimeout(statement,milisecond_to_wait); - will execute a statement once when the time has run out. INid = setInterval(statement,interval_in_miliseconds); - will execute the statement every interval miliseconds. Both can be cancelled as follows: clearTimeout(TOid); clearInterval(INid).

  38. Timer example <html> <body> <script language="JavaScript"> <!-- function timer() { setTimeout("i()", 3000); } function i(){ f.size=parseInt(f.size)+1; timer(); } --> </script> <form> <input type="button" value="Timer" onClick="timer()"> <font size="1" id="f">test</font> </form></body></html>

  39. Clock Example <html> <head> <script Language="JavaScript"> <!-- var timeStr, dateStr; function clock() { now= new Date(); // time hours= now.getHours(); minutes= now.getMinutes(); seconds= now.getSeconds(); timeStr= "" + hours; timeStr+= ((minutes < 10) ? ":0" : ":") + minutes; timeStr+= ((seconds < 10) ? ":0" : ":") + seconds; document.clock.time.value = timeStr; // date date= now.getDate(); month= now.getMonth()+1; year= now.getYear(); dateStr= "" + month; dateStr+= ((date < 10) ? "/0" : "/") + date;

  40. dateStr+= "/" + year; document.clock.date.value = dateStr; Timer= setTimeout("clock()",1000); } // --> </script> </head> <body onLoad="clock()"> <form name="clock"> Time: <input type="text" name="time" size="8" value=""><br> Date: <input type="text" name="date" size="8" value=""> </form> </body> </html>

  41. Cookies • A cookie is a way to store and retrieve a small piece of persistent data across multiple browser sessions from the client-side of the connection. Persistent data means that the data is available after the user disconnects from the WWW for reuse in the next session, or multiple sessions, if they are prior to the expiration date of the cookie. • When they were first introduced, Cookies were typically used to store the user's name and password for sites that require them, as a courtesy to the user so that the information doesn't have to be resubmitted every time the user logs on to a site. There are lots of other uses that authors have created for them, such as storing user Preferences for text size and color, etc. At a site that is transacting commerce, they could be used to store the items that the user has chosen to purchase like the shopping cart metaphor you've probably seen.

  42. Cookie Syntax • document.cookie = "cookieName=cookieValue [; EXPIRES=GMTDateString] [; PATH=pathName] [; DOMAIN=domainName] [; SECURE]"

  43. Parameters Defined: • cookieName=cookieValue You assign a name for the Cookie with the cookieName parameter and a value for the Cookie with the cookieValue parameter. They can be any sequence of characters except a semicolon, comma, or any white space. • PATH=pathName An optional parameter that specifies the path name. • DOMAIN=domainName An optional parameter that specifies the domain name. • SECURE An optional parameter that if included specifies that the Cookie will only be sent over a secure server.

  44. Continued • EXPIRES=GMTDateString Sets an expiration time and date for the Cookie. This is an optional parameter and if it's omitted, then the Cookie expires at the end of the current session. The format of the String that is specified for the GMTDateString Value is: Weekday, DD-Mon-YY HH:MM:SS GMT where: • Weekday The day of the week like Monday. • DD A two-integer representation of the day of the month like 05 or 22. • Mon A three-letter abbreviation for the name of the month. • YY A two-integer representation for the last two numerals of the year like 99. • HH The hours in military time from 0 to 23. • MM The minutes like 04 or 33 where the zero is required for less than 10. • SS The seconds where the zero is required for less than 10. Note that the comma, dashes, colons, and spaces are necessary parts of the syntax.

  45. Creating a Cookie is very simple. Using and manipulating Cookie data is royally difficult. Here is a simple example of creating a Cookie: document.cookie="myCookie1=Eat_A_Cookie”; • If you were to write the cookie to screen like this: document.write(document.cookie); • It would produce the following output in the browser: myCookie1=Eat_A_Cookie

  46. Using Cookies in your Scripts requires some creative manipulation of the text contained in the Cookie String. For instance, if you assign more than one Value to document.cookie, then it will contain a single String that contains each of those Values so that each one is separated by a semicolon. One way to access one of those Cookie Values later on is to use the split(";") Method of the String Object, and use the semicolon Character as the separator Argument, which will return an Array of Strings. Then, access individual Array Elements as needed, which is demonstrated in the following example.

  47. <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript1.2"><!-- document.cookie="myCookie1=Eat_A_Cookie"; document.cookie="myCookie2=Eat_Another_Cookie"; document.cookie="myCookie3=Throw_A_Cookie"; cookieString = document.cookie; cookieArray = cookieString.split(";"); document.write(document.cookie + "<P>"); document.write(cookieArray[0] + "<BR>"); document.write(cookieArray[1] + "<BR>"); document.write(cookieArray[2] + "<BR>"); --> </SCRIPT> </HEAD> <BODY> Make sure that your browser can accept Cookies or this won't work. </BODY> </HTML>

More Related