1 / 44

Introduction to Javascript

Introduction to Javascript. variables , window dialogues, loops, Date , String , Math , functions, etc. Textbook: chapter 8 Reference Book: Javascript chapters JavaScript Tutorial at http://www.w3schools.com/js/. Client-side scripting.

sibyl
Download Presentation

Introduction to Javascript

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. Introduction to Javascript variables, window dialogues, loops, Date, String, Math, functions, etc. Textbook: chapter 8 Reference Book: Javascript chapters JavaScript Tutorial at http://www.w3schools.com/js/

  2. Client-side scripting • client-side script: code runs in browser after page is sent back from server • often this code manipulates the page or responds to user actions

  3. Why use client-side programming? • client-side scripting (JavaScript) benefits: • usability: can modify a page without having to post back to the server (faster UI) • efficiency: can make small, quick changes to page without waiting for server • event-driven: can respond to user actions like clicks and key presses • Server-side programming (PHP) benefits: • security: has access to server's private data; client can't see source code • compatibility: not subject to browser compatibility issues • power: can write files, open connections to servers, connect to databases, ..

  4. What is JavaScript? • JavaScript is a lightweight programming scripting language that facilitates a disciplined approach to designing computer programs that enhance the functionality and appearance of web pages. • used to make web pages interactive • insert dynamic text into HTML (ex: user name) • react to events (ex: page load user click) • get information about a user's computer (ex: browser type) • perform calculations on user's computer (ex: form validation) • a web standard (but not supported identically by all browsers) • NOT related to Java other than by name and some syntactic similarities

  5. JavaScript vs. Java • interpreted, not compiled • more relaxed syntax and rules • fewer and "looser" data types • variables don't need to be declared • errors often silent (few exceptions) • key construct is the function rather than the class • "first-class" functions are used in many situations • contained within a web page and integrates with its HTML/CSS content

  6. Linking to a JavaScript file: script <script src="filename" type="text/javascript"></script> <script src="example.js" type="text/javascript"></script> • scripttag should be placed in HTML page's head • scriptcode is stored in a separate .js file • JS code can be placed directly in the HTML file's bodyor head(like CSS) • but this is bad style (should separate content, presentation, and behavior) • The <script> tag indicates to the browser that the text that follows is part of a script. • Attribute type specifies the scripting language used in the script—such as text/javascript

  7. Some JavaScript features • The browser interprets the contents of the <head> section first • Every statement should end with a semicolon ; • JavaScript iscase sensitive • Astring can be contained between double (") or single (') quotation • A single-line comment begins with the characters // and terminates at the end of the line • Multiline comments begin with delimiter /* and end with */ • recall: 4 comment syntaxes • HTML: <!-- comment --> • CSS/JS/PHP: /* comment */ • Java/JS/PHP: // comment • PHP: # comment

  8. document object • documentobject representstheHTML document currently being displayed in the browser • Browser contains a complete set of objects that allow programmers to access and manipulate every element of an HTML document • Object resides in memory and contains information used by the script • Object implies attributes (data) and behaviors(methods) • methods use the attributes’ data to perform useful actions for the client of the document.writeln(“text" ); document.writeln("<h1>Welcome to JavaScript Programming!</h1>" ); • The documentobject’swritelnmethod • Writes a line of HTML text in the HTML document • Text displayed is dependent on the contents of the string written, which is subsequently rendered by the browser. • Browser will interpret the HTML elements as it normally does to render the final text in the document

  9. Simple program: Display a line of text • You cannot split a statement in the middle of a string. The + operator (called the “concatenation operator” when used in this manner) joins two strings together • Many people confuse the writing of HTML text with the rendering of HTML text. WritingHTML text creates the HTMLthat will be rendered by the browser for presentation to the user.

  10. Simple program: Display a line of text

  11. JavaScript Popup Boxes alert("message"); window.alert("message"); var name; name = window.prompt("sometext","defaultvalue"); confirm("sometext"); window.confirm("message"); • Useful to display information in windows that “pop up” on the screen • display plain text; they do not render HTML. • Browser’s window object’s alert method displays an alert dialog • The window object’sprompt method displays a dialog into which the user can type a value. • first argument is a prompt message to direct the user to take a specific action. • optionalsecond argument is the default string to display in the text field. • Script can then use the value that the user inputs. • window object’s confirm method is often used if you want the user to verify or accept something. • When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

  12. JavaScript Popup Boxes-alert welcome.html <head> <title>Printing Multiple Lines in a Dialog Box</title> <script src="welcome.js" type="text/javascript"></script> </head> <body> <p>Click Refresh (or Reload) to run this script again.</p> </body> welcome.js window.alert( "Welcome to\nJavaScript\nProgramming!" );

  13. Variables and types var name; var name = expression; var age = 32; var weight = 127.4; varclientName = "Connie Client"; • Keyword var is used to declare variables • All variables have a name, type and value, and should be declared before they are used in a program • A variable name mayconsist of letters, digits, underscores ( _ ) and dollar signs($) that does not begin with a digit and is not a reserved JavaScript keyword. • types are not specified, but JS does have types ("loosely typed") • Number, Boolean, String, Array, Object, Null, Undefined • can find out a variable's type by calling typeof • A variable can contain a value of any data type, and in many situations, JavaScript automatically converts between values of different types for you. • A declared variable that is not given a value, it has an undefinedvalue. • If such variable is used, it results in logic errors and produces the value NaN(not a number) • Declarations end with a semicolon (;)

  14. Null and undefined • null keyword signifies that a variable has no value • null is not a string literal, but rather a predefined term indicating the absence of value • Writing a null value to the document, however, displays the word “null” • When variables are declared, they are not assigned default values but undefined. varned = null; varbenson = 9; varcaroline; // at this point in the code, // ned is null // benson's 9 // caroline is undefined

  15. parseInt and parseFloat • JavaScript provides seven global functions as part of a Globalobject: parseInt and parseFloatare two of them • Function parseInt converts its string argument to an integer • JavaScript represents all numbers as floating-point numbers in memory • If the string passed to parseIntcontains a floating-point numeric value, parseInt simply truncates the floating-point part. • For example, the string "27.95" results in the integer 27, • string "–123.45" results in the integer –123. • parseInt ( "abc123.45" ) returns NaN • parseFloatTakes a string argument and attempts to convert the beginning of the string into a floating-point value. • If the conversion is unsuccessful, the function returns NaN; • otherwise, it returns the converted value • parseFloat( "abc123.45" ) returns NaN • parseFloat( "123.45abc" ) returns the value 123.45

  16. Obtaining User Input with prompt Dialogs

  17. Obtaining User Input with prompt Dialogs addition.js varfirstNumber, secondNumber; // first and second string entered by user var number1, number2; // first and second number to add var sum; // sum of number1 and number2 // read in first number from user as a string firstNumber = window.prompt( "Enter first integer" ); // read in second number from user as a string secondNumber = window.prompt( "Enter second integer" ); // convert numbers from strings to integers number1 = parseInt( firstNumber ); number2 = parseInt( secondNumber ); sum = number1 + number2; // add the numbers // display the results document.writeln( "<h1>The sum is " + sum + "</h1>" ); window.alert( "The sum is " + sum ); … <head> <script src="addition.js" type="text/javascript"></script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body> … addition.html

  18. Confirm Dialogs confim.js var r = confirm("Press a button"); if (r == true) { alert("You pressed OK!"); } else { alert("You pressed Cancel!"); } confirm.html … <head> <script src="addition.js" type="text/javascript"></script> </head> <body> <script src="confirm.js" type="text/javascript"></script> </body> …

  19. if/else statement (same as Java) & (?:) if (condition) { statements; } else if (condition) { statements; } else { statements; } Conditional operator (?:) • takes three operands that together with the operator form a conditional expression • first operand is a boolean expression • second is the value for the conditional expression if booleanexpression is true • Third is the value for the conditional expression if booleanexpression is false document.writeln(studentGrade >= 60 ?“Passed” :“Failed" );

  20. Algebraic, Logical, and relational operators • most logical operators automatically convert types: 5 < "7" is true • 42 == 42.0 is true • "5.0" == 5 is true • === and !== are strict equality tests; checks both type and value "5.0" === 5 is false

  21. Dateobject var name; //string entered by the user var now = new Date(); // current date and time var hour = now.getHours(); // current hour (0-23) // read the name from the prompt box as a string name = window.prompt( "Please enter your name" ); // determine whether it is morning if ( hour < 12 ) document.write( "<h1>Good Morning, " ); // determine whether the time is PM if ( hour >= 12 ){ hour = hour - 12; // convert to a 12-hour clock // determine whether it is before 6 PM if ( hour < 6 ) document.write( "<h1>Good Afternoon, " ); // determine whether it is after 6 PM if ( hour >= 6 ) document.write( "<h1>Good Evening, " ); } // end if document.writeln( name + ", welcome to JavaScript programming!</h1>" ); Date object is used acquire the current local time date.js <head> <title>Using Relational Operators</title> <script src="date.js" type="text/javascript"></script> </head> <body> <p>Click Refresh (or Reload) to run this script again.</p> </body> date.html

  22. Dateobject • Date object provides methods for date and time manipulations • Based either on the computer’s local time zone or on World Time Standard’s Coordinated Universal Time (abbreviated UTC) • Empty parentheses after an object name indicate a call to the object’s constructor with no arguments • The Date constructor with no arguments initializes the Date object with the local computer’s current date and time • A new Date object can be initialized by passing to the constructor either • the number of milliseconds since midnight, January 1, 1970, • Arguments for year, month, date, hours, minutes, seconds and milliseconds. • Hours, minutes, seconds and milliseconds arguments are all optional • If any one of these arguments is not specified, a zero is supplied in its place • If an argument is specified, all arguments to its left must be specified

  23. Dateobject

  24. Dateobject

  25. var current = new Date(); document.writeln( "<h1>String representations and valueOf</h1>" ); document.writeln( "toString: " + current.toString() + "<br />toLocaleString: " + current.toLocaleString() + "<br />toUTCString: " + current.toUTCString() + "<br />valueOf: " + current.valueOf() ); document.writeln( "<h1>Get methods for local time zone</h1>" ); document.writeln( "getDate: " + current.getDate() + "<br />getDay: " + current.getDay() + "<br />getMonth: " + current.getMonth() + "<br />getFullYear: " + current.getFullYear() + "<br />getTime: " + current.getTime() + "<br />getHours: " + current.getHours() + "<br />getMinutes: " + current.getMinutes() + "<br />getSeconds: " + current.getSeconds() + "<br />getMilliseconds: " + current.getMilliseconds() + "<br />getTimezoneOffset: " + current.getTimezoneOffset()); document.writeln( "<h1>Specifying arguments for a new Date</h1>" ); varanotherDate = new Date( 2007, 2, 18, 1, 5, 0, 0 ); document.writeln( "Date: " + anotherDate ); document.writeln( "<h1>Set methods for local time zone</h1>" ); anotherDate.setDate( 31 ); anotherDate.setMonth( 11 ); anotherDate.setFullYear( 2007 ); anotherDate.setHours( 23 ); anotherDate.setMinutes( 59 ); anotherDate.setSeconds( 59 ); document.writeln( "Modified date: " + anotherDate ); Date object –datetime.js

  26. Number type var enrollment = 99; varmedianGrade = 2.8; var credits = 5 + 4 + (2 * 3); • integers and real numbers are the same type (no int vs. double) • similar precedence to Java

  27. Boolean type var iLike190M = true; varieIsGood = "IE6" > 0; // false if ("web dev is great") { /* true */ } if (0) { /* false */ } • any value can be used as a Boolean • "falsey" values: 0, 0.0, NaN, "", null, and undefined • "truthy" values: anything else • converting a value into a Boolean explicitly: • varboolValue = Boolean(otherValue);

  28. while loops (same as Java) while (condition) { statements; } do { statements; } while (condition); • break and continue keywords also behave as in Java 28

  29. var total; // sum of grades vargradeCounter; // number of grades entered var grade; // grade typed by user (as a string) vargradeValue; // grade value (converted to integer) var average; // average of all grades // Initialization phase total = 0; // clear total gradeCounter = 0; // prepare to loop // prompt for input and read grade from user grade = window.prompt( "Enter Integer Grade, -1 to Quit:", "0"); // convert grade from a String to an integer gradeValue = parseInt( grade ); while ( gradeValue != -1 ) { total = total + gradeValue; // add gradeValue to total gradeCounter = gradeCounter + 1; // add 1 to gradeCounter // prompt for input and read grade from user grade = window.prompt( "Enter Integer Grade, -1 to Quit:", "0"); // convert grade from a String to an integer gradeValue = parseInt( grade ); } // end while // Termination phase if ( gradeCounter != 0 ){ average = total / gradeCounter; // display average of exam grades document.writeln("<h1>Class average is " + average + "</h1>" ); } // end if else document.writeln( "<p>No grades were entered</p>" ); Example: average.js 29

  30. for loop (same as Java) for (initialization; condition; update) { statements; } var sum = 0; for (var i = 0; i < 100; i++) { sum = sum + i; } var s1 = "hello"; var s2 = ""; for (var i = 0; i < s1.length; i++) { s2 += s1.charAt(i) + s1.charAt(i); } // s2 stores "hheelllloo" 30

  31. Example–interest.js (to calculate the interest rate for 10 years) var amount; // current amount of money var principal = 1000.0; // principal amount var rate = .05; // interest rate // begin the table document.writeln( "<table border = \"1\">" ); //add caption document.writeln( "<caption>Calculating Compound Interest</caption>" ); // year column heading document.writeln( "<thead><tr><th>Year</th>"); // amount column heading document.writeln( "<th>Amount on deposit</th>"); document.writeln( "</tr></thead><tbody>"); // output a table row for each year for ( var year = 1; year <= 10; ++year ){ amount = principal * Math.pow( 1.0 + rate, year ); document.writeln( "<tr><td>" + year + "</td><td>" + amount.toFixed(2) + "</td></tr>"); } //end for document.writeln( "</tbody></table>" ); 31 31

  32. String type var s = "Connie Client"; varfName = s.substring(0, s.indexOf(" ")); // "Connie" varlen = s.length; // 13 var s2 = 'Melvin Merchant'; // can use "" or ' ' • method charAt returns a one-letter String (there is no char type) • Length is a property (not a method as in Java) • many operators auto-convert types: "2" * 3 is 6 • Confusing the + concatenation operator used for string with the + addition operator often leads to undesired results. • 1 + 1 is 2 • "1" + 1 is "11" • if y =5 then, then "y + 2 = " + y + 2 results in "y + 2 = 52", not "y + 2 = 7", • first the value of y (i.e., 5) is concatenated with the string"y + 2 = ", • then the value 2 is concatenated with the new, larger string "y + 2 = 5". • "y + 2 = " + (y + 2) results in "y + 2 = 7" • parentheses ensure that y + 2 is executed mathematically before it is converted to a string.

  33. String type • converting between numbers and Strings: var count = 10; var s1 = "" + count; // "10" var s2 = count + " bananas, ah ahah!"; // "10 bananas, ah ahah!" var n1 = parseInt("42 is the answer"); // 42 var n2 = parseFloat("booyah"); //NaN • accessing the letters of a String: varfirstLetter = s[0]; // fails in IE varfirstLetter = s.charAt(0); // does work in IE varlastLetter = s.charAt(s.length - 1);

  34. String type • escape sequences behave as in Java: \' \" \& \n \t \\

  35. String type

  36. String type

  37. String Example : charAt, charCodeAt, fromCharCode, toLowercaseand toUpperCase Returns the character at index 0 of string s var s = "ZEBRA"; var s2 = "AbCdEfG"; document.writeln( "<p>Character at index 0 in '" + s + "' is " + s.charAt( 0 ) ); document.writeln( "<br />Character code at index 0 in '" + s + "' is " + s.charCodeAt( 0 ) + "</p>" ); document.writeln( "<p>'" + String.fromCharCode( 87, 79, 82, 68 ) + "' contains character codes 87, 79, 82 and 68</p>" ) document.writeln( "<p>'" + s2 + "' in lowercase is '" + s2.toLowerCase() + "'" ); document.writeln( "<br />'" + s2 + "' in uppercase is '" + s2.toUpperCase() + "'</p>" ); Returns the Unicode value of the character at index 0 of string s Creates a string from the characters with the Unicode values 87, 79, 82 and 68 Converts s2 to lowercase Converts s2 to uppercase

  38. HTML Markup Methods of the String Object Puts anchor element tags around the text in anchorText with a name attribute of “top” varanchorText = "This is an anchor"; varfixedText = "This is monospaced text"; varlinkText = "Click here to go to anchorText"; varstrikeText = "This is strike out text"; varsubText = "subscript"; varsupText = "superscript"; document.writeln( anchorText.anchor( "top" ) ); document.writeln( "<br />" + fixedText.fixed() ); document.writeln( "<br />" + strikeText.strike() ); document.writeln("<br />This is text with a " + subText.sub() ); document.writeln( "<br />This is text with a " + supText.sup() ); document.writeln( "<br />" + linkText.link( "#top" ) ); Puts text in a fixed-width font by wrapping it in <tt> and </tt> tags Puts a line through text by wrapping it in <strike> and </strike> tags Puts text in a subscript font by wrapping it in <sub> and </sub> tags Puts text in a superscript font by wrapping it in <sup> and </sup> tags Creates a link to anchorText by putting anchor tags around the text in linkText with an href element of #top

  39. var choice; // user's choice var startTag; // starting list item tag var endTag; // ending list item tag var validInput = true; // indicates if input is valid var listType; // type of list as a string choice = window.prompt( "Select a list style:\n" + "1 (numbered), 2 (lettered), 3 (roman)", "1" ); switch ( choice ){ case "1": startTag = "<ol>"; endTag = "</ol>"; listType = "<h1>Numbered List</h1>"; break; case "2": startTag = "<ol style = \"list-style-type: upper-alpha\">"; endTag = "</ol>"; listType = "<h1>Lettered List</h1>"; break; case "3": startTag = "<ol style = \"list-style-type: upper-roman\">"; endTag = "</ol>"; listType = "<h1>Roman Numbered List</h1>"; break; default: validInput = false; } //end switch if ( validInput == true ){ document.writeln( listType + startTag ); for ( var i = 1; i <= 3; ++i ) document.writeln( "<li>List item " + i + "</li>" ); document.writeln( endTag ); }//end if else document.writeln( "Invalid choice: " + choice ); Using the switch multiple-selection statement

  40. Math object var rand1to10 = Math.floor(Math.random() * 10 + 1); var three = Math.floor(Math.PI);

  41. Math object

  42. Random Number Generation • Method randomgenerates a floating-point value from 0.0 up to, but not including, 1.0 • Random integers in a certain range can be generated by scaling and shifting the values returned by random, then using Math.floor to convert them to integers • scaling factor determines the size of the range (i.e. a scaling factor of 6 means six possible integers) • shift number is added to the result to determine where the range begins (i.e. shifting the numbers by 3 would give numbers between 3 and 7) • Method Math.floorrounds its argument down to the closest integer • Example: Takes the floor of the number from 1.0 up to, but not including, 7.0 Var value = Math.floor( 1 + Math.random() * 6 );

  43. functions 9.5 Random Number Generation function name(parameter-list) { statement ; statement ; ... statement ; } • Using the JavaScript varkeyword to declare a variable in a function parameter list results in a JavaScript runtime error. • Placing a semicolonafter the right parenthesis enclosing the parameter list of a function definition results in a JavaScript runtime error. • A function must be called explicitly for the code in its body to execute • returnstatement • passes information from inside a function back to the point in the program where it was called

  44. 44 Calls function square with x as an argument, which will return the value to be inserted here Names the parameter y Begin function square Returns the value of y * y (the argument squared) to the caller End function square

More Related