Java Script
Java Script
Lecture #
JavaScript I
CSE 130
Lecture #
Materials
The information here is dominantly derived from JavaScript: The Complete Reference 2nd edition which is a class recommended text There are plenty of other good resources online about JavaScript, but there is also quite poor discussions about it youve been warned Tools
Browsers (Firefox, IE, Opera, Safari, etc.) Debugging and DOM focused toolbars (Web Developer Toolbar, Firebug, etc.) Text editor that is JS aware Aptana, Dreamweaver, Eclipse, etc.
CSE 130
Lecture #
Part of the client-side triangle consisting of (X)HTML, CSS and of course JavaScript
Manipulation of mark-up and style via the document object model or DOM
CSE 130
Lecture #
Helloworld
<!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"> <head> <title>JavaScript Hello World</title> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> </head> <body> <h1>First JavaScript</h1> <hr /> <script type="text/javascript"> document.write("Hello World from JavaScript!"); </script> </body> </html>
CSE 130
Lecture #
or even
<strong> <script type="text/javascript"> document.write("Hello World from JavaScript! "); </script> </strong>
CSE 130
Lecture #
CSE 130
Lecture #
Adding JavaScript to HTML Documents There are four standard ways to include script in an (X)HTML document:
1.Within the <script> element 2.As a linked file via the src attribute of the <script> element 3.Within an (X)HTML event handler attribute such as onclick 4.Via the pseudo-URL javascript: syntax referenced by a link
Note: There may be other approaches but they are non-standard
CSE 130
Lecture #
<script> Tag The <script> tag (<script> </script>) in all major browsers interprets contents as JavaScript unless one of the following occurs:
Inclusion of language attribute <script language=VBS> </script> Inclusion of type attribute <script type=text/javascript> </script> The type attribute is W3C recommended, language more common and in many ways more useful Note: A <meta> tag can also be used to set the script language document wide or even by a Web server.
<meta http-equiv=Content-Script-Type content=text/javascript />
CSE 130
Lecture #
Top-to-Bottom Execution
You can use as many <script> tags as you like in both the <head> and <body> and they are executed sequentially.
<h1>Ready start</h1> <script language="Javascript" type="text/javascript"> alert("First Script Ran"); </script> <h2>Running</h2> <script language="Javascript" type="text/javascript"> alert("Second Script Ran"); </script> <h2>Keep running</h2> <script language="Javascript" type="text/javascript"> alert("Third Script Ran"); </script> </h1>Stop!</h1>
Fun threading issue since you are running a JavaScript interpreter within a browser it is possible to see different amounts of text before/after alerts. This is more pronounced with long running scripts or network activity.
CSE 130
Lecture #
Script in <head>
<!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"> <head> <title>JavaScript in the Head</title> <meta http-equiv="content-type" content="text/html;charset=ISO-8859-1" /> <script type="text/javascript"> function alertTest() { alert("Danger! Danger! JavaScript Ahead"); } </script> </head> <body> <h2>Script in the Head</h2> <hr /> <script type="text/javascript"> alertTest(); </script> </body> </html>
CSE 130
Lecture #
<noscript> Element
Useful to provide alternative rendering in browsers that have script off or dont support script <noscript> <strong>Either your browser does not support JavaScript or it is currently disabled.</strong> </noscript> Next example shows a great way to keep non-JavaScript aware users out of your site
CSE 130
Lecture #
<noscript> Example
<!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"> <head> <title>JavaScript Masked</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
</head> <body> <script type="text/javascript"> <!-document.write("Congratulations! If you see this you have JavaScript."); //--> </script> <noscript> <h1 class="errorMsg">JavaScript required</h1> <p>Read how to <a href="/errors/noscript.html">rectify this problem</a></p> </noscript> </body> </html>
CSE 130
Lecture #
Meta-Refresh Trick Add a <meta> refresh within a <noscript> in the head to redirect non-JS users right-away to an error page
<noscript> <meta http-equiv="Refresh" content="0;URL=/errors/noscript.html"> </noscript>
Downsides
Wont validate W3C oversight? Redirects turned off at certain security settings with JS Not bot friendly
CSE 130
Lecture #
CSE 130
Lecture #
Event Handlers
(X)HTML defines a set of event handler attributes related to JavaScript events such as onclick, onmouseover, etc. which you can bind JavaScript statements to.
<!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"> <head> <title>JavaScript Events</title> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> </head> <body onload="alert('page loaded');"> <form action="#" method="get"> <div id="formfields"> <input type="button" value="press me" onclick="alert('You pressed my button!');" /> </div> </form> <p><a href="http://www.yahoo.com" onmouseover="alert('hi');">Yahoo!</a></p> </body> </html>
CSE 130
Lecture #
Linked Scripts
Like linked style sheets you can store JavaScript code in a separate file and reference it
Use a .js file Contains only JavaScript Store these files like images in a common directory in your site (e.g. /scripts) Linked scripts can be cached and clean up (X)HTML documents Linked scripts do have problems under some browsers
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
JavaScript Pseudo-URLs
You can use the JavaScript pseudo-URL to trigger a script statements For example <a href=javascript: alert(hi);>Click me</a> You can also type such a URL directly in the browsers location box, for example javascript:alert(5+9) Be aware that JavaScript pseudo-URLs do not degrade well in non-JavaScript aware situations
CSE 130
Lecture #
You shouldnt use this form of inclusion since it is no longer supported by even Netscape and is not cross browser in support
CSE 130
Lecture #
History of JavaScript
JavaScript first introduced in 1995
Invented by Netscape Originally called LiveScript Renamed JavaScript when first beta in Netscape 2 Not really related to Java
Standards oriented JavaScript called ECMAScript The ideas of DHTML and Ajax add even more confusion JavaScript used both client and server-side and within browsers and outside browsers Some of the bad aspects of JavaScript are really the bad aspects of the environment in which it is used
CSE 130
Lecture #
JavaScript Versions
Browser Version
Netscape 2.x Netscape 3.x Netscape 4.0 4.05 Netscape 4.06 4.7x Netscape 6.x, Mozilla 0.9 Firefox 1.5 Firefox 2.0 Internet Explorer 3.x Internet Explorer 4.x Internet Explorer 5.x Internet Explorer 5.5 Internet Explorer 6.x Internet Explorer 7.x 1.0 1.1 1.2 1.3 1.5 1.6 1.7 JScript 1.0 JScript 3.0 JScript 5.0 JScript 5.5 JScript 5.6 Jscript 5.6 + Native XHR (or 5.7 under Vista)
JavaScript Version
CSE 130
Lecture #
JavaScript Applications
Common uses of JavaScript include:
Form validation Page embellishments and special effects Navigation systems Basic Math calculations Dynamic content manipulation
The last use gets into the real power of JavaScript being a full fledged document manipulation language
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
CSE 130
Lecture #
Basic Features
Script Execution order
Top to bottom <head> before <body> Cant forward reference outside a <script> tag
10
CSE 130
Lecture #
Return character can cause havoc Given white space support by JavaScript some developers favor crunching
CSE 130
Lecture #
CSE 130
Lecture #
Blocks
To group together statements we can create a block using curly braces { }. In some sense this creates one large statement Blocks are used with functions as well as larger decision structures like if statements
function add(x,y) { var result = x+y; return result; } if (x > 10) { x= 0; y = 10; }
11
CSE 130
Lecture #
Variables
Variables store data in a program The name of a variable should be unique well formed identifier starting with a letter and followed by letters or digits Variable names should not contain special characters or white space Variable names should be well considered
X versus sum Some rules of programming might not follow on the Web?
CSE 130
Lecture #
Variables Contd.
Define a variable using the var statement
var x;
If undefined a variable will be defined on its first use Variables can be assigned at declaration time
var x = 5;
CSE 130
Lecture #
12
CSE 130
Lecture #
Weak Typing
JavaScript is a weakly type language meaning that the contents of a variable can change from one type to another.
Some languages are more strongly type in that you must declare the type of a variable and stick with it.
Example of dynamic & weak typing a variable initially holding a string can later hold a number x = "hello"; x = 5; x = false; While weak typing seems beneficial to a programmer it can lead to problems
CSE 130
Lecture #
Type Conversion
Consider the following example of weak typing in action
document.write(4*3); document.write("<br>"); document.write("5" + 5); document.write("<br>"); document.write("5" - 3); document.write("<br>"); document.write(5 * "5");
You may run into significant problems with type conversion between numbers and strings use functions like parseFloat() to deal with these problems
Prompt demo
CSE 130
Lecture #
Be aware that using operators like equality or even + may not produce expected results
x=5; y = "5"; alert(x == y) Produces a rather interesting result. We see the inclusion of a type equality operator (===) to deal with this
13
CSE 130
Lecture #
Composite Types
JavaScript supports more advanced types made up of a collection of basic types. Arrays
An ordered set of values grouped together with a single identifier
Defining arrays
var var var var myArray = [1,5,1968,3]; myArray2 = ["Thomas", true, 3, -47]; myArray3 = new Array(); myArray4 = new Array(10)
CSE 130
Lecture #
Arrays
Access arrays by index value
var myArray = new Array(4) myArray[3] = "Hello";
Arrays in JavaScript are 0 based given var myArray2 = ["Thomas", true, 3, -47];
myArray2[0] is Thomas, myArray[1] is true and so on Given new Array(4) you have an array with an index running from 03 To access an array length you can use arrayName.length
alert(myArray2.length);
CSE 130
Lecture #
Objects
An object is a collection of data types as well as functions in one package
var stooge1 = { names : [Larry,Curly,Moe] , number : 3} var stooge2 = { names : [Larry,Curly,Moe] , showNumber : function() {alert(this.names.length);} } alert(stooge1.names); stooge2.showNumber();
14
CSE 130
Lecture #
Given the need to use objects so often shortcuts are employed such as the with statement
We also see the use of the short cut identifier this when objects reference themselves
CSE 130
Lecture #
Increment decrement
++ (add one) -- (subtract one)
Comparison
>, <, >=, <= , != (inequality), == (equality), === (type equality)
Logical
&& (and) || (or) ! (not)
CSE 130
Lecture #
More Operators
Bitwise operators (&, |, ^)
Not commonly used in JavaScript except maybe cookies? Shift operators (>> right shift, << left shift)
String Operator
+ serves both as addition and string concatenation document.write("JavaScript" + " is " + " great! "); You should get familiar with this use of +
15
CSE 130
Lecture #
Flow Control
Basic program execution control handled in JavaScript using the if statement
if (expression) true-case or if (expression) true-case; else false-case;
if (x > 10) alert("x bigger than 10"); else alert("x smaller than 10");
CSE 130
Lecture #
More on If Statements
You can use { } with if statements to execute program blocks rather than single statements
if (x > 10) { alert("X is bigger than 10"); alert("Yes it really is bigger"); }
");
CSE 130
Lecture #
Switch Statements
If statements can get messy so you might consider using a switch statement instead switch (condition) { case (value) : statement(s) break; default: statement(s); } The switch statement is not supported by very old JavaScript aware browsers (pre-JavaScript 1.2), but today this is not such an important issue
16
CSE 130
Lecture #
Switch Example
var x=3; switch (x) { case 1: alert('x is 1'); break; case 2: alert('x is 2'); break; case 3: alert('x is 3'); break; case 4: alert('x is 4'); break; default: alert('x is not 1, 2, 3 or 4'); }
CSE 130
Lecture #
Loops
JavaScript supports three types of loops: while, do/while, and for Syntax of while: while(condition) statement(s) Example:
var x=0; while (x < 10) { document.write(x); document.write("<br />"); x = x + 1; } document.write("Done");
CSE 130
Lecture #
Do Loop
The difference between loops is often when the loop condition check is made, for example
var x=0; do { document.write(x); x = x + 1; } while (x < 10);
In the case of do loops the loop always executes at least once since the check happens at the end of the loop
17
CSE 130
Lecture #
For Loop
The most compact loop format is the for loop which initializes, checks, and increments/decrements all in a single statement
for (x=0; x < 10; x++) { document.write(x); }
With all loops we need to exercise some care to avoid infinite loops. See example
CSE 130
Lecture #
For/In Loop
One special form of the for loop is useful with looking at the properties of an object. This is the for/in loop. for (var aProp in window) { document.write(aProp) document.write("<br />"); } We will find this construct useful later on when looking at what we can do with a particular object we are using
CSE 130
Lecture #
Loop Control
We can control the execution of loops with two statements: break and continue break jumps out of a loop (one level of braces) continue returns to the loop increment
var x=0; while (x < 10) { x = x + 1; if (x == 3) continue; document.write("x = "+x); if (x == 5) break;
} document.write("Loop done");
18
CSE 130
Lecture #
Functions
Functions are useful to segment code and create a set of statements that will be used over and over again The basic syntax is function name(parameter list) { function statement(s) return; } For example
function add(x, y) { var sum = x + y; return sum; }
CSE 130
Lecture #
Functions Contd.
We can then invoke a function using the function name with ( )s var result = add(2, 3); We can also pass variable values as well as literals var a = 3, b=5; var result; result = add(a,b); Variables are passed to function by value so you must use return to send things back. You can return a value or not from a function and you can have as many return statements as you like
CSE 130
Lecture #
Input/Output in JavaScript
Special dialog forms
Alert
alert("Hey there JavaScript coder! ");
Confirm
if (confirm(Do you like cheese?) alert("Cheese lover"); else alert("Cheese hater");
Prompts
var theirname = prompt("Whats your name? ", "");
19
CSE 130
Lecture #
CSE 130
Lecture #
You also may want to format your script for nice reading or you may want to crunch it for fast download?
CSE 130
Lecture #
Summary
JavaScript supports a basic syntax very similar to C It is a weakly typed language It has a limited set of data types It is very object flavored but it does not force objectoriented programming on programmers It forgoes many features of programming languages that wouldnt make sense in the Web environment (file I/O, complex Math, etc.)
20