1 / 75

CS 482 Web Programming and Scripting

CS 482 Web Programming and Scripting. Week 3 – JavaScript Basics. Topics . JavaScript Basics Formatting with Tables Formatting with Layers. What is JavaScript?. JavaScript is a light-weight, interpreted programming language or scripting language with object-oriented capabilities.

gil
Télécharger la présentation

CS 482 Web Programming and Scripting

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. CS 482 Web Programming and Scripting Week 3 – JavaScript Basics

  2. Topics • JavaScript Basics • Formatting with Tables • Formatting with Layers

  3. What is JavaScript? • JavaScript is a light-weight, interpreted programming language or scripting language with object-oriented capabilities. • An interpreted language is not compiled. The browser has an interpreter that scans the JavaScript code and interprets it. If it finds syntax errors, it flags them and stops executing the code. • The general-purpose core of the language has been embedded in Netscape and Internet Explorer (IE), and other Web browsers. • JavaScript is cross-platform, simple, easy to comprehend, and powerful.

  4. Why Use JavaScript? • The two main reasons that we use JavaScript in Web pages are: • Dynamics • JavaScript’s dynamic and visual effects include intercepting and processing mouse clicks, opening pop-up windows upon loading and unloading of Web pages, and producing animation. • Client-side execution • Client-side execution includes validating form input and processing client requests that do not require server processing. Other examples include rollover effects, scrollers, and live clocks. • Server-side JavaScript – we are not covering

  5. JavaScript Versus JScript • JavaScript was developed by Netscape and successful because of its simplicity and power. • Microsoft has a clone of JavaScript, called JScript, that is designed to run inside the Internet Explorer browser. • JScript is almost identical to JavaScript; however, in this course, we cover JavaScript. With this knowledge, you will be able to easily pick up JScript.

  6. ECMAScript Standard • JavaScript 1.5 version is fully compliant with the European Computer Manufacturing Association (ECMA) language specification known as ECMA-262 Edition 3 or ECMAScript. • ECMA is the international standards association for information and communications systems (http://www.ecma-international.org). • What can be confusing is the fact that different versions of Netscape and IE support different versions of JavaScript. • For this class, we concentrate on the latest browser versions: Netscape 6/Mozilla Firefox 1.5 and higher, and IE 6 and higher. These both support JavaScript version 1.5.

  7. JavaScript Myth #1 – JavaScript is not Java • JavaScript is not Java! • Other than being similar in syntax, and both providing executable contents in Web browsers, the two languages are entirely unrelated. • The similarity in names was purely a marketing ploy by Netscape. • JavaScript contains a much smaller and simpler command set than does Java. • It is an easier language for most people to learn.

  8. JavaScript Myth #2 – JavaScript is not simple • JavaScript is touted as a scripting language instead of a programming language. This implies that scripting languages are simpler and easier for non-programmers to pick up. JavaScript at first glance appears to be a fairly simple language – on the order of BASIC. • JavaScript does have a number of features designed to make it a more forgiving and easier to use language for new programmers. • Non-programmers can use JavaScript for limited, cookbook-style programming tasks. • Beneath the veneer of simplicity, however, JavaScript is a full-featured programming language. It is as complex as any and more complex than some. Programmers who attempt to use JavaScript for nontrivial tasks often find the process frustrating if they do not have a solid understanding of the language.

  9. JavaScript Resources • Books: • Powell and Schneider (2004),. JavaScript – The Complete Reference, California: McGraw-Hill/Osborne, ISBN: 0-07-225357-6. • Flanagan, David. JavaScript – The Definitive Guide, California: O’Reilley, ISBN: 0-596-0048-0.

  10. What Can JavaScript Do? • Control Document Appearances and Content • JavaScript contains a write() method that allows you to write arbitrary XHTML into a document as the document is being parsed by the browser. • You can also use the Document object (to be covered in Week 4) to generate documents entirely from scratch. • Properties of the Document object allow you to specify colors for the document background, text, and hypertext links within it. • Generates dynamic HTML documents which can allow JavaScript to replace a traditional server-side script. The latest version of the browsers supports the capability of manipulating CSS (the Cascading Style Sheets you learned about last week) style attributes which opens an unlimited world of scripting possibilities.

  11. Interact with HTML Forms • Capability is provided by the Form object • Form element objects it can contain which are: Button, Checkbox, Hidden, Password, Radio, Reset, Select, Submit, Text, and Textarea objects. These element objects allow you to read and write the values of the input elements in the forms in a document. • For example, an online catalog might use an HTML form to allow the user to enter his order and use JavaScript to read the input from that form in order to compute the cost of the order, the sales tax, and shipping charge. • JavaScript has an obvious advantage over server-based scripts because the JavaScript is executed on the client so the form’s contents do not have to be sent to the server for the computation to be made. • Allows validating form data before it is submitted . • If client-side JavaScript is able to perform all necessary error checking of a user’s input , no round trip to the server is required to determine minor user input errors. In some cases, JavaScript can eliminate the need for scripts on the server altogether!

  12. Interact with the User • An important feature of JavaScript is the ability to define event handlers. • Event handlers are arbitrary pieces of code to be executed when a particular event occurs. • You covered the same concept when you did user interface development using Java’s Swing classes in CS 434. • For example, when a user presses a Submit button, a button event is generated. • JavaScript can trigger any kind of action in response to user events.

  13. Read and Write Client State Cookies • A cookie in Web-speak is a small amount of state data stored permanently or temporarily by the client. • Cookies may be transmitted along with a Web page by the server to the client, which stores them locally. Later, when the client requests the same or related Web page, it passes the relevant cookies back to the server, which can use their values to alter the content it sends back to the client. • For example, when a Web page “remembers” your password from a prior visit. The main reason for cookies is to provide the state information that is missing from the stateless HTTP protocol of the Web.

  14. What JavaScript Can’t Do… • The main things that JavaScript cannot do are related to the fact that the script is on the client-side which means that it does not have features that would be required for standalone languages (such as regular Java). • JavaScript does not have any graphics capabilities, except for the ability to dynamically generate HTML (including images, tables, frames, forms, etc.) for the browser to display. • For security reasons, client-side JavaScript does not allow the reading or writing of files. Obviously, you wouldn’t want to allow an untrusted program from any random Web site to run on your computer! • JavaScript does not support networking of any kind, except that it can cause the browser to download arbitrary URLs and it can send the contents of HTML forms across the network to server-side scripts and email addresses.

  15. JavaScript Development Environment • The JavaScript development environment is no different from that of XHTML. • You will still need a HTML editor (Dreamweaver, FrontPage) • Writing JavaScript does generate syntax errors. • If you recall when you made an error in XHTML, the Web page did not display correctly. • In JavaScript, an error results in a blockage of the rendering of the Web page content. • This can leave you wondering what happened and without a debugger, it can be time consuming to find errors. • Do not need a full-fledge debugger because the JavaScript interpreter does a good job in reporting syntax errors.

  16. Debuggers • Netscape/Mozilla has a built-in JavaScript debugger (JavaScript Console) • IE does not • In fact, IE does not recognize the javascript: protocol • Don’t forget to test the script in IE!

  17. Can also use: <script language=“javascript”>

  18. When you press the OK button, the following text appears in the browser – caused by the document.write() method:

  19. Where Does JavaScript Go? • You can embed JavaScript code in three places: • In the top section of the page between the <head> and </head> tags; • In the middle section of the page between the <body> and </body> tags; • In a separate file. • JavaScript code is placed on the between a pair of container tags that look like: <script type = ”text/javascript”> <!-- …script goes here… //--> </script> • The opening tag, <script type=”text/javascript”>, tells the browser: • It has encountered a script; • It is in text format; and • It is to be interpreted as JavaScript.

  20. JavaScript continued... • <!–and//--> • Used to enclose the script code in an XHTML document so older browsers that do not support scripting do not try and display as part of the Web page. • The actual script code starts on the third line. • Use <noscript>...</noscript> for informing users that the browser does not support JavaScript • If the script is to be placed in an external file, the opening and closing tags are not included – just the script itself. • The file should have an extension of “.js”. The (X)HTML page would then contain a link to the JavaScript file like this: <script type=”text/javascript” src=”/javascript/scriptfile.js”></script>

  21. Some Basics… • JavaScript is a case-sensitive language. • This means that language keywords, variables, method names, and any other identifiers must always be typed with consistent capitalization of letters. • JavaScript ignores spaces, tabs, and newlines that appear between tokens in programs, except those that are a part of a string or regular expression literals. • You are free to format and indent your programs for neat and consistent coding style. • Simple statements in JavaScript are generally followed by semicolons (;) (as inC++ and Java) • The semicolon serves to separate the statements from each other. However, you may omit the semicolon if each of your statements is placed on a separate line. This is frowned upon and is not good programming practice. • You should end all your statements in this class with a semicolon.

  22. Some Basics… • JavaScript supports two types of comments (like C++ and Java) : • // and /* */ • In the first case, any text following the // and the end of the line is treated as a comment. • In the latter, any text between the characters / and */ is also treated as a comment.

  23. JavaScript Variables • A variable is a symbolic name that can store a value. • myVar = 5 assigns the value of 5 to the variable myVar • Identifiers • JavaScript identifiers must conform to certain rules (like C++ and Java): an identifier must begin with a letter (upper or lower-case), an underscore (_), or dollar sign ($). • It must not begin with a number. • Subsequent characters can be digits. • Examples of valid identifiers: • test, Test123, my_test, $abc, and a_$1234. • It is recommended because JavaScript is an object-oriented language to use camel hump notation. Camel hump notation is where the first word is in lowercase and the first character of the remaining words are capitalized. • For example, myFirstVariableName.

  24. JavaScript Variables - Types • JavaScript is a dynamically typed language which means that you do not have to declare variable data types explicitly. • Data types are converted automatically during script execution. • The first use of the variable defines the data type. • JavaScript recognizes data types of number, logical (Boolean), and string. • JavaScript numbers can be integers (3,10) or floating point numbers (3.10). • Unlike Java, JavaScript does not differentiate between integer or long and float or double data types.

  25. JavaScript Variables – Logical & String Types • Logical data types are used to represent true and false Boolean values. • They are typically used to check logical expressions or control statements. • if (flag != true) tests for the variable flag not equal to Boolean1. • Strings are sets of characters enclosed in a single or double quotes. • “John Doe” is a string. • Strings are one or more characters. • XHTML elements can also be used inside of strings. Doing so will help you to create more dynamic pages. • document.write(“This is <strong>really</strong> fantastic!”);

  26. Var Keyword • JavaScript keyword var used to declare a variable but not assign a value to it. • var myVar does not assign a type or value to a variable but simply flags it as a variable that will be assigned a value at a later time. • This is a technique that is used to group variables at the top of a program together for easy readability.

  27. Using JavaScript Variables:

  28. Scope • The scope of a variable is defined as the code block within which the variable is visible, or, in other words, available for use. • JavaScript variables can be global or local. • A global variable is available everywhere within the <script> tag. • A variable that is declared without var is a global variable. • A local variable is visible only inside a code block such as a function (method).

  29. Constants • Constants are read-only variables and are defined with the const keyword. • const x = 35, means that x is assigned the value 35 and it cannot be changed. • JavaScript ignores any reassignment of a constant in a script and reassignment does not cause an error. • All variable and scope rules apply to constants. • Note, only Netscape (Firefox) recognizes the const keyword. IE produces errors and does not render the Web page.

  30. Literals • Literals are fixed values in JavaScript (not variables) • Known as hard-coded values. • Examples are number (3.5) , Boolean (false) and string literals (“Hello”). • Nesting string literals requires extra care to avoid creating syntax errors when we run a script. • Must toggle the types of quotations we use – from double to single quotes or vice versa. str = “Our facilitator said, ‘We must study for the exam’ last week”;

  31. Data-Type Conversion • JavaScript converts data types automatically as needed during script execution. • This is because JavaScript is dynamically typed. • Can write answer = true and then change it to answer = 35 • converts the variable answer from Boolean to number. • Practically, however, we should not do this so as to avoid confusion and increase program maintainability.

  32. Escaping Characters • JavaScript uses the backslash (\) as an escaping character. • An escaping character is an instruction to the JavaScript interpreter to ignore what follows the character, and not to execute it according to the JavaScript syntax rules. • Can insert a quotation mark inside a string by preceding the quotation mark by a backslash. str = “Our facilitator said \”We must study for the exam\” last week”;

  33. The Alert, Confirm, and Prompt Windows • Browsers often use three small windows to send information to or request information from the user. • The JavaScript window object contains three methods (alert, confirm, prompt) that create these tiny pop-up windows.

  34. The Alert Window

  35. Alert Output:

  36. The Confirm Window

  37. Confirm Output:

  38. The Prompt Window

  39. Prompt Output:

  40. Parsing Numbers • For integers (whole numbers), we use the parseInt() method. • This method requires a string parameter and it returns the integer equivalent. • For example, the following statement asks the user to enter the total questions, parsing this to an integer, and places the result in the variable total. • var total = parseInt (prompt (“Total questions: “, “”)); • For floating-point numbers, we use the parseFloat() method. • For example, if a facilitator assigns partial credit for answers, we could use this method to obtain the answer: • var correct = parseFloat (prompt(“Correct answers: “, “”));

  41. JavaScript Statements • A statement is a line of JavaScript code that uses the assignment operator, the equal sign (=). • The assignment operator has two operands, one on each side. The value of the right operand is assigned to the left one. • JavaScript does not allow a statement to be broken into two lines. • Each statement must be one line long, not matter how long it is. • Breaking a statement by entering a carriage return <Enter> results in a syntax error. • A statement may end with a semicolon(;). • The purpose of whitespace in statements has no effect on the statement’s results. • We use it for the purpose of code readability. The only time that whitespace matters is when we use it in literal strings.

  42. JavaScript Expressions and Operators • An expression is any valid set of variables, literals, operators, and other expressions that evaluates to a single value. • That value could be a number, Boolean, or a string.

  43. The Rules of Precedence: • Rule 1: Operators are evaluated in the order of their precedence; higher-order operators are evaluated before lower order operators. • Rule 2: Operators of the same precedence are evaluated according to their associatively. Left-associative operators (addition, subtraction, multiplication, division, and modulus) evaluate from left to right. Right-associative operators (assignment) evaluate operators from right to left. • Rule 3: Parentheses are used to override precedence. • Rule 4: Parenthesized expressions are evaluated from the innermost to the outermost set of parenthesis. • Bottom line: USE PARENTHESIS FOR CLARITY AND MAINTAINABILITY!!

  44. Assignment Operators • The equal sign (=) is the main assignment operator. • Other assignment operators are shorthand for certain operators. • x = x + y or use x += y (the shorthand version). Here, we add y = x and store the result back in x. • Other shorthand operators include x -= y (x = x – y), x *= y (x = x * y), and x /= y (x = x/y).

  45. Comparison Operators:

  46. Arithmetic Operators:

  47. Logical Operators

More Related