Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 A World Wind Tour of JavaScript JavaScript. 2 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How.

Similar presentations


Presentation on theme: "1 A World Wind Tour of JavaScript JavaScript. 2 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How."— Presentation transcript:

1 1 A World Wind Tour of JavaScript JavaScript

2 2 Objectives l 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

3 3 Competencies l 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

4 4 JavaScript: Its Beginnings l JavaScript developed by Netscape & initially called livescript. l 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). l Microsoft … »Came out with their own flavor of JavaScript called “Jscript”. »They also added support for VBScript in IE. Differences are minor. l 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.

5 5 The “goods” on JavaScript l JavaScript can be used to: 1. perform simple client-side computations l For example, add up total costs of shopping cart before it is submitted. 2. facilitate dynamic and interactive Web page creation l 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 -

6 6 The “not so goods” on JavaScript l JavaScript runs completely on Client machine l It does NOT have: 1. Any graphic capabilities l E.g., cannot show a graph of survey results. 2. Access to client (you PC) resources l Cannot print, modifying PC files, or launching client applications. 3. Access to any Web server resources l E.g., cannot send email, write to file, write to database.

7 7 PHP/JavaScript Similarities and Differences l What they have in common. Both languages can: 1.Be embedded in HTML documents 2.Cause dynamic content to be displayed (e.g., the current date) 3.Can be placed in external files and “included” into html files 4.Look more like a programming language than HTML l What they DON’T have in common: 1.The big difference … JavaScript runs 100% on client (i.e., PC). This means: A. JavaScript stuff runs noticeably faster (not dependent on Internet and Web Server) B. PHP has access to Web Server resources (mail, databases, files) 2.Using differences A.Writing JavaScript does NOT require a Web Server (but more concern about browser implementation differences). B.PHP’s syntax is easier to write and understand for beginners.

8 8 How JavaScript Pages are Run JavaScript does not run here JavaScript is run here by the browser but just before HTML

9 9 Objectives l 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

10 10 Adding JavaScript to HTML pages JavaScript is added to HTML pages using the tag. usually placed in the HEAD or BODY of the document <!-- Javascript code //--> If link to an external file (use.js suffix) If embed JS within HTML

11 11 A Simple Example A Beginning Script document.write ("Welcome to the wonderful world of JavaScript"); 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

12 12 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

13 13 Objectives l 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

14 14 When does it run? JavaScript can run 1.as the page loads 2.as soon as the page is finished loading 3.in response to user input (remember the form button?) Competency Alert: You need to know this !

15 15 Document Object Document Object document.write("This page was last modified on” + document.lastModified); JavaScript that Runs as Page Loads Enter JavaScript. Within the html body (in this case) Normal HTML code 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’

16 16 JavaScript output (onload) is HTML input ….. The output of JavaScript statements is taken as HTML input... A Beginning Script document.write (" JavaScript commands are interpreted first "); document.write (" JS output often generates HTML "); Write these 2 messages

17 17 Java Example 2 welcome to my page Here is my stuff function waitLittle() { setTimeout( "alertMe()", 5000 ); } function alertMe() { alert('test'); } This is some text over here. JavaScript that Runs when Loading Complete Run ‘allertMe’ code call after 5000 miliseconds Create a pop-up box with test as text After 5000 milisecond pop-up Run ‘waitLittle’ when page is loaded

18 18 JavaScript that Runs in Response to User Input <!-- function showTime() { document.forms["getDate"].curTime.value = (new Date()).toLocaleString(); } function alertme() { alert("Don't Do that"); } //--> <input type="button" name="getTime" onClick="showTime()" value="Show Current Time" /> When click call showtime Set the value of the form variable curTime to the current time If they click generate an alert

19 19 Dealing with Browsers that don’t Support JavaScript You may have noticed something a little strange about the examples so far. <!-- Javascript code //--> 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: Your browser doesn’t support Javascript The only limitation with this is that this will NOT be displayed by NS if the user has JavaScript just disabled.

20 20 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.

21 21 Objectives l 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

22 22 JavaScript And Objects... l JavaScript is object-oriented –Objects are things your scripts can work with l Have JS objects to work with browsers, windows, and forms –Objects have l properties - are variables or other objects describing the object. »E.g., document.lastmodified l 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

23 23 Using JavaScript Objects … l Lots of useful properties available l 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... tag.

24 24 Printing out one of these Can use the plus sign (+) to attach string output with propert output document.write("last modified:” + document.lastModified + " "); Print out this string Attach to the string this property Attach to the entire string this html tag Write the following out.

25 25 A couple other interesting properties l 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 tag »document.lastModified – last modified time of document Competency Alert: You need to know this !

26 26 For example Document Information Properties document.write("Referring link was:” + document.referrer) + " ") document.write("Document URL is:“ + document.URL +" ") document.write("The title is: " + document.title +" ") document. write("last modified:” + document.lastModified + " ") This is my web site. It is my Web Site all by myself.

27 27 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 Document Object Document Object document.write ( new Date().toLocaleString());

28 28 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).

29 29 Math Object Example Document Object document.write( " sqrt(25)=" + Math.sqrt(25)); document.write( " round(5.632)=" +Math.round(5.632)); document.write( " floor( 5.232 )=" + Math.floor( 5.232 ));

30 30 Objectives l 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

31 31 Using Variables Document Object Using Variables var x = 12; var y = 15; var z = y + x; document.write( "x=" + x + " "); document.write ( 'y='+ y + " " ); document.write ( 'z=' + z + " "); Set variables x, y, z Output a string, then a variable and then tag. Common Problem Area! People seem to forget this Note: remember to separate strings from values with a plus sign Competency Alert: You need to know this ! Each variable should be ‘defined’ with var

32 32 Some JavaScript Operators OperExampleResult +X = 2 + zAddition - X is assigned z plus 2 + (strg)Z = ‘a’ + ‘b” ;Catenation - Z is assigned ‘ab’ -y= 3 – 1;Subtraction – y is assign 2; *y=2*apple;Multiplication – y is assign 2 times apple /x = y / 2;Division = z is assign y divided by 2. %x = y / 2;Modulus – x is assign remainder of y/2; --x--;Decrement – same as x = x – 1; ++y++;Increment – same as y = y + 1;

33 33 Some JavaScript Assignments OperExampleResult =X = 1 + 2;X is assign 3; +=y += 2;y= y + 2; -=z -= 1z = z – 1; *=X *= 2;x = x * 2; / =x /= 2;x = x / 2; Document Object Using Variables x = 1; x++; x *= 2; document.write( "x=" + x + " ");

34 34 Using prompt... l Prompt will ask the user for input and set a variable with result... Document Object Using Variables 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 "); document.write( "distance=" + dist + " inches "); document.write( "dist in feet=" + dist_feet + " feet "); Convert character 10 to number 10

35 35 JavaScript Is also Event Driven l 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 selects a window item contents can specify some action User puts cursor over a window item (then take some action) User clicks a window item (then can specify some action) User’s cursor left a window item (then can specify some action)

36 36 Example of a JavaScript Event my form function genAlert() { alert( "Don't do that!" ); } When click form item then do genalert() code.

37 37 Debugging JavaScript l 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 Common Problem Area! People seem to forget this

38 38 Objectives l 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

39 39 Conditionals l 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> Document Object 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 ); Using Variables Competency Alert: You need to know this !

40 40 Example Grade Calculator Document Object var t1 = prompt( "Enter the score for the first test"); t1=parseInt(t1); if ( 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 100 ) { alert( "Impossible score for t2 - I cannot go on!"); exit; } var t3 = parseInt(prompt( "Enter the score for the third test")); if ( 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( ' This score is a ' + grade ); Notice how convert to number on 1 line

41 41 JavaScript Conditional Tests OperExampleResult ==if ( x == 1 )Is true if x is equal to 1 !=if ( apple != ‘blue’ )Is true if apple is NOT equal to ‘blue’ >if ( z > y )Is true if z is greater that y >=if ( z >= y )Is true if z is greater than or equal to y <if ( z < 3 )Is true if z is less than 3 <=if ( z <= y )Is true if z is less than or equal to y &&If ( a && b)Is true if both a and b are true ||If ( a || b)Is true if both a || b are true !If ( !x )Is true is x is false

42 42 Testing Browser Versions Document Object if ( navigator.appName == 'Netscape' ) { document.bgColor='#c6c6c6'; document.write( 'name=' + navigator.appName ); document.write( ' version=' + navigator.appVersion ); document.write( ' appCodename=' + navigator.appCodeName ); document.write( ' userAgenet=' + navigator.userAgent ); } else { document.bgColor='yellow'; document.write( 'Not netscape name=' + navigator.appName ); document.write( ' version=' + navigator.appVersion); document.write( ' appCodename=' + navigator.appCodeName ); document.write( ' userAgenet=' + navigator.userAgent ); } When netscape do this When not netscape do this

43 43 Summary l 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

44 44 Hands on assignment l Write a simple javascript-based web page that »Redirects the browser to http://netscape.com if the user is using netscape or firefox http://netscape.com »Redirects the browser to http://microsoft.com otherwise http://microsoft.com »Hint: you can redirect a browser by setting the window.location property.

45 45 One Possible Solution... Document Object if ( navigator.appName == 'Netscape') { window.location = 'http://www.netscape.com'; } else { window.location = 'http://www.microsoft.com'; }

46 46 Another Hands on assignment l 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.

47 47 One Possible Solution Document Object document.write ("Today is " + new Date().toLocaleString() + " "); 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. " ); document.write( "We have maximum of " + rev + " total revenue. " );


Download ppt "1 A World Wind Tour of JavaScript JavaScript. 2 Objectives l Introduction to JavaScript »JavaScript: Its Beginnings –Advantages and disadvantages –How."

Similar presentations


Ads by Google