C ITS 1231 Web Tec hnolog ies JavaScript: Document, Event, Date objects
D oc um ent O bjec t JavaScript can interact with HTML page elements via the Document Object. The Document Object is accessed via the keyword document. Recall from previous lectures: document.writeln() to print out to page. Document Object has: Collections Properties Methods 2
D oc um ent M ethods w rite() Writes HTML or JavaScript to a document w riteln() Same as write(), but adds a newline character Note that newline characters are normally ignored by browser. You can use the <pre> tag to preserve line breaks. Example: <pre> document.writeln( Hello ); document.writeln( World ); document.write( Hello ); document.write( World ); </pre> 3
D oc um ent M ethods g ete lem entb yid() Accesses the first element with the specified id One can then access the various properties of this element innerhtml property refers to the text between the element s opening and closing tags 4 <head> <script type="text/javascript"> function getvalue() { var x=document.getelementbyid("myheader"); alert(x.innerhtml); } </script> </head> <body> <h1 id="myheader" onclick="getvalue()">click <em>me!</em></h1> </body> </html>
D oc um ent M ethods g ete lem ents B yn a m e() Accesses all elements with a specified name <head> <script type="text/javascript"> function calc() { var x=document.getelementsbyname("para"); alert("there are "+x.length+" paragraphs. First one says:"+x[0].innerhtml); } 5
D oc um ent M ethods g ete lem ents B yta g N a m e() Accesses all elements with a specified tagname <head> <script type="text/javascript"> function gettags() { var x=document.getelementsbytagname("input"); alert("there are "+x.length+" inputs. First second has value: "+x[1].value); } </script> </head> <body> <input type="text"/><br /> <input type="text"/><br /> <input type="text"/><br /> <input type="button" onclick="gettags()" value="how many input elements?" /> </body> </html> 6
U nders ta nding E vent H a ndlers Event Action that occurs within a Web browser Event handler Statement that tells browsers what code to run in response to specified event Syntax to insert event handler as an attribute <element onevent="script"...>... 7
Java S c ript E vent H a ndlers 8 Many more. See text or http://www.w3schools.com/jsref/dom_obj_event.asp
E vent: onkeydow n The user has pressed a key. Example: 9 <head> <script type="text/javascript"> function update(id) { var txt=document.getelementbyid(id).value; document.getelementbyid(id).value=txt.touppercase(); } </script> </head> <body> Type something: <input type="text" id="fname" onkeydown="update(this.id)" /> </body> </html> Why is the last character not uppercase? Character is not added to input text until key goes up. When key down, function is called to convert input text to upper case. Only when function returns and key is released, the last character is appended to input text (still lower case!).
E vent: onkeyup The user pressed a key and released it. Example: <head> <script type="text/javascript"> function update(id) { var txt=document.getelementbyid(id).value; document.getelementbyid(id).value=txt.touppercase(); } </script> </head> <body> Type something: <input type="text" id="fname" onkeyup="update(this.id)" /> </body> </html> Each character is made upper case on key going up. 10
E vent: onc ha ng e The content of the input field has changed. Example: <head> <script type="text/javascript"> function update(id) { var txt=document.getelementbyid(id).value; document.getelementbyid(id).value=txt.touppercase(); } </script> </head> <body> Type something: <input type="text" id="fname" onchange="update(this.id)" /> </body> </html> No change to characters as you type. Event onchange is triggered only when you hit Enter key. 11
E vent: onc lic k User has clicked mouse button. Example: <head> <script type="text/javascript"> function calc() { var num1 = parseint(document.getelementbyid('num1').value); document.getelementbyid('num2').value = num1*num1; } </script> </head> <body> Enter a number: <input type="text" id="num1" /> <button onclick="calc()">click to square it</button> <input type="text" id="num2" readonly="true" /> </body> </html> 12
D ate O bjec t Allows your JavaScript to work with dates and times. There are 4 ways to create a Date object: Date Object with current date and time: <body> <script type="text/javascript"> var dt=new Date(); document.write(dt); 13 </script>
D ate Initia lis e U s ing S tring variable = new Date("month day, year hours:minutes:seconds"); 14 <body> <script type="text/javascript"> var dt=new Date("June 1, 1977 10:11:00"); document.write(dt); </script> </body> </html>
D ate Initia lis ed U s ing N um ber var dt = new Date(num) num is number of ms past 01 Jan 01, 1970 00:00:00 UTC Perth is UTC+08:00:00 There are 86,400,000 ms in one day <body> <script type="text/javascript"> var dt=new Date(86400000); document.write(dt); </script> </body> </html> 15
D ate Initia lis ed U s ing S evera l Pa ra m eters new Date(yr, mth, day, hrs, mins, secs, ms) Parameters are numbers and optional. If you leave out a parameter, zero will be assumed and all subsequent parameters must be left out also. new Date(2010) is valid. new Date(2010,, 1) is invalid. <body> <script type="text/javascript"> var dt=new Date(2010,0,1,2); document.write(dt); </script> </body> </html> 16
E xtra c ting D ate a nd Tim e Va lues 17
S etting D ate a nd Tim e Va lues 18
C reating a C us tom D ate Func tion showd ate() function returns dd/mm/yyyy formatted date. <head> <script type="text/javascript"> function showd ate(dateobj) { var thisdate = dateobj.getdate(); //get day var this Month = dateobj.getmonth()+1; //get month (jan=0 s o add 1) var this Year = dateo bj.getfullyear(); return thismonth + "/" + thisdate + "/" + thisyear; //get year //format as dd/mm/yyyy } </script> 19 </head>
C reating a C us tom Tim e Func tion showtime() function returns hh:mm:ss formated time. <head> <script type="text/javascript"> function showtime(dateo bj) { thiss econd=dateo bj.gets econds(); var this Minute=dateO bj.getminutes(); var this Hour=dateO bj.gethours(); return thishour + ":" + thisminute + ":" + thiss econd; //get seconds //get minutes //get hours //format as hh:mm:ss } </script> 20 </head>
C a lc ulate D a ys to N ew Yea r calcd ays() function returns number days to new year. <head> <script type="text/javascript"> function calcd ays(dateo bj) { var nextyear=dateobj.getfullyear()+1; var newyear=new D ate(nextyear,0,1); var ms = newyear-dateobj; var days = ms /(1000*60*60*24); //get next year //create date of next new year //calc ms from now to new year //convert ms to days return days; } 21 </script> We want integer whole days. How to rid of decimals?
C a lc ulate D a ys to N ew Yea r C ont calcd ays() function returns number days to new year. <head> <script type="text/javascript"> function calcd ays(dateo bj) { var nextyear=dateobj.getfullyear()+1; var newyear=new D ate(nextyear,0,1); var ms = newyear-dateobj; var days = ms /(1000*60*60*24); //get next year //create date of next new year //calc ms from now to new year //convert ms to days return days; } 22 </script>
Tim e to N ew Yea r Time to New Year can be expressed in number of days, hours, minutes and seconds. calcdays() returns a number. Integer portion is number whole days to new year. Decimal portion can be converted to remainder hours, mins and secs. calchours() returns remainder hours calcmins() returns remainder minutes calcsecs() returns remainder seconds 23
c a lc H ours () rem a inder hours to N ew Yea r <head> <s cript type="text/javascript"> function calchours(days) { var fracd ay = days - Math.floor(days); var hours = fracday*24; // get fractional day // convert to hours return hours; 24 } </s cript> </head> <body> <pre>
c a lc M ins () rem a inder m inutes to N ew Yea r <head> <s cript type="text/javascript"> function calcmins(hours) { var frachours = hours - Math.floor(hours); var minutes = frachours*60; // get fractional hours // convert to minutes return minutes; 25 } </s cript> </head> <body> <pre>
c a lc S ec s () rem a inder s ec onds to N ew Yea r <head> <s cript type="text/javascript"> function calcs ecs(minutes) { var fracmins = minutes - Math.floor(minutes); var seconds = fracmins*60; // get fractional minutes // convert to seconds return s econds; 26 } </s cript> </head> <body> <pre>
A utom atic a lly U pdating C ountdow n Use JavaScript timing events id = settimeout("command", delay) execute code sometime in future cleartimeout(id) cancels settimeout() 27
s ettim eout E xa m ple <head> <script type="text/javascript"> var c=1000; function start() { document.getelementbyid('num').value=c; c--; settimeout("start()",1000); } </script> 28 </head>
C reating the monthname A rra y 29
C reating the writedaynames() Func tion 30
T he C om plete daysinmonth() Func tion 31
R unning Java S c ript C om m a nds a s Links Syntax <a href="javascript:script">content</a> The following code runs the calctotal() function <a href="javascript:calctotal()"> </a> C alculate total cost 32