480 likes | 586 Vues
John Hurley Department of Computer Science California State University, Los Angeles. Introduction to Web Site Development. Lecture 7: JavaScript I. Difficulty of This Unit.
E N D
John Hurley Department of Computer Science California State University, Los Angeles Introduction to Web Site Development Lecture 7: JavaScript I
Difficulty of This Unit • Some of you are CS majors taking this class to learn skills necessary for your major, others just want to learn how to make basic web pages • Some have taken programming classes, some haven’t • Those who have programming backgrounds will find the next two weeks much easier than those who don’t, but • Someone with no prior programming experience should be able to get an A if s/he works hard • If you are a programmer and find the material too easy, feel free to go beyond the assigned work. I’ve read a couple of books on JS and can’t recommend any of them, but references are easily available on the web.
JavaScript • Our work so far has involved pre-written content • More sophisticated sites generate content interactively based on information from the client • This can be done with either client-side or server-side programming • You will learn about server-side programming in CS320 • To the extent that processing can be done on client computers, web site owners save expense • The industry has experienced challenges in taking advantage of this possibility
JavaScript • Programming language that executes while you are browsing • Sent to the browser as code and interpreted by browser add-on • JavaScript is the dominant client-side scripting language of the world wide web • IE supports VBScript, other browsers don’t • So JavaScript is the only alternative
JavaScript • Generally used for simple functionality to enhance web pages, yet it is a real Turing-complete programming language • A Google search will easily turn up some small to medium-sized apps. Here are some fun ones: • Space Invaders: http://matthaynes.net/playground/javascript/glow/spaceinvaders/ • emulator for the old Applesoft II BASIC interpreter: http://www.calormen.com/Applesoft/ • Some colleges, especially community colleges, teach entire courses on Javascript • Santa Monica College has an online JS class at least once a year.
Scripting Languages • Term is used oddly • Originally applied to languages used for scheduling jobs on mainframes under batch processing (that is, jobs that required no runtime input and were queued up to run) • Then applied to languages used to simulate use of a GUI or actions of some agent (like a nonplayer character in a video game) • But JS code often takes live user input at runtime • In web development, used to mean roughly “interpreted languages used in web programming”
JavaScript • JavaScript is a misnomer • Syntax similarities to Java are due to common legacy of Algol/C family languages and superficial adoptions from Java • Java was the hot new thing when JS came out, and Sun was one of the early endorsers of JS. The name was pasted on although the internal working of JS are radically different from those of Java
It’s Not All JavaScript’s Fault! • Many developers consider JavaScript to be suboptimal in some ways • Javascript sometimes gets a worse rap than it deserves • Much of the difficulty programmers experience with client side scripting is not caused by JS
It’s Not All JavaScript’s Fault! • JavaScript is different from the languages most of us usually work with, and thus sometimes seems weird. • A language that stood on ceremony about OOP, as Java does, would be overkill for the typical use situations of JavaScript • There are severe environmental constraints on client-side programs • browser security measures required to support anonymously-sourced programs from the internet • cross-browser incompatibilities aggravated by standards-busting and by competition between MS and the other original endorsers (Netscape and Sun)
It’s Not All JavaScript’s Fault! • Most aggravating of all: you always need a fallback in case JS doesn’t work • Users in high-security organizations like banks are not allowed to enable Javascript in their browsers • Those who are just security conscious or who have been burned by security bugs may turn off Javascript support • Future browsers may not be backward compatible with the JS you write now, or users may use a browser that can’t run your JS • <noscript>Your browser does not support JavaScript. You may not be able to use all the functionality of this page!</noscript> • This is caused by the nature of the internet and of business competition, not by the design of JavaScript
JavaScript • History • 1995 – Invented by Netscape (now Mozilla) • Became a standard called ECMAScript-262 • JavaScript is now a dialect of ECMAScript-262 • Current version: JavaScript 1.8.1 • Support • Firefox 3.5: JavaScript 1.8.1 Supported • Internet Explorer 8: JScript 5.8 • JScript is Microsoft’s dialect of the ECMA-262 standard. They cannot use JavaScript because JavaScript is trademarked by Sun Microsystems.
Internal JavaScript • JavaScript can be written inside an HTML file using the script element • Start and end tags are required • Example: • <head><script type="text/javascript"> // your JavaScript code goes here</script></head>
Notes About Internal JavaScript • The SCRIPT element can go inside the HEAD • Script is run before BODY is loaded • The SCRIPT element can go inside the BODY • Script is run as BODY is being loaded
External Scripts • Include a script that is saved in a separate file, much like using an external CSS • Place a link in the head section: <script type = “text/JavaScript” src = “scripts/myscript.js” />
Statements • A computer program executes statements • A statement is the smallest unit of execution in a computer program • A statement should always be terminated by a semicolon in JavaScript • There are many types of statements • assignment • return • if… else… • Plus many more!!! • Unless we go out of our way to set things up differently, statements will execute in the order in which they appear.
The Window Object • Every browser has a window object that you can access through your JavaScript • There are five important functions that we need to know about window: • window.alert(message); • window.open(URL); • window.showModalDialog(URL); • window.prompt(message, defaultValue); • window.confirm(message);
The Window Object • Notice that: • The object name, window, comes first • Next is the period, which is called the member access operator • Next is the name of the function • Next is the left parenthesis • Next is zero or more comma-separated arguments • Next is the right parenthesis • And finally, there is the semicolon
The Window Object Example • Example: <script type="text/javascript"> window.alert("Free Beer!"); window.prompt("How many people want free beer?", 26); window.confirm("Are you sure you want free beer?"); window.open("http://www.yahoo.com"); window.showModalDialog("http://www.yahoo.com/"); </script>
Alerts • window.alert displays a simple dialog box • window.alert(message); • window.alert(x); • message is a JavaScript string that you would like to have shown in an alert box
Prompts • window.prompt displays a simple dialog box with a text input box, that allows the user to enter text • This function is used for user input. • var value = window.prompt(message, default-value); • message is a JavaScript string that you would like to have shown in an prompt box • default-value is a JavaScript string that you would like to have shown in the input box • value is the JavaScript string that was in the input box when the user closed the prompt dialog box by pressing OK; if the user pressed CANCEL, the keyword null is returned.
Confirmation • window.confirm displays a simple dialog box with a message and two button, OK and CANCEL • This function is used for user input. • var value = window.confirm(message); • message is a JavaScript string that you would like to have shown in the confirm box • value is the JavaScript boolean value that is true if the user pressed the OK button, and false if the user pressed the CANCEL button
Popup Windows • window.open displays a popup window • Most users now have multiple popup blockers, so you may want to avoid this • Note: Whether a popup window opens in a tab or a new window is up to the browser. • window.open(URL); • URL is a JavaScript string that represents the URL that you would like to open up in a popup window
Modal Dialogs • window.showModalDialog opens up a modal dialog • A modal dialog is a popup window that prevents you from going back to the parent document; you must answer a modal dialog before proceeding • window.showModalDialog(URL); • URL is a JavaScript string that represents the URL that you would like to open up in a popup window • showModalDialog is often used by obnoxious marketers this way: window.showModalDialog("http://www.vicodin4pain.com"); • That’s downright rude!
JavaScript Data Types • There are three basic data types that we need to understand form the outset: numbers, strings, and Booleans • Numbers • 1, 2, 3, 1.0, 2.0, 3.0, -1.0, -2.0 • Interpreter will distinguish correctly between integers and floating point numbers • Strings • "This is a string of characters." • Boolean • true, false
JavaScript Variables • In an HTML page, sometimes we need to maintain the state of something • To do this we can using a named variable • The name can be any alpha-numeric character that does not start with a number • To declare a variable, use the var keyword • The syntax is: • var variable-name = initial-value;
Assignment Statements • Assignments give a value to a variable • Each one of the four statements below is an assignment statement var myCarValue = 1000;myCarValue = 2000;var total; total = 10 + 14 – 3; x = 10
Variables Example • Example: • <script type="text/javascript">var x = 3;var y = 1.0;var str = "This is a string.";var b1 = true;var b2 = false;</script>
Expressions • An expression is sequence of numbers, variable names, values, function calls, and operators that computes a single value • 3 + 4, is an expression that computes 7 • ((7 – 2)*4), is an expression that computes 20 • There are many different types of expressions • Mathematical • Boolean • Logical
Mathematical Expressions • Addition: x + y • Subtraction: x – y • Multiplication: x * y • Division: x / y • Remainder (Modulus): x % y
Boolean Expressions • A Boolean expression is an expression that evaluates to either true or false • Less Than: x < y • Greater Than: x > y • Less Than or Equal: x <= y • Greater Than or Equal: x >= y • Equal: x == y • Not Equal: x != y
Modulo Those who do the hard version of the lab will need to use modulo % finds the remainder in an integer division problem: 1 % 1 is 0 5 % 1 is 0 5 % 5 is 0 5 % 4 is 1 5 % 2 is 1 6 % 2 is 0 9 % 2 is 1
Modulo • Modulo is incredibly useful in programming! • Of its many uses, the easiest to understand is that it can be used to find out whether one integer is evenly divisible by another: • The expression 10 % 5 == 0 is true, so we know that 10 is evenly divisible by 5 • The expression 9 % 2 == 0 is false, so we know that 9 is *not* evenly divisible by 2
if… else… Statements • We use the if… else… statement in conjunction with Boolean and logical expressions to execute branches of statements • The syntax is: • if(boolean-or-logical-expression) single-statement;else single-statement; • Example: • if(x < 10) y = 3;else y = 4;
if… else… Statements • If multiple statements are needed, use curly brackets to label a block (a set of statements). • The syntax is: • if(boolean-or-logical-expression) { statement1; statement2; statement3; }else { statement1; statement2; statement3; }
Document Functions • document.write(str) • A function that allows you append HTML code to your document while it is being loaded • If the output contains html tags, the browser will render the output using them. • CSS styles apply to markup generated this way
Quotes Nested In Output • You sometimes (for example, in lab 7) need to nest quotes inside string quotes in document.write or other JavaScript statements • Choice a: more intuitive but less rigorous • use single quotes for literal quotes (that is, ones you want to render as quotes) • document.write("<div class = 'main'>"); • Choice b: weirder but more logical • escape with backslash • document.write("<div class = \"main\">"); • document.write("She said \"They tried to make me go to rehab, but I said \"no, no,no\"\"");
Linefeed with document.write • To skip to a new line with document.write, just print the line break element: • document.write(“<br />”); • \n will NOT work!
Logical Expressions • A logical expression computes a value based on a truth table • Logical OR: x || y • If x is true or y is true, then the result is true; otherwise false • Logical AND: x && y • If both x and y are true, then the result is true; otherwise false • Logical NOT: !x • If x is true, result is false; otherwise true
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> </head> <body> <script type="text/javascript"> var a = true; var b = false; window.alert("a: " + a); window.alert("not a: " +!a); window.alert("b: " +b); window.alert("not b: " +!b); window.alert("a and b: " + (a&&b)); window.alert("not (a and b): " + !(a&&b)); window.alert("a or b: " + a||b); window.alert("not (a or b): " + !(a||b)); window.alert("a and not b: " +(a && !b)); window.alert("b and not a: " +(!a && b)); window.alert("a and a: " +(a && a)); window.alert("a and not a: " +(a && !a)); window.alert("b or not b: " +(b || !b)); </script> </body> </html>
Loops • Loops are used in programming to repeat actions • Loop breaks when some condition is met, for example when x == 100 or cancelled == true • Here is the simplest kind of loop in JavaScript: var counter = 0; while (counter < 100) { document.write(counter + “<br />”); counter++; // increment counter by 1 } document.write(“done”);
Preview of Loops Programmers, note that loops may be nested, just as in other programming languages var x = 0; var y = 0; while(x < 10){ y = 0; while (y <10){ document.write("x = " + x + "; y = " + y +"<br />"); y++; } document.write(“<br />"); x++; }
Preview of Loops For Loop: for(var counter = 0; counter < 5; counter++) { window.alert(counter + "!"); } The first line declares and initializes a variable, defines the test, and sets the variable to increase by 1 at the *end* of each execution of the loop. The initialization only occurs in the first iteration of the loop.
Preview of Loops <script> for (var counter = 0; counter < 100; counter++) { document.write("Always watch out for Godzilla: " + counter + "<br />"); } </script>
Preview of Loops Do…while Loops • Test is at the *end* of the loop, so the loop always runs at least once • One use is for input validation
Preview of Loops <script type = "text/javascript"> var choice; do{ choice = window.prompt("Who would win? Enter G for Godzilla or B for Bruce Lee"); choice = choice.toUpperCase(); } while (choice != 'G' && choice != 'B'); var winner; if(choice == 'G') winner = "Godzilla"; else if(choice == "B") winner = "Bruce Lee"; document.write("user thinks " + winner + " would win"); </script>
Preview of Loops If the browser freezes while you are testing a script with a loop: • Stop loading if possible • otherwise, close the browser • check to make sure the loop increments correctly and that the condition for breaking the loop is eventually met
View Source and JS View Source will *not* show you the output from execution of JavaScript, even with document.write, which is executed at load time.