490 likes | 787 Views
JavaScript. A World Wind Tour of JavaScript. Objectives. Introduction to JavaScript JavaScript: Its Beginnings Advantages and disadvantages How differs from html and server side programs Working with JS and HTML tags. Running onload, when done, on an event Using JS objects
E N D
JavaScript A World Wind Tour of JavaScript
Objectives • Introduction to JavaScript • JavaScript: Its Beginnings • Advantages and disadvantages • How differs from html and server side programs • Working with JS and HTML tags. • Running onload, when done, on an event • Using JS objects • Objects with properties and methods • Using conditional tests
Competencies • At end of unit be able to • Describe 3 times when javascript runs • Describe some of the capabilities of JavaScript • Write a JavaScript with conditional expression • Use a JavaScript program with variables and calculations Competency Alert: You need to know this! Common Problem Area! People seem to forget this
JavaScript: Its Beginnings • JavaScript developed by Netscape & initially called livescript. • After Java came out, Netscape cut a deal with Sun to rename it to JavaScript (12/95). • They are separate, distinct languages. (Though JavaScript is simpler). • Microsoft … • Came out with their own flavor of JavaScript called “Jscript”. • They also added support for VBScript in IE. Differences are minor. • Eventually standardized … • JavaScript has been turned over to the European Computer Manufactures Association, and is now officially called ECMAScript • Both Netscape & IE4.0 and Netscape implement ECMAScript standard.
The “goods” on JavaScript • JavaScript can be used to: 1. perform simple client-side computations • For example, add up total costs of shopping cart before it is submitted. 2. facilitate dynamic and interactive Web page creation • For example, do image roll overs, pop up windows on click, expand a menu. 3. Verify HTML forms enhance HTML forms with data collections and form validation 4. manipulate user cookies -
The “not so goods” on JavaScript • JavaScript runs completely on Client machine • It does NOT have: 1. Any graphic capabilities • E.g., cannot show a graph of survey results. 2. Access to client (you PC) resources • Cannot print, modifying PC files, or launching client applications. 3. Access to any Web server resources • E.g., cannot send email, write to file, write to database.
PHP/JavaScript Similarities and Differences • What they have in common. Both languages can: • Be embedded in HTML documents • Cause dynamic content to be displayed (e.g., the current date) • Can be placed in external files and “included” into html files • Look more like a programming language than HTML • What they DON’T have in common: • The big difference … JavaScript runs 100% on client (i.e., PC). This means: • JavaScript stuff runs noticeably faster (not dependent on Internet and Web Server) • PHP has access to Web Server resources (mail, databases, files) • Using differences • Writing JavaScript does NOT require a Web Server (but more concern about browser implementation differences). • PHP’s syntax is easier to write and understand for beginners.
How JavaScript Pages are Run JavaScript does not run here JavaScript is run here by the browser but just before HTML
Objectives • Introduction to JavaScript • JavaScript: Its Beginnings • Advantages and disadvantages • How differs from html and server side programs • Working with JS and HTML tags. • Running onload, when done, on an event • Using JS objects • Objects with properties and methods • Using conditional tests
Adding JavaScript to HTML pages • JavaScript is added to HTML pages using the <script> tag. • usually placed in the HEAD or BODY of the document • <script src=URLlanguage=“JavaScript”></script> • <script language=“JavaScript”> • <!-- • Javascript code • //--> • </script> If link to an external file (use .js suffix) If embed JS within HTML
A Simple Example <HTML> <HEAD> <TITLE> A Beginning Script </TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> document.write ("Welcome to the wonderful world of JavaScript"); </SCRIPT> </BODY> </HTML> These statements are run before HTML document interpreted by browser Within the javascript ‘mode’ any output to browswer needs to be within a document.write output command
Where do you put it? • Can add JavaScript to head or body of html document • Functions are usually added to the head section • assures that the functions OK (parsed) by the time they are called. • Non-functions usually put in body • then can call and functions in head
Objectives • Introduction to JavaScript • JavaScript: Its Beginnings • Advantages and disadvantages • How differs from html and server side programs • Working with JS and HTML tags. • Running onload, when done, on an event • Using JS objects • Objects with properties and methods • Using conditional tests
When does it run? • JavaScript can run • as the page loads • as soon as the page is finished loading • in response to user input (remember the form button?) Competency Alert: You need to know this!
JavaScript that Runs as Page Loads Normal HTML code <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY bgColor=#ccccff> <CENTER> <H2>Document Object </H2> <SCRIPT language=JavaScript> document.write("This page was last modified on” + document.lastModified); </SCRIPT> </CENTER></BODY></HTML> Enter JavaScript. Within the html body (in this case) document.write like print. Get lastModified browser vrbl. . The + is catenation. Calls function to get current date and output date document.write("This page was last modified on” + document.lastModified); Output this set of text (called a string) Output the result of this ‘command’
JavaScript output (onload) is HTML input … . The output of JavaScript statements is taken as HTML input... <HTML> <HEAD><TITLE> A Beginning Script </TITLE> </HEAD><BODY> <SCRIPT language=JavaScript> document.write ("<FONT Size=4>JavaScript commands are interpreted first</FONT>"); document.write ("<BR> <FONT COLOR=BLUE>JS output often generates HTML</FONT>"); </SCRIPT> </BODY></HTML></HTML> Write these 2 messages
JavaScript that Runs when Loading Complete <html> <head> <title> Java Example 2 </title> </head> <body onload=waitLittle()> <font size=4 color=blue> welcome to my page </font> <br>Here is my stuff <br> <br> <script language="JavaScript"> function waitLittle() { setTimeout( "alertMe()", 5000 ); } function alertMe() { alert('test'); } </script> This is some text over here. </body> </html> Run ‘allertMe’ code call after 5000 miliseconds Run ‘waitLittle’ when page is loaded Create a pop-up box with test as text After 5000 milisecond pop-up
JavaScript that Runs in Response to User Input <html><head> <script language="JavaScript"> <!-- function showTime() { document.forms["getDate"].curTime.value = (new Date()).toLocaleString(); } function alertme() { alert("Don't Do that"); } //--> </script> </head> <body style="background-color: #fffff0;"> <form name="getDate"> <input type="button" name="getTime" onClick="showTime()" value="Show Current Time" /> <input type="text" name="curTime" size="40" onClick="alertme()"/> </form> Set the value of the form variable curTime to the current time When click call showtime If they click generate an alert
Dealing with Browsers that don’t Support JavaScript You may have noticed something a little strange about the examples so far. <script language=“JavaScript”> <!-- Javascript code //--> </script> This makes the script invisible to browsers that don’t support JavaScript by “commenting it out”. In addition, you can provide some page content that only displays when the browser DOESN’T handle JavaScript: <noscript> Your browser doesn’t support Javascript </noscript> The only limitation with this is that this will NOT be displayed by NS if the user has JavaScript just disabled.
Some Important Aspects of JavaScript • Case Sensitive: Variable names, functions you use • - (e.g., Date not date ) • Space Insensitive - generally ignored, except in strings • Statements end in semicolon – Except JS will assume you meant to semicolon at the end of the line if the statement appears to be complete.
Objectives • Introduction to JavaScript • JavaScript: Its Beginnings • Advantages and disadvantages • How differs from html and server side programs • Working with JS and HTML tags. • Running onload, when done, on an event • Using JS objects • Objects with properties and methods • Using conditional tests
JavaScript And Objects ... • JavaScript is object-oriented • Objects are things your scripts can work with • Have JS objects to work with browsers, windows, and forms • Objects have • properties - are variables or other objects describing the object. • E.g., document.lastmodified • methods - behaviors or built-in functions you use • E.g., accessed my ObjectName.MethodName() Object name Property has time value (like a date) Method name Object name
Using JavaScript Objects … • Lots of useful properties available • Here are some properties for window object: • document.lastModified – (read-only property) gives the document last changed date • document.URL - (read-only property) gives the URL of the document source code file. • window.referrer – (read-only property) gives the URL of the calling document. (It is an empty string, if user does not reach the URL by clicking a link. • window.title – (read-only property) gives the value in the <TITLE> ... </TITLE> tag.
Printing out one of these Can use the plus sign (+) to attach string output with propert output document.write("last modified:” + document.lastModified + "<P>"); Write the following out. Print out this string Attach to the string this property Attach to the entire string this html tag
A couple other interesting properties • Here are a few examples of properties • navigator.appName – Set to the browser name • window.location – the current URL your viewing. Setting this property to a URL will redirect the browser • window.location = ‘http://indelible-learning.com’; • window.status – what is being displayed on the status line of the browser • navigator.appName – Name of browser running • document.title – the information in the <title> tag • document.lastModified – last modified time of document Competency Alert: You need to know this!
For example <HTML> <HEAD> <TITLE>Document Information Properties</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> document.write("Referring link was:” + document.referrer) + "<BR>") document.write("Document URL is:“ + document.URL +"<BR>") document.write("The title is: " + document.title +"<BR>") document. write("last modified:” + document.lastModified + "</P>") </SCRIPT> <HR> This is my web site. It is my Web Site all by myself. </BODY> </HTML>
Using an Object Method – date() • The Date object to access time and date information. • Unlike the Math object, need to create a Date object first: • var dateObj = new Date(); • You can specify the data/time when you create the object. • xmasObj = new Date(“December, 25, 2002”); • Can print out current date via: • document.write ( new Date().toLocaleString()); Creates new date object <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY bgColor=#ccccff> <CENTER> <H2>Document Object </H2> <SCRIPT language=JavaScript> document.write ( new Date().toLocaleString()); </SCRIPT> </CENTER></BODY></HTML>
The Math Object An example JavaScript object. Math.abs(number) Math.sin(number) Math.cos(number) Math.round(number) Math.ceil(number) Math.floor(number) Math.log(number) Math.sqrt(number) Math.random(number) • absolute value • sine of an angle (expressed in radians) • cosine of an angle (expressed in radians) • closest integer value • rounds up to next integer value • rounds down to next integer value • natural log of the number • square root of the number • returns a floating point number • that is >= 0.0 but < 1.0 Other methods include: tangent, arc tangent, arc sine, arc cosine, tangent, power, angle of polar coordinates, maximum, and minimum. Also has constant definitions for values like pi and e (natural log base).
Math Object Example <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY> <SCRIPT language=JavaScript> document.write( "<br> sqrt(25)=" + Math.sqrt(25)); document.write( "<br> round(5.632)=" +Math.round(5.632)); document.write( "<br> floor( 5.232 )=" + Math.floor( 5.232 )); </SCRIPT> </CENTER></BODY></HTML>
Objectives • Introduction to JavaScript • JavaScript: Its Beginnings • Advantages and disadvantages • How differs from html and server side programs • Working with JS and HTML tags. • Running onload, when done, on an event • Using JS objects • Objects with properties and methods • Using conditional tests
Competency Alert: You need to know this! Using Variables Each variable should be ‘defined’ with var <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY bgColor=#ccccff> <CENTER> <H2>Using Variables </H2> <SCRIPT language=JavaScript> var x = 12; var y = 15; var z = y + x; document.write( "x=" + x + "<br>"); document.write ( 'y='+ y + "<br>" ); document.write ( 'z=' + z + "<br>"); </SCRIPT> </CENTER></BODY></HTML> Set variables x, y, z Output a string, then a variable and then <br> tag. Note: remember to separate strings from values with a plus sign Common Problem Area! People seem to forget this
Some JavaScript Assignments <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY bgColor=#ccccff> <CENTER> <H2>Using Variables </H2> <SCRIPT language=JavaScript> x = 1; x++; x *= 2; document.write( "x=" + x + "<br>"); </SCRIPT> </CENTER></BODY></HTML>
Using prompt . . . • Prompt will ask the user for input and set a variable with result. . . <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY bgColor=#ccccff> <CENTER> <H2>Using Variables </H2> <SCRIPT language=JavaScript> var rad = prompt('What is radius of wheel (in inches)?'); rad = parseInt(rad); var rotations = prompt('How many rotations did the wheel make?'); rotations = parseInt(rotations); var dist = 3.14 * (rad * rad) * rotations; var dist_feet = dist / 12; document.write( "Caluating distance using a wheel of radius " + rad + " inches"); document.write( " that made " + rotations + " rotations <br>"); document.write( "distance=" + dist + " inches<br>"); document.write( "dist in feet=" + dist_feet + " feet<br>"); </SCRIPT> </CENTER></BODY></HTML> Convert character 10 to number 10
JavaScript Is also Event Driven • In JavaScript you can specify actions to take on many different events: • onAbort, • onBlur, • onChange, • onClick, • onDblClick, • onDragDrop, • onError, • onFocus, • onKeyDown, • onKeyPress, • onKeyUp, • onload, • onMouseDown, • onMouseOut, • onMouseOver, • onMouseUp, • onMove, • onReset, • onResize, • onSelect, • onSubmit, • onUnload User’s cursor left a window item (then can specify some action) User clicks a window item (then can specify some action) User puts cursor over a window item (then take some action) User selects a window item contents can specify some action
Example of a JavaScript Event <html><head> <title> my form </title> </head> <body> <script> function genAlert() { alert( "Don't do that!" ); } </script> <form name="totals"> <input type="text" name="total" OnClick="genAlert()"></formm> </body> </html> When click form item then do genalert() code.
Common Problem Area! People seem to forget this Debugging JavaScript • Both Netscatpe and Firefox have built in JavaScript debug tool • From URL line type javascript: Entering javascript: will open a JavaScript debug window Any error messages, while script runs will show errors here
Objectives • Introduction to JavaScript • JavaScript: Its Beginnings • Advantages and disadvantages • How differs from html and server side programs • Working with JS and HTML tags. • Running onload, when done, on an event • Using JS objects • Objects with properties and methods • Using conditional tests
Competency Alert: You need to know this! Conditionals • JavaScript has many programming constructs if ( x == 6 ) { document.write( “6 X=“ ); document.write( x ); x += 1; } else if ( x > 6 ) { document.write( “LT 6 X=“ ); document.write( x ); x += 1; } else { document.write( “else 6 X=“ ); document.write( x ); } document.write( “x=“ + x ); 1 or more statements to run when x is equal to 6. Test these only when x X is not 6 Run when X > 6. Run X is not 6 or gt 6 HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY bgColor=#ccccff> <SCRIPT language=JavaScript> x=5; if ( x == 6 ) { document.write( "6 X=" ); document.write( x ); x += 1; } else if ( x > 6 ) { document.write( "LT 6 X=" ); document.write( x ); x += 1; } else { document.write( "else 6 X=" ); document.write( x ); } document.wirte( "x=" + x ); </script> <H2>Using Variables </H2> </SCRIPT> </CENTER></BODY></HTML>
Example Grade Calculator <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY bgColor=#ccccff> <SCRIPT language=JavaScript> var t1 = prompt( "Enter the score for the first test"); t1=parseInt(t1); if ( t1 < 0 || t1 > 100 ) { alert( "Impossible score - I cannot go on!"); exit; } var t2 = prompt( "Enter the score for the second test"); t2=parseInt(t2); if ( t2 < 0 || t2 > 100 ) { alert( "Impossible score for t2 - I cannot go on!"); exit; } var t3 = parseInt(prompt( "Enter the score for the third test")); if ( t3 < 0 || t3 > 100 ) { alert( "Impossible score - I cannot go on!"); exit; } var aver = ( t1 + t2 + t3 ) / 3; var grade; if ( aver >= 90 ) { grade = 'A'; } else if ( aver >= 80 ) { grade = 'B' } else if ( aver >= 70 ) { grade = 'C' } else { grade = 'D or lower'; } document.write( 'Student average was ' + aver ); document.write( '<br>This score is a ' + grade ); </SCRIPT> </CENTER></BODY></HTML> Notice how convert to number on 1 line
Testing Browser Versions <HTML><HEAD><TITLE>Document Object</TITLE></HEAD><BODY> <SCRIPT language=JavaScript> if ( navigator.appName == 'Netscape' ) { document.bgColor='#c6c6c6'; document.write( 'name=' + navigator.appName ); document.write( '<br>version=' + navigator.appVersion ); document.write( '<br> appCodename=' + navigator.appCodeName ); document.write( '<br> userAgenet=' + navigator.userAgent ); } else { document.bgColor='yellow'; document.write( 'Not netscape name=' + navigator.appName ); document.write( '<br>version=' + navigator.appVersion); document.write( '<br> appCodename=' + navigator.appCodeName ); document.write( '<br> userAgenet=' + navigator.userAgent ); } </SCRIPT></BODY></HTML> When netscape do this When not netscape do this
Summary • Introduction to JavaScript • JavaScript: Its Beginnings • Advantages and disadvantages • How differs from html and server side programs • Working with JS and HTML tags. • Running onload, when done, on an event • Using JS objects • Objects with properties and methods • Using conditional tests
Hands on assignment • Write a simple javascript-based web page that • Redirects the browser to http://netscape.com if the user is using netscape or firefox • Redirects the browser to http://microsoft.com otherwise • Hint: you can redirect a browser by setting the window.location property.
One Possible Solution . . . <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY> <SCRIPT language=JavaScript> if ( navigator.appName == 'Netscape') { window.location = 'http://www.netscape.com'; } else { window.location = 'http://www.microsoft.com'; } </SCRIPT> </CENTER></BODY></HTML>
Another Hands on assignment • Create a webpage with JavaScript that: • Displays the current date • Prompts the user for number of rows, cols and ticket cost. • Displays number of seats and total revenue.
One Possible Solution <HTML><HEAD><TITLE>Document Object</TITLE> </HEAD> <BODY> <SCRIPT language=JavaScript> document.write ("Today is " + new Date().toLocaleString() + "<br>"); var rows = parseInt( prompt("How many rows?")); var cols = parseInt( prompt("How many seats per row?")); var ticket = parseInt( prompt("How much per ticket?")); var size = rows * cols; var rev = size * ticket; document.write( "We have " + size + " total seats.<br>" ); document.write( "We have maximum of " + rev + " total revenue.<br>" ); </SCRIPT> </CENTER></BODY></HTML>