310 likes | 331 Views
JavaScript Global Functions and Objects I. Introduction to JavaScript Objects and HTML Element Objects Global Functions: isFinite, isNaN, escape/unescape, eval Creation of Objects: the new operator and constructor functions Commonly used objects: Window: Math and Random Number Generation
E N D
JavaScript Global Functions and ObjectsI • Introduction to JavaScript Objects and HTML Element Objects • Global Functions: isFinite, isNaN, escape/unescape, eval • Creation of Objects: the new operator and constructor functions • Commonly used objects: • Window: • Math and Random Number Generation • Date • ------------------------------------------------------------------------------ • In next powerpoint, we will have: • Array • String • Document and Adding Cookies • Forms: • Style, Cascading Style Sheets (CSS) and Dynamic HTML (DHTML)
What are Objects • Objects: • An object is a collection of named values called properties. • Each property may contain any type of data, functions, and even other objects. • Example: The document object may contain a form object named F1: document.F1 • The form may contain 2 input box objects with names equal to n1 and n2: • document.F1.n1anddocument.F1.n2 • The input boxes may contain several properties like: value, size, readOnly: • document.F1.n1.value • The properties can be examined as follows: [Refer to Lec03_Slide12_V4_MarksToGrade.htm]
What are Objects Exercise: [Refer to Lec02_Slide13_V4_MarksToGrade.htm] What will be shown by running the statements below? javascript:alert(document.F1.CGrade.readOnly) javascript:alert(document.F1.CGrade) javascript:alert(document.F1) javascript:alert(document) javascript:alert(document.write) javascript:alert(convertAll)
HTML Elements as JavaScript Objects • Handling HTML Elements as JavaScript Objects • Contents in a webpage are automatically represented as • "objects contained in the document object" (ie. a property of the document object). • 2 simple methods to refer to these contents: • (1) Each element object in the webpage body, that contains an ID, can be referred using • document.getElementById(id). • If it contains a pair of starting and ending tags, the HTML text in-between the tags can be referred as the innerHTML property: • document.getElementById(id).innerHTML • (2) For forms and form elements, there is one more method to refer to them. • Any form object is an individual property of the document, can be referred by its name. • document.formname • Each element in the form is an individual property of the form, can be referred by its name. • document.formname.elementname • The set of properties defined for one kind of object is usually different from others. • For example, an input box contains the value property but an image does not. • The list of properties for each kind of object can be found in the appendix of many JavaScript books or on-line resources. However, practically we use only a few of them.
What are Objects • A function stored as an object property is often called a method. eg. document.write( ); • In the above, write() is "a method" of document objects. • All JavaScript code loaded in a browser window is contained in a global object: window • The window object contains • - all global functions (functions that not really specific to the "window"): eg. parseInt( ) • - many useful window methods, eg. window.setInterval( ), window.alert() .. • - the document object • - other useful window properties, eg. window.status (the text shown in the status bar) • To access window properties, like window.document and window.setInterval( ), we may omit the window. part, ie. simply document, setInterval(..) • Some people prefer to keep the window. part : easier to understand the code (to know that 'the property belongs to the window object'). • The Global functions do not relate much to the browser window, we prefer to type their names directly like parseInt, instead of window.parseInt. • Some common Global functions: parseFloat, parseInt isFinite, isNaN, escape and unescape, eval
Global Functions – isFinite(), isNaN() /* check a mark and return the grade*/ function convertToGrade(mark) { var x=parseInt(mark); if (isNaN(x)) return 'Wrong'; if (mark>80) return 'A'; else if (mark>65) return 'B'; else if (mark>45) return 'C'; else return 'F'; } • isFinite() • Test whether a value is a finite number (opposite cases: NaN or infinity) • Example: isFinite(8%0) and isFinite(9/0)false • If the computation result is NaN or infinity, then false is returned, otherwise true is returned. • isNaN() • Test whether a value is not-a-number. • Example: isNaN(parseInt(document.F1.t1.value)) • Application: • Check whether a value is a valid number before processing it: Note: To check whether a string value x is empty, simply type if (x=="")
alert ( escape("McDonald's") ) alert ( unescape("McDonald%27s") ) Escape()/unescape() will not appear in test/exam Global Functions – escape(), unescape() • escape() • encode a string by replacing special characters with hexadecimal values like %xx. • These are not changed: 0-9, a-z, A-Z, @, *, _, +, -, ., / • unescape() • decode a string that is encoded with escape(). Application: Encoding/decoding processes are needed if we don't want to send special characters across web applications directly [ or not permitted to do so ].
eval() will not appear in test/exam Global Functions – eval() • eval() - Evaluate and execute the code in a string. • Eg. eval("3+4"), eval("alert('hello')") : The parameter is the string of code to be executed. • Interesting : to allow somebody to type some code. But not used frequently in real-world programs. • Example: Suppose there is a text box object: document.F1.t1 (1) If it contains: then alert(document.F1.t1.value) shows 3+4. alert(eval(document.F1.t1.value)) shows 7. To store the result in a variable x: x=eval(document.F1.t1.value) 3+4 (2) If it contains: setInterval('alert(Math.random())',1000) <BODY > <form name="F1"> <input type="text" size=40 name="t1" /> <input type="button" onclick="eval(document.F1.t1.value)" value="do it"/> </form> </BODY> then eval(document.F1.t1.value) pops up random numbers every second.
Creation of Objects • Objects created with the new operator • During object creation, a special constructor function is invoked for initialization of the object. • The new operator creates a new object and invokes a constructor function to initialize it. • new constructor(arguments) • Example 1: var now = new Date(); //Current date and time • Example 2: var new_years_eve = new Date(2000, 11, 31); // Dec 31, 2000 • In the above, Date() is a constructor function that creates a Date object • (The Date objects will be covered very soon in this topic. ) • As a special case (for the new operator only), omitting the parentheses is allowed: • Example 3: var now = new Date; //Current date and time
Creation of Objects • Even without using the new operator directly, objects can be created as a result of some operations. • For example: <html> <head> <title>CS1301</title> <script type="text/javascript"> /*show a new window with 10 lines of text*/ function createNewWindow() { var myWindow = window.open(); var i=0; while (i<10) { myWindow.document.write( "This is a new window<br/>"); i++; } } </script> </head> <body> <a href="javascript: createNewWindow(); "> Create New Window </a> </body> </html> Use the open method to create a new window object. The myWindow variable is defined to receive the new window object. The new window object is referred as myWindow afterwards.
The window Object • window object - Every web browser window is represented by a window object. • Commonly used window methods: • alert(), confirm(), prompt() - Simple dialogs • resizeTo(), resizeBy() - Change the window size • moveTo(), moveBy() - Change the window location • open() - Create a blank window or a new window with a specified URL • print() - Print the window or frame • (same as the File/Print command of the window.) • setInterval(), clearInterval() - Schedule or cancel a function to be invoked • Commonly used window properties: • status - The text that appears in the status bar • document - The document object • location - The URL of the current document • Can be set to load a new document Also provides reload method • history - Provides history.back() and history.forward() for traversals • Also contains global functions (functions that not really specific to the "window"): eg. parseInt( )
The window Object The example below shows the uses of resizeTo(newWidth, newHeight) - Set the window size (in pixels) resizeBy(changeWidth, changeHeight) - Increase or decrease width and height moveTo(newX, newY) - Set the window location (upper left, in pixels) moveBy(changeX, changeY) - Move the window by offset print() - Print the window or frame (same as the File/Print command of the window.) status - The text that appears in the status bar history - history.back() and history.forward() for traversals <a href="javascript: window.status='Welcome';void(0);">set status bar</a><br/> <a href="javascript: window.print();">print</a><br/> <a href="javascript: window.resizeTo(300,300);">set window size to 300x300</a><br/> <a href="javascript: window.resizeBy(-30,80);">decrease width by 30, increase height by 80</a><br/> <a href="javascript: window.moveTo(300,300);">Move window to (300,300)</a><br/> <a href="javascript: window.moveBy(-30,100);">Move window by (-30,100)</a><br/> <a href="javascript: window.history.back();">back</a><br/> <a href="javascript: window.history.forward();">forward</a><br/>
The window Object • window.location • The location object represents the URL of the document currently being displayed. • Can be set to load a new document, eg. var interest; .. if (interest=='Programming') window.location='http://www.cs.cityu.edu.hk'; else window.location='http://www.cityu.edu.hk'; .. • Also provides reload method to refresh the page: <a href="javascript: window.location.reload();">Reload the page</a>
The window Object • window.setInterval(code, milliseconds) • Schedules a piece of code to run repeatedly. • Returns an idthat can be passed to window.clearInterval to stop the schedule. • window.clearInterval(id) • Stops the repeated execution of the code that was started by window.setInterval • The following example schedules the status bar clock to be updated every second. function showStatusBarClock() { var now=new Date; window.status=now.toString(); } <a href="javascript: var interval_id=window.setInterval('showStatusBarClock()',1000);void(0)"> Update status bar clock every second </a> <br/> <a href="javascript: window.clearInterval(interval_id);">Stop the status bar clock</a>
The window Object • window.open() • Create a blank window or a new window with a specified URL. • (see a previous slide on Creation of Objects) • Examples: • //Open a new window to show CS department homepage. • window.open("http://www.cs.cityu.edu.hk"); • //Open a blank window and then write contents to the document • var myWindow = window.open(); • myWindow.document.write("This is a new window<br/>"); • //Open a simple blank window with a given size (in pixels): • var myWindow = window.open("","","width=200,height=200"); • //Open a simple blank window with a given size and additional features: • var myWindow = window.open("","","width=200,height=200,status=yes,resizable=yes");
The window Object • Arguments of window.open() : window.open(url, name, features) • Example. var myWindow = window.open("","","width=200,height=200,status=yes,resizable=yes"); • url: Specifies the URL to be displayed. Can be blank for empty document. • name: The window name. • Can be blank (new window is created). • Otherwise if a window with the same name already exists, the open method just returns this existing window. • If you need to erase the contents in the window document first, use the open method of the window's document before writing, eg. myWindow.document.open() • features: Specifies the size, and window features. • size and position: height, width, left, top (in pixels) • features: • location - address box • resizable - can be resized by dragging border • scrollbars - display the scrollbars if the size of content exceeds window size • status - status bar • toolbar • menubar
The Math Object • The Math Object -Can be used for many common mathematical calculations. • Provides predefined values like: Constant Description Value Math.E Base of a natural logarithm (e). Approximately 2.718 Math.LN2 Natural logarithm of 2. Approximately 0.693 Math.LN10 Natural logarithm of 10. Approximately 2.302 Math.LOG2E Base 2 logarithm of e. Approximately 1.442 Math.LOG10E Base 10 logarithm of e. Approximately 0.434 Math.PI p Approximately 3.142 Math.SQRT1_2 Square root of 0.5. Approximately 0.707 Math.SQRT2 Square root of 2.0. Approximately 1.414 Example: to compute the circumstances of a circle with radius 10: var area=Math.PI*10*10;
The Math Object The Math Object also provides a lot of calculation methods: Method Description Example Math.abs( x ) absolute value of x Math.abs( 7.2 ) is 7.2 Math.abs( 0 ) is 0 Math.abs( -5.6 ) is 5.6 Math.round( x ) rounds x to the closest integer Math.round( 9.75 ) is 10 Math.round( 9.25 ) is 9 Math.ceil( x ) rounds x to the smallest integer not less than x Math.ceil( 9.2 ) is 10 Math.ceil( -9.8 ) is -9 Math.floor( x ) rounds x to the largest integer not greater than x Math.floor( 9.2 ) is 9 Math.floor( -9.8 ) is -10 Math.max(x,y,..) largest value in the list Math.max( 0.1, 2.3, 12.7 ) is 12.7 Math.max( -2.3, -12.7 ) is -2.3 Math.min(x,y,..) smallest value in the list Math.min( 2.3, 12.7 ) is 2.3 Math.min( -2.3, -12.7 ) is -12.7 Question: What are the values returned by: Math.floor(0) Math.floor(9.9999999)
The Math Object MethodDescription Example Math.exp( x ) exponential method ex Math.exp( 1.0 ) is 2.71828 Math.exp( 2.0 ) is 7.38906 Math.log( x ) natural logarithm of x (base e) Math.log( 2.718282 ) is 1.0 Math.log( 7.389056 ) is 2.0 Math.pow( x, y ) x raised to power y (xy) Math.pow( 2, 7 ) is 128 Math.pow( 9, 0.5 ) is 3 Math.sqrt( x ) square root of x Math.sqrt( 900 ) is 30 Math.sqrt( 9 ) is 3 Math.cos( x ) trigonometric cosine of x (x in radians) Math.cos( 0 ) is 1 Math.cos(Math.PI/3) is 0.5 Math.sin( x ) trigonometric sine of x (x in radians) Math.sin( 0 ) is 0 Math.tan( x ) trigonometric tangent of x (x in radians) Math.tan( 0 ) is 0
The Math Object • Generate Random Numbers • The Math.random() method returns a random value between 0 and 0.99999…(less than 1.0). • Example: var randomValue = Math.random(); • To adjust the range, eg. between 0 and 99.999.., scaling is needed: • var randomValue = Math.random()*100; • To obtain whole integers, eg. among 0,1,2,99, Math.floor() can be used to cut off the digits after the decimal point: • var randomValue = Math.floor(Math.random()*100); • Explanation: 0 is obtained if Math.random() gives 0.0000, 0.0001,0.0002,...0.0099 • 1 is obtained if Math.random() gives 0.0100, 0.0101,0.0102,...0.0199 • … • 99 is obtained if Math.random() gives 0.9900,0.9901,0.9902,…0.9999 • The smallest possible value is : 0 • The largest possible value is : 99 • 0,1,2,..99 are obtained with equal chances (randomness)
The Math Object “I want to pick a random number among 40, 41, .. 59” x y • Generate Random Numbers (Continue) • If the range is arbitrary: x, x+1, x+2, ..y (totally y-x+1 numbers), Shifting is needed: • var randomValue = x + Math.floor(Math.random()*(y-x+1)); • For example, if the range is: 40,41,42,..59 • (ie. 40,40+1,40+2,..40+19, totally 20 numbers) • var randomValue = 40 + Math.floor(Math.random()*20); • x y-x+1 • Explanation: The smallest possible value is : 40 • The largest possible value is : 59 (just less than 40+20) • 40,41,42,..59 are obtained with equal chances (randomness) • Think about it: • How to obtain a random number among 41,42,..60? • How to obtain the random Die Roller numbers (1,2,3,4,5,6)? • How to obtain a random number among 72,73,..88? • How to obtain a random student ID among 50000000 to 50999999?
The Date Object (Handle date and time) • The Date Object - Provides methods for date and time manipulations. • Date and time processing can be based on the computer's • (1) local time zone • - eg. Our lecture started at 10:30:00 UTC+0800 • or (2) World Time Standard's Coordinated Universal Time (UTC) • - formerly called Greenwich Mean Time (GMT) • - eg. Our lecture started at 02:30:00 UTC • Most methods of the Date object have 2 versions for the above. • Examples: toString() and toUTCString()
The Date Object (Handle date and time) • Creation of Date Objects • To handle date and time, we need to create a Date object • like: var d=new Date(..); • new Date() • current date and time • new Date(milliseconds) • milliseconds is number of milliseconds since midnight (UTC) on 1/1/1970. • new Date(year, month, day, hours, minutes, seconds, ms) • day, hours, minutes, seconds, ms are optional • [Note that month values are 0 to 11, meaning Jan to Dec] var d1 = new Date(); var d2 = new Date(1000); var d3 = new Date(2007,2,15,10,30,40); alert( d1.toString()+"\n"+ d2.toString()+"\n"+ d3.toString()+"\n");
The Date Object Methods (B) Conversion of Date object to a date/time String (1) Obtain DATE and TIME String • toString() : use the local time zone. • toLocaleString() : use the local time zone and the local date formatting conventions. • toUTCString() : use universal time. Example: Given var x=new Date(2006,2,10,15,30); alert(x.toString()) or alert(x) //automatically converted to string alert(x.toLocaleString()) alert(x.toUTCString())
The Date Object Methods (2) Obtain DATE String Only • toDateString() alert(x.toDateString()) • toLocaleDateString() alert(x.toLocaleDateString()) (3) Obtain TIME String Only • toTimeString() alert(x.toTimeString()) • toLocaleTimeString() alert(x.toLocaleTimeString())
(C) Conversion of Date/Time data to numbers Date Methods Description getFullYear(), getUTCFullYear()Returns the year as a four-digit number in local time or UTC. getMonth(), getUTCMonth() Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC. getDate(), getUTCDate() Returns a number from 1 to 31 representing the day of the month in local time or UTC. getDay(), getUTCDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC. getHours(), getUTCHours()Returns a number from 0 to 23 representing hours since midnight in local time or UTC. getMinutes(), getUTCMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time or UTC. getSeconds(), getUTCSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time or UTC. getMilliseconds(), getUTCMilliSeconds() Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC. getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object. getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC.
(D) Override Date/Time data with numbers Date Methods Description setFullYear(y,m,d), setUTCFullYear(y,m,d) Sets the year in local time or UTC. m and d are optional. setMonth(m,d), setUTCMonth(m,d) Sets the month in local time or UTC. d is optional. setDate(d), setUTCDate(d) Sets the day of the month (1 to 31) in local time or UTC. setHours(h,m,s,ms), setUTCHours(h,m,s,ms) Sets the hour in local time or UTC. m, s, and ms are optional. setMinutes(m,s,ms), setUTCMinutes(m,s,ms) Sets the minute in local time or UTC. s and ms are optional. setSeconds(s,ms), setUTCSeconds(s,ms) Sets the second in local time or UTC. ms is optional. setMilliSeconds(ms), setUTCMilliseconds(ms) Sets the number of milliseconds in local time or UTC. setTime(ms) Sets the time based on its argument—the number of elapsed milliseconds since January 1, 1970. * Meaning of arguments listed above: y: year, m: month or minute, d: date, h: hour, s: second, ms: millisecond. * For each optional argument: if not specified, the current value in the Date object is used.
The Date Object : Application • Application: The Date Navigator • The page contains dd, mm, yyyy fields for a date. Users can type in these fields. • Two buttons are available for moving the date forward and backward by one day. • On loading, the date fields are initialized to the current date. <body onload="setup()"> <h2>Date Navigator</h2> <form name="F1"> <input type="text" name="d" size="2"/> / <input type="text" name="m" size="2"/> / <input type="text" name="y" size="2"/> (dd/mm/yyyy)<br/> <input type="button" value="next day" onclick="showNextDay()"/> <input type="button" value="previous day" onclick="showPrevDay()"/> </form> </body>
Demonstration of : • 3 kinds of Date constructors, • getDate(), getMonth(), getYear() • getTime() • The setup() and showNextDay() functions //Initialize the date fields to current day. functionsetup() { var today=new Date; //current date and time document.F1.d.value=today.getDate(); document.F1.m.value=today.getMonth()+1; document.F1.y.value=today.getYear(); } //Advance the shown date to the next day. functionshowNextDay() { var shownDate, newDate, nMilliSeconds; //1. Create a date object for the form data ==> shownDate shownDate=new Date(document.F1.y.value,document.F1.m.value-1,document.F1.d.value); //2. Create a date object for the new date ==> newDate nMilliSeconds=shownDate.getTime(); //elapsed milliseconds since January 1, 1970. newDate=new Date(nMilliSeconds+1000*60*60*24); //add milliseconds of 24 hours. //3. Update the form with newDate document.F1.d.value=newDate.getDate(); document.F1.m.value=newDate.getMonth()+1; document.F1.y.value=newDate.getYear(); } //Initialize the date fields to current day. functionsetup() { var today=new Date; //current date and time document.F1.d.value=today.getDate(); document.F1.m.value=today.getMonth()+1; document.F1.y.value=today.getFullYear(); } //Advance the shown date to the next day. functionshowNextDay() { var shownDate, newDate, nMilliSeconds; //1. Create a date object for the form data ==> shownDate shownDate=new Date(document.F1.y.value,document.F1.m.value-1,document.F1.d.value); //2. Create a date object for the new date ==> newDate nMilliSeconds=shownDate.getTime();//elapsed milliseconds since 1/1/1970. newDate=new Date(nMilliSeconds+1000*60*60*24); //add ms of 24 hours. //3. Update the form with newDate document.F1.d.value=newDate.getDate(); document.F1.m.value=newDate.getMonth()+1; document.F1.y.value=newDate.getFullYear(); }
Demonstration of : • setFullYear () - instead of using the Date(yyyy,mm,dd..) constructor • setTime() - instead of using the Date(milliseconds) constructor Another version of showNextDay() //Advance the shown date to the next day. functionshowNextDay() { var nMilliSeconds; var x=new Date; x.setFullYear( document.F1.y.value, document.F1.m.value-1, document.F1.d.value); nMilliSeconds=x.getTime(); //elapsed milliseconds since 1/1/1970. x.setTime(nMilliSeconds+1000*60*60*24); //add ms of 24 hours. document.F1.y.value=x.getFullYear(); document.F1.m.value=x.getMonth()+1; document.F1.d.value=x.getDate(); } • Create a date object x (current date and time). • Update day, month, year of x based on the form data. • Find new value for x. • Display x in the form. • Your exercises: • Finish the showPrevDay function. • Add two buttons for moving 10 days backward and forward.
Summary • Introduction to JavaScript Objects and HTML Element Objects • Global Functions: isFinite, isNaN, escape/unescape, eval • Creation of Objects: the new operator and constructor functions • Commonly used objects: • Window: status, location, resizeTo, …, setInterval, clearInterval, open (new window) • Math: constants (E, LN2, PI, ...) and methods(floor, max, sqrt ...) • Random Number Generation • Date: Constructors, conversion to string, getXX and setXXX methods • Application: Date Navigator