Lecture 14 Javascript Announcements Project #2 New website Exam#2 No. Class Date Subject and Handout(s) 17 11/4/10 Examination Review Practice Exam PDF 18 11/9/10 Search, Safety, Security Slides PDF UMass Thursday: Examination #2 Tentative 19 11/10/10 (covers Lec.11-16), location TBD 1
JavaScript Java real name is ECMAScript is reasonably platform-independent a complete, full-featured, complex language most popular scripting language scripting languages are lightweight PL seldom used to write complete programs used to add functionality to HTML pages JavaScript often embedded directly into HTML pages but most scripts should be loaded from an external file is an interpreted language scripts execute without preliminary compilation 2
Using JavaScript in a browser JavaScript code is included within <script> tags: <script type="text/javascript"> document.write("<h1>hello World!</h1>"); </script> This simple code does the same thing as just putting <h1>hello World!</h1> in the same place in the HTML document Using JavaScript in a browser <script type="text/javascript"> document.write("<h1>hello World!</h1>"); </script> type attribute is to allow you to use other scripting languages but JavaScript is the default semicolon at the end of the JavaScript statement is optional need semicolons if you put 2 + statements on the same line always a good idea to use semicolons 3
More examples <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>java Script Example</title> <html> <body> <script type="text/javascript"> document.write("<h1>this is a header</h1>"); </script> </body> </html> JavaScript Comments Comments can be added to explain the JavaScript, or to make it more readable. Single line comments start with //. This example uses single line comments to explain the code: <script type="text/javascript"> // This will write a header: document.write("<h1>this is a header</h1>"); // This will write two paragraphs: document.write("<p>this is a paragraph</p>"); document.write("<p>this is another paragraph</p>"); </script> 4
Handling old browsers Use html comment that JavaScript will interpret as JavaScript comment <html> <body> <script type="text/javascript"> <!-- Rest of line ignored by (x)html interpreter document.write("hello World!"); //--> </script> </body> </html> Some users turn off JavaScript Use the <noscript>message</noscript> to display a message in place of whatever the JavaScript would put there Where to put JavaScript JavaScript functions can (should) be put in a separate.js file Put this in the <head> <script src="myjavascriptfile.js"></script> An external.js file lets you use the same JavaScript on multiple HTML pages The external.js file cannot itself contain a <script> tag 5
Where to put JavaScript JavaScript can be put in the <head> or in the <body> of an HTML document JavaScript functions should be defined in the <head> This ensures that the function is loaded before it is needed JavaScript in the <body> will be executed as the page loads JavaScript can be put in an HTML form object, such as a button This JavaScript will be executed when the form object is used Locating JavaScript Scripts in the head section: <html> <head> <script type="text/javascript">... </script> </head> Scripts in the body section: <html> <head> </head> <body> <script type="text/javascript">... </script> </body> 6
Locating JavaScript Scripts in both the body and the head section: <html> <head> <script type="text/javascript">... </script> </head> <body> <script type="text/javascript">... </script> </body> Using an External JavaScript <html> <head> JavaScripts in the body section will be executed WHILE the page loads. JavaScripts in the head section will be executed when CALLED <script type="text/javascript" src="xxx.js"></script> </head> <body> </body> </html> Note: The external script cannot contain the <script> tag! More examples JavaScript Blocks JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket {, and ends with a right curly bracket }. The purpose of a block is to make the sequence of statements execute together. 7
More examples Example write a header and two paragraphs to a web page: <script type="text/javascript"> { document.write("<h1>this is a header</h1>"); document.write("<p>this is a paragraph</p>"); document.write("<p>this is another paragraph</p>"); } </script> Programming overview What is programming? process of creating a set of instructions for the computer to follow instructions are written in a language or languages which people can understand "compiled" (literally, translated) into machine language interpreted by the computer from reading a script. HTML is a programming language, as are Javascript and VBScript ASP Programming Fundamentals by Kevin Spencer 2005 8
Programming overview What is programming? "syntax" of a programming language consists of the various language elements, conventions, and operators that are used to write the instructions. Procedural vs. Object-Oriented Programming Procedural Prrogramming was first Computer is given a set of instructions which it executes, and then waits for input, which it reacts to by executing another set of instructions, and so on ASP Programming Fundamentals by Kevin Spencer 2005 Procedural Programming 3 basic elements Sequence order in which instructions are executed more important than it might seem having things in the proper sequence is essential. Selection If/else conditional statements and other forms of selection how a program makes and reacts to choices. Iteration use of "loops" and other forms of repetitive sets of instructions ASP Programming Fundamentals by Kevin Spencer 2005 9
Object Oriented Programming Came along with the advent of multi-tasking operating systems such as, PARC Alto, Mac, Windows Procedural programming is at the heart of all programming, including object-oriented programming Objects have properties, methods, and event handlers. ASP Programming Fundamentals by Kevin Spencer 2005 Properties, methods, and events Properties the characteristics define how the object behaves a web page has certain properties, which are defined in the HTML & CSS tags, such as the background color, style source page, etc. Methods blocks of instructions that can be executed by an object each object has its own set of methods. ASP Programming Fundamentals by Kevin Spencer 2005 10
Properties, methods, and events Event Handlers an "event" is when something happens either something that the user has done, or something the program itself has done, or another program has done. event handlers are designed to react to events each object has its own event handlers ASP Programming Fundamentals by Kevin Spencer 2005 Procedure-oriented programming focus on functions and procedures that operate on data large programs divided in smaller units data and functions treated as separate entities top-down design 11
Object-oriented programming emphasis on data code is divided into objects both data and functions integrated properties, data hidden and accessed only by internal methods via interface bottom-up design Document Object Model (DOM) 12
Document Object Model (DOM) An application programming interface (API) for HTML and XML documents defines the logical structure of documents and the way a document is accessed and manipulated programmers can build documents, navigate their structure, and add, modify, or delete elements and content Document Object Model (DOM) Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model, with a few exceptions The DOM originated as a specification to allow JavaScript scripts and Java programs to be portable among Web browsers 13
Variables Provide temporary storage for information that will be needed by program or application Transfer information from one part of the program to another Variable naming rules: upper and lower case letters, underscores, and dollar signs numbers are allowed after the first character no other characters are allowed 14
Variables Variables are declared with a var statement: var pi = 3.1416, x, y, name = "Dr. Dave" ; Variable names are case-sensitive Month, month are different Variables names must begin with a letter or underscore _month, month but not 2months avoid reserved words Reserved words Some words have a special meaning in Javascript Reserved words are the ones that you use to provide the instructions on what the program is to do You cannot use these words as variable or function names. 15
Reserved words examples Other keywords 16
Variables Examples var x; var carname; var x=5; var carname="volvo"; the variables are empty (they have no values yet). can also assign values to the variables when you declare them: The word var is optional, but it s good style to use it these statements: x=5; carname="volvo"; have the same effect as: var x=5; var carname="volvo"; Variables If you redeclare a JavaScript variable, it will not lose its original value. var x=5; var x; it will not lose its original value. Variables are untyped (they can hold values of any type) 17
Example A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value. Example <script type="text/javascript"> var firstname; firstname="hege"; document.write(firstname); document.write("<br />"); firstname="tove"; document.write(firstname); </script> <p> The script above declares a variable,assigns a value to it, displays the value, change the value,and displays the value again. </p> Example <html> <head> <title>javascript Variables</title> <script language="javascript"> var first_name="christian"; // first_name is assigned a value var last_name="dobbins"; // last_name is assigned a value var age = 8; var ssn; // Unassigned variable var job_title=null; </script> </head> Example <body bgcolor="lightblue"> <font="+1"> <script> document.write("<b>name:</b> " + first_name + " " + last_name + "<br>"); document.write("<b>age:</b> " + age + "<br>"); document.write("<b>ssn:</b> " + ssn + "<br>"); document.write("<b>job Title:</b> " + job_title + "<br>"); ssn="xxx-xx-xxxx"; document.write("<b>now Ssn is:</b> " + ssn, "<br>"); </script> <body><p><img src="christian.gif"></body> </html> 18
Passing variables by value (read-only) information can be read by the function, procedure, method, subroutine, etc. but not modified by reference passes a pointer to the variable, rather than the value, and ensures that the variable is read-write, when in scope global variables are in scope for the duration of the programs executionand are read-write for all statements that access them. Types Type system defines how a PL classifies values and expressions into types can manipulate those types and how they interact 19
Types Typed versus untyped languages A language is typed if the specification of every operation defines types of data to which the operation is applicable example, "this text between the quotes" is a string, dividing a number by a string has no meaning in most PL Languages usually allow the possibility to cast (convert) between compatible types Types Weak and strong typing Weak typing allows a value of one type to be treated as another, for example treating a string as a number. JavaScript permits a large number of implicit type conversions 2 * x implicitly converts x to a number, and this conversion succeeds even if x is null, undefined, or a string of letters Strong typing prevents the above perform an operation on the wrong type of value -> an error 20
Javascript Variable Types Primitive Types provided by the system Booleans, numbers and text treated as value types and when you pass them around they go as values some types, such as string, allow method calls User-defined types in addition to the primitive types, users may define their own classes -> objects thus, a complex type is an object, be it either standard or custom made. it goes everywhere by reference Javascript types Primitive Types provided by Javascript: booleans, numbers and text user-defined classes treated by Javascript as value types and when you pass them around they go as values some types, such as string, allow method calls 21
Primative Variable Types Boolean Type can only have 2 possible values, true or false var mayday = false;var birthday = true; 0, "0", empty strings, undefined, null, and NaN are false, other values are true NaN, which stands for Not a Number, is a value or symbol that is usually produced as the result of an operation on invalid input operands Primitive Type Examples Numeric Types both Integer and Float are a numeric significant digits base type exponent var sal = 20;var pal = 12.1; in ECMA Javascript your number literals can go from 0 to - +1.79769e+308. multiplied by ten to the power of =10 308 anything smaller than the smallest infinitesimal (5e-324) is rounded to 0. 22
Primitive Type Examples Numeric Type numbers are always stored as floating-point values Hexadecimal numbers begin with 0x Some platforms treat 0123 as octal, others treat it as decimal Since you can t be sure, avoid octal altogether Primative Variable Types String Types string and char types are all strings, so you can build any string literal that you want var myname = "Some Name";var mychar = 'f'; Strings may be enclosed in single quotes or double quotes Strings can contain \n (newline), \" (double quote), etc 23
JavaScript escape sequences JavaScript escape sequences <html> example <head> </head> <body> <pre> <font size="+2"> <script language="javascript"><!-- Hide script from old browsers. document.write( \t\thello\nworld!\n"); document.writeln( \"Nice day, Mate.\ \n"); document.writeln('smiley face:<font size="+3"> \u263a\n');//end hiding here. --> </script> </pre> </body> </html> 24
Complex Types standard or custom made Array Type untyped, so you can put everything you want in an Array possible to have thousands of items in an array Arrays are objects, they have methods and properties you can invoke at will e.g., the ".length" property indicates how many things are currently in the array var myarray = new Array(0, 2, 4);var myotherarray = new Array(); Complex Types Array Type can also be created with the array notation, which uses square brackets: var myarray = [0, 2, 4];var myotherarray = []; Arrays are accessed using the square brackets: myarray[2] = "Hello";var text = myarray[2]; 25
Complex Types Object Types An object within Javascript is created using the new operator: var myobject = new Object(); Objects can also be created with the object notation, which uses curly braces: var myobject = {}; JavaScript Objects can be built using inheritance and overriding, and you can use polymorphism. There are no scope modifiers, with all properties and methods having public access. Variable scope In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them -- or semantics. 26
Variable scope local variables are those that are in scope within a specific part of the function, procedure, method, or subroutine, global variables are those that are in scope for the duration of program execution; can be accessed by any part of the program, and are read-write for all statements that access them Scope In Javascript Variables declared within a function are local to that function (accessible only within that function) if a variable is initialized inside a function without var, it will have a global scope. Variables declared outside a function are global (accessible from anywhere on the page) A local variable can have the same name as a global variable 27
Example declare a global variable a and assign it a value of 10 call a function in which we again initialize a variable named a var a = 10; disp_a( ); function disp_a( ) { var a = 20; alert("value of 'a' inside the function " + a); } alert("value of 'a' outside the function " + a); Example example var a = 10; disp_a( ); function disp_a( ) { var a = 20; alert("value of 'a' inside the function " + a); } alert("value of 'a' outside the function " + a); since we have used the var keyword inside the function, the variable a will have a local scope once we come out of the function, the local variable no longer exists and the global variable takes over. 28
Type conversion Example from W3C 29