introduction to javascript n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Introduction to JavaScript PowerPoint Presentation
Download Presentation
Introduction to JavaScript

Loading in 2 Seconds...

play fullscreen
1 / 113

Introduction to JavaScript - PowerPoint PPT Presentation


  • 130 Views
  • Updated on

Introduction to JavaScript. From the InfoTech Internet/Intranet Series. Presented by Dr. Billy Lim Developed by Dr. Billy B. L. Lim & Dr. Joaquin Vila Applied Computer Science Illinois State University. Agenda. Introduction Basic Language Features

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
    Presentation Transcript
    1. Introduction to JavaScript From the InfoTech Internet/Intranet Series Presented by Dr. Billy Lim Developed by Dr. Billy B. L. Lim & Dr. Joaquin Vila Applied Computer Science Illinois State University

    2. Agenda • Introduction • Basic Language Features • variables, expressions, operators, statements • The JavaScript Object Model • objects, properties, methods, events • Built-in Objects and Functions • Examples and Miscellany

    3. What is JavaScript? • (Formerly LiveScript) Sun's simple, cross-platform, WWW scripting language adopted by Netscape and allies. • Compact, user-level, object-based  now OO • Ideal for making web pages “smart” • Brief history • developed (late 1995) primarily by Netscape, but in cooperation with Sun Microsystems • Brendan Eich (Netscape) • Bill Joy (Sun Microsystems)

    4. Why JavaScript? • Java and JavaScript becoming defacto standards • Huge leap from static HTML coding to Java programming • Scripting makes things easy • No additional tools needed • (a browser and text editor will do!)

    5. Server Based Processing Server Client (browser) Server Processing User’s Input

    6. Client Based Processing Server Client (browser) User’s Input Server Processing JavaScript Processing

    7. Uses of JavaScript • Tailor pages for the user • Make interactive pages • Process forms • Provide CAI (computer-aided instructions) • Special effects

    8. JavaScript and Navigator (and IE) versions Navigator versionDefault JavaScript version<SCRIPT> tags supported Navigator earlier than 2.0 JavaScript not supported None Navigator 2.0, I.E., 3.0a JavaScript 1.0 <SCRIPT LANGUAGE="JavaScript"> Navigator 3.0, IE 3.0b JavaScript 1.1 <SCRIPT LANGUAGE = "JavaScript1.1"> and all earlier versions Navigator 4.0-4.05, IE 4.0 JavaScript 1.2 <SCRIPT LANGUAGE = "JavaScript1.2"> and all earlier versions Navigator 4.06-4.7, IE 5.0 JavaScript 1.3 <SCRIPT LANGUAGE = "JavaScript1.3"> and all earlier versions IE 5.0 (partially) JavaScript 1.4 <SCRIPT LANGUAGE = "JavaScript1.4"> and all earlier versions Navigator 6, IE 5.5-6.0 JavaScript 1.5 <SCRIPT LANGUAGE = "JavaScript1.5"> and all earlier versions Note: Microsoft’s version is called JScript Official standard is called ECMAScript

    9. Using JavaScript in HTML • JavaScript can be embedded in a HTML document in three ways: • 1. As statements and functions using the SCRIPT tag. • 2. As event handlers using HTML tags. • 3. In javascript: <some javascript code here>

    10. Your First JavaScript Program FileName: hello.htm <HTML> <HEAD> <SCRIPT LANGUAGE="JavaScript"> // This is a comment in JavaScript document.write("<h1>Hello folks!</h1>"); </SCRIPT> </HEAD> <BODY> Welcome to this class! </BODY> </HTML> Also, <script type="text/javascript">

    11. First Program (cont’d) • <SCRIPT> and </SCRIPT> tags must surround your JavaScript code <SCRIPT LANGUAGE="JavaScript"> document.write("<h1>Hello folks!</h1>"); </SCRIPT> • Safest to put the tags within the <HEAD> • LANGUAGE attribute is optional

    12. write Method • document.write directs the document object to write the given string • Examples: <script> counter = 10; document.write(counter); document.write("<h1>Counter is "+counter+"</h1>"); </script> <script> document.write("<IMG SRC=‘small.gif’>"); // notice the use of “ and ‘ </script> Concatenate the strings and number together and write the resulting string out

    13. Simple Interactions • alert • Displays an Alert dialog box with a message and an OK button. • Syntax: alert("message"); • Example: alert(“You’re in a Special Area …”); alert(“count=“+count); // count is a variable to be traced here • confirm • Displays a Confirm dialog box with the specified message and OK and Cancel buttons. • Syntax: confirm("message"); • Example: ans = confirm(“Are you sure you want to continue?”); • ans will be true if OK is clicked or false if Cancel is clicked

    14. Simple Interactions (2) • eval • The eval function evaluates a string and returns a value. • Syntax: eval(stringExpression) • Example: eval(1+2*3) // gives 7 here • prompt • The prompt function prompts for a string value. • Syntax: prompt(“message”) or prompt(“message”, default value) • Example: • aString1 = prompt(“Enter Name”); • aString2 = prompt(“Enter Salary”, 0); • Note: The return value is a string. Need to convert if a numeric value is desired. Use parseInt() or parseFloat(). • Example: numSalary = parseInt(aString2); // parse aString2 into an int numSalary = numSalary + 500;

    15. Using javascript: (on the location field) • Can test the simple interactions discussed above with the command to invoke the JavaScript interpreter – javascript: on the location field of your browser (see figure below).

    16. JavaScript Debugging • In Firefox, Netscape, and Mozilla, type javascript: (on the location field) to get the console window so that you can see the error messages generated. Also, go to Error Console under Tools menu.

    17. JavaScript Debugging (2) • In Chrome, go to Tools > Developer Tools. The window should display the error, as shown below

    18. JavaScript Debugging (3) • In IE, when there is a script error on a page, a message appears on the bottom left corner. Double click on it to see the error.

    19. JavaScript Debugging (4) • Firebug extension for Firefox (http://www.joehewitt.com/software/firebug/)

    20. Language Features

    21. JavaScript vs. C/C++ • Similarities (apply to Java too) • comments /* */ and // • if, for, while, return • operators (arithmetic, relational, etc.) • Differences • In JavaScript • loose typing • no file I/O library • no pointers • built-in string object

    22. Data Types • Numbers • 1, 3.14159, -99 • Logical (Boolean) values • true or false (these two are the literal values that you use to test the truth value of a logical expression) • Strings • “hello”, ‘hello’ • null • special keyword denoting null value

    23. String Literals • A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be delimited by quotes of the same type; that is, either both single quotes or double quotes. The following are examples of string literals: • "Hello" • 'Hello' • "1234" • “one line \n another line” • '"Don\'t try that again!," I yelled.' Escape character for single quote

    24. Variables • You use variables to hold values in your application. • Syntax: varVariablename ; // var => local variable; Otherwise, the variable is global var Variablename = value; • JavaScript is a loosely typed language. myVar = 33; myVar = “Hello World”; myVar = 33 + “Hello World”; // gets “33Hello World” myVar = “Hello World” + 33; // gets “Hello World33 ”

    25. Variable Names • A JavaScript identifier or name must start with a letter or underscore ("_"); subsequent characters can also be digits (0-9). Letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). JavaScript is case-sensitive. • Some examples of legal names are: • Last_Name • status • _name

    26. Operators • Arithmetic + (Addition, String Concatenation) - (Subtraction, Unary Negation) * (Multiplication) / (Division) % (Modulus) (e.g., 7 % 3 gives 1, the remainder of dividing 7 by 3) ++ (Preincrement, Postincrement) // increments a variable by 1 e.g., x = 1; alert(x++); alert (x) // displays 1, then 2 e.g., x = 1; alert(++x); alert (x) // displays 2, then 2 -- (Predecrement, Postdecrement) // decrements a variable by 1 e.g., x = 1; alert(x--); alert (x) // displays 1, then 0 e.g., x = 1; alert(--x); alert (x) // displays 0, then 0

    27. Operators (Cont...) • Assignment Operators = means assignment PI = 3.14159; // var PI is assigned 3.14159 Op= (where op is one of +, -, *, /, etc.) x += y means x = x + y x *= y means x = x * y x -= y means x = x - y x /= y means x = x / y

    28. Operators (Cont...) • Relational Operators ==, != (Equality, Inequality) <, <=, =>, > (Arithmetic and String Comparison) ! (Logical Not) &&, || (Logical AND, Logical OR) ?: (Conditional Selection) e.g., x = (1 < 5) ? ‘a’:’b’; // here, x gets ‘a’ condition Returned if true Returned if false

    29. Operator Precedence • The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses. • The precedence of operators, from lowest to highest is as follows: (Partial Listing) • assignment = += -= *= /= %= • conditional ?: • logical-or || • logical-and && • equality == != • relational < <= > >= • addition/subtraction + - • multiply/divide * / % • negation/increment ! ++ -- • call, member () [] .

    30. Expressions • An expression is any valid set of literals, variables, and operators that evaluates to a single value. PI = 3.14159 12 + 6 2 * PI * r x++ x -= 3

    31. Statements • Comments • Variable Declaration / Assignment • Conditionals • Loops • for loop • while loop • for...in loop • break and continue statements • with statement • Function Definition

    32. Comments • // Single Line • var x // this part of the line is a comment • /* Multiline Comment Line 2..... Line 3 */

    33. Syntax if (condition) { statements } [else { else statements }] Note: else part is not required; [ ] signifies that it is optional Examples <script> var marriedCount = 0; var singleCount = 0; status = prompt("What is your status (0 or 1)?") if (status == 1) { deduction = 500; marriedCount++; } else { deduction = 100; singleCount++; } alert("Your deduction is: " + deduction); </script> Conditionals

    34. Loops – for • Syntax for ([initial expression]; [condition]; [update expression]) { statements } • Example for (var i = 0; i < 10; i++) { document.write(i); } Output: ???

    35. Loops – for-in • Syntax for (varin obj) { statements } • Examples FileName: Winloop.htm <SCRIPT> // The following script shows all of the properties of the window object. for (var i in window) document.write (i + "<BR>"); </SCRIPT> FileName: Winloop2.htm <SCRIPT> // The following script shows all of the properties and their values of the window object. for (var i in window) document.write (i + "=" + window[i]+ "<BR>"); </SCRIPT>

    36. Loops – while • Syntax while (condition) { statements } • Example n = 0; x = 0; while ( n < 3 ) { n ++ ; x = x + n; document.write(n,x); } • Output: • 1 • 3 • 3 6

    37. Functions • Function • A user-defined or built-in set of statements that perform a task. It can also return a value when used with the return statement. • Syntax: function name([param] [, param] [..., param]) { // param’s are optional statements } • Example // Takes 2 values and returns the smaller of the two function findMin (value1, value2) { if (value1 < value2) return (value1); else return (value2); } answer = findMin(50,50); // function call alert("Your answer is: " + answer); Output: ???

    38. Arguments and Parameters FileName: argument.htm <HEAD> <SCRIPT LANGUAGE="JavaScript"> <!-- to hide script contents from old browsers function square(i) { document.write("The call passed “+ i + " to the function.“+"<BR>") return i * i } document.write("The function returned “+square(8)+".") // end hiding contents from old browsers --> </SCRIPT> </HEAD> <BODY> <BR> All done. </BODY>

    39. Arrays • An array is an ordered set of values associated with a single variable name. • Syntax: arrayName = new Array() arrayName = new Array(arrayLength) // no enforcement of length • To access the elements of an array arrayName[elementIndex] • The first element of an array has an index of zero (0)

    40. Arrays (Cont...) • Example: Each of these elements can be accessed by its index, as follows: • myCar[0] = "Ford" • myCar[1] = "Mustang" • myCar[2] = 67 • Note: • Array elements can be heterogeneous (can contain elements of multiple data types)

    41. Arrays (Cont...) • Properties and arrays in JavaScript are intimately related; in fact, they are different interfaces to the same data structure. • Example: • you could set the properties of the myCar object described above as follows: • myCar["make"] = “Benz" • myCar["model"] = “M Class 320" • myCar["year"] = 99 Or • myCar.make = " Benz" • myCar.model = " M Class 320" • myCar.year = 99

    42. Arrays (Cont...) • Example: FileName: Array-with-ForIn.htm // This prints only the defined values of the array <script> for (i in anArray) document.write("anArray at "+i+" = "+anArray[i] +"<BR>"); </script>

    43. Arrays (Cont...) • Other syntax of defining arrays: // TestOtherArraySyntax.htm <script> function compare(a,b) { return a-b; } anArray = new Array("Freshman","Sophomore","Junior","Senior"); anArray2 = ["Computer Science","Mathematics","Accounting","Biology","Political Science"]; anArray3 = [10, 300, 20, 40]; for (i in anArray) document.write("anArray at "+i+" = "+anArray[i] +"<BR>"); document.write("<hr>"); anArray2.sort(); // do sorting of strings for (i in anArray2) document.write("anArray at "+i+" = "+anArray2[i] +"<BR>"); document.write("<hr>"); anArray3.sort(); // does not sort the numbers! for (i in anArray3) document.write("anArray at "+i+" = "+anArray3[i] +"<BR>"); document.write("<hr>"); anArray3.sort(compare); for (i in anArray3) document.write("anArray at "+i+" = "+anArray3[i] +"<BR>"); </script>

    44. Arrays (Cont...) • JavaScript’s Object Model (later on this) consists of many arrays that allow you to manipulate the objects on a web document. • For example, • frames (from window) // window.frames[0]…. • anchors (from document) // document.anchors[0]…. • applets (from document) // document.applets[0]…. • forms (from document) // document.forms[0]…. • images (from document) // document.images[0]…. • layers (from document) // document.layers[0]…. • links (from document) // document.links[0]…. • elements (from form) // document.forms[0].elements[0]…. • options (from select) // document.forms[0]. elements[0].options[0]….

    45. JavaScript Object Model • Object-based (not object-oriented) scripting language • can manipulate instances of JavaScript’s built-in object types • e.g., date, document, location, etc. • objects have properties (i.e., characteristics of objects) • e.g., document.bgColor, ... • objects have methods (i.e., services provided by the objects) • e.g., document.write(“Hello”), ... • Can also create and use your own objects • later on this ...

    46. Objects and Properties • Objects in Navigator exist in a hierarchy that reflects the hierarchical structure of the HTML page itself HTML Page in a Window Corresponding JavaScript Objects window (= the window instance) document (= the page) links (= array with all the links in the page) images (= array with all the images) etc.

    47. document.images[0] document.images[1] document.images[2] document.links[0] document.links[1] document.links[2] document.forms[0].elements[0] document.forms[0].elements[1] document.forms[0].elements[2] document.forms[0].elements[3] document.forms[0].elements[4]

    48. Parent Object Property of parent object an object and a property Child Object Property of child object Property only Objects and Properties (2) • An object's "descendants" are properties of the object • e.g., a form named "form1" is an object, but is also a property of document, and is referred to as "document.form1"

    49. Object Hierarchy (DOM) • Built-in Objects: • String • • Date • • Array • • Boolean • • Math

    50. Objects in a Page • Every page has the following objects: • navigator: has properties for the name and version of the Navigator being used, for the MIME types supported by the client, and for the plug-ins installed on the client. • window: the top-level object; has properties that apply to the entire window. There is also a window object for each "child window" in a frames document. • document: contains properties based on the content of the document, such as title, background color, links, and forms. • location: has properties based on the current URL. • history: contains properties representing URLs the client has previously requested. • Depending on its content, the document may contain other objects. • For instance, each form (defined by a FORM tag) in the document has a corresponding Form object.