Upload
austin-leonard
View
228
Download
0
Embed Size (px)
Citation preview
JavaScript
Instructor: Charles Moen
CSCI/CINF 4230
2
JavaScript
JavaScript is a scripting language
For client-side Web application development
• Adds usability
• It’s a lightweight programming language that you can use to create “mini programs” within your Web pages
• Some common uses: validating form fields, and enabling menus
JavaScript (Ding, Schultz, Koch)
3
JavaScript History
Invented by Brendan Eich at Netscape in 1996 for the NetScape 2 browser
Not related to the Java programming language• LiveScript – the original name of JavaScript• Name was changed to JavaScript by the Netscape marketing department
because Java was popular at the time
All modern browsers support the minimal Netscape 3 level of JavaScript
Today, the standard for JavaScript is maintained by the European Computer Manufacturers Association (ECMA)
JavaScript (Ding, Wikipedia, Koch)
4
Browser Wars
1996 – 1999
Netscape vs. Microsoft• Netscape 3 was the most popular browser in 1996• In order to compete in the marketplace, Microsoft had to copy Netscape’s
functionality and created “Jscript” as their version of JavaScript• MS Internet Explorer 4 competed with Netscape 4 and tried to be as
incompatible as possible
Incompatible DOM extensions• Netscape 4 supported document.layers• IE 4 supported document.all
“Browser peace” – 1999• Microsoft Internet Explorer 5 was released• Netscape 4 died
JavaScript (Ding, Wikipedia, Koch)
5
Simple Example
<html> <head> <title>JavaScript Example</title> <script type="text/javascript" language="JavaScript"> document.write("<h1>Hello from JavaScript</h1>"); </script> </head> <body> </body></html>
JavaScript (Ding, Yue)
6
Another Simple Example
<html> <head> <title>JavaScript Example</title> <script type="text/javascript" language="JavaScript"> alert("Hello from JavaScript"); </script> </head> <body> </body></html>
JavaScript (Ding, Yue)
7
How does it work?
The browser reads and displays the content of your HTML file
When it finds a line of JavaScript code, it executes it• Executed by an interpreter within the browser
• You do not need to install it or buy a license for it
• There are some differences between browsers
• Code within a function isn’t executed until it’s called
JavaScript (Schultz, Koch, Ding)
8
Adding JavaScript Code to a Web Page
External file with JavaScript code• A separate text document linked to the page
• Best practice
Internal script element• Usually embedded within the <head> element of an HTML
document
• Deprecated
Inline JavaScript• Called as an event handler for an HTML element
• Deprecated
JavaScript (Schultz, Koch, Ding)
9
The script Element
JavaScript code is placed within a script element
Can be used either for internal JavaScript code or to link to an external file of JavaScript code
JavaScript (Schultz, Koch, Ding)
<html> <head> <title>JavaScript Example</title> <script type="text/javascript" language="JavaScript"> <!-- document.write("<h1>Hello from JavaScript</h1>"); //--> </script> </head> <body> </body></html>
Default is JavaScript
Comment symbols are used to hide the internal JavaScript code from browsers that do not support JavaScript
Internal JavaScript is usually placed in the head, but can be within the body – however, internal JavaScript is deprecated
10
The script Element
Example of linking to an external file of JavaScript code
JavaScript (Schultz, Koch, Ding)
<html> <head> <title>JavaScript Example</title> <script type="text/javascript" src="myscripts.js"></script> </head> <body> </body></html>
By convention, the extension is “.js”
document.write("<h1>Hello from JavaScript</h1>");
myscripts.js
The closing tag is important
11
Best Practice
The best practice is to place your JavaScript code in an external file
To separate behavior from the presentation and structure of our Web pages
Advantages• Cleaner HTML code that’s easier to maintain• Allows us to reuse the same JavaScript code with many
Web pages• Reduces the load size of a page, because the browser will
cache the js file
JavaScript (Schultz, Koch)
12
Another Example
<html> <head> <title>Simple HTML Form</title> <script type="text/javascript" src="BonusLab4.js"></script> </head> <body>
<!-- More code not shown -->
JavaScript
13
Some Syntax Rules
JavaScript code looks like Java code, but they are unrelated languages
JavaScript is case-sensitive
Using semicolons at the end of statements is optional, but considered good practice
White space is ignored
Comment syntax is the same as Java and C++
JavaScript (Schultz, Koch)
14
Calling a Built-in Function
alert("Hello from JavaScript");
JavaScript
myscripts.js
Functions can be called explicitly by using the name of the function, followed by parentheses that enclose any required arguments
15
Some Useful Built-in Functions
Can be used for user input
Can be used to alert the user
Often used for debugging
JavaScript (Schultz, Koch)
alert("Hello from JavaScript");var response = confirm("Continue?");var name = prompt("Enter your name");
A variable can be used to store the return value of a function
16
Variables
Variable names are case-sensitive
Data types• number• string
Implicit variable declaration – a variable may be declared before assigning a value to it, but it is not necessary to declare the data type
JavaScript (Schultz, Koch)
n = 42;var m = 3;
Scope Local – defined in a function and available only in that function Global – defined outside of a function and available anywhere
• boolean• object
17
Data Type Conversion
JavaScript converts from one data type to another when it is necessary
JavaScript (Koch)
var a = 4;var b = '4';var c = a * b;
The problem with + The + operator can mean either “add” when used with numbers, or
“concatenate” when used with strings
The variable b is interpreted as a number for this operation, however the data type of b doesn't change. The value of c is 16
var a = 4;var b = '4';var c = a + b;
Both variables are interpreted as strings, and the value of c is ‘44’
var a = 4;var b = '4';var c = a + (b*1);
PPK suggests using multiplication by 1 to convert a string to a number
18
Common Operators
Arithmetic+ - * / %
Assignment operators=+= -= *= /= %/
Comparison> < >= <= == !=
Increment and decrement++ --
Math object has many methods for working with numbersMath.round()Math.floor(), Math.ceiling()Math.random()
JavaScript (Schultz, Koch)
19
Calling a Function
Functions can be called explicitly or events can be used to execute a function
Events are actions that happen in a document, e.g. a user clicks a button or submits a form
Example:• When a user submits a form, a submit event is triggered
JavaScript (Schultz, Koch)
<form method="POST" action="#" onsubmit="alert('Submitted');">
<!-- More code not shown -->
<input type="submit" value="Add Sandwich"/> </form>
This inline event handler calls the alert function whenever the user clicks the submit input element
function addSandwich() { alert("Adding a sandwich");}
20
Calling User-Defined Functions
Functions that we define in the external script or within the script element are called the same way
JavaScript (Schultz, Koch)
The event handler can call any function that we added to the JavaScript code
<form method="POST" action="#" onsubmit="addSandwich();">
<!-- More code not shown -->
<input type="submit" value="Add Sandwich"/> </form>
BonusLab4.js
Function name Parentheses
function addSandwich(theForm) { var sandwich = "";}
21
Writing a Function
Start with the keyword function Followed by the function name Followed by parentheses
• Arguments can be declared within the parentheses
Curly braces enclose the function body
JavaScript (Schultz, Koch)
An argument declared within the function definitionBonusLab4.js
Initializing a string variable
The code in a function returns whenever it completes, and the keyword “return” is optional
22
Objects in JavaScript
JavaScript is object-oriented• Predefined objects
– JavaScript objects, such as String objects
– Browser objects
• Objects that we define and use
window – a single global browser object that contains everything
document• The most important object in the window• Represents the HTML page
Every HTML element is an object
JavaScript (Koch)
23
Defining and Using an Object
var sandwich = new Object();sandwich.meat = "Ham";sandwich.cheese = "Swiss";sandwich.showName = function() { alert(this.meat + " and " + this.cheese);}
alert(sandwich.meat);
alert(sandwich.showName());
JavaScript (Koch)
The “new” operator instantiates an object and returns a reference to it that can be stored in a variable
Define its properties and set the values
Define its method as a function
Using a property•Properties are publicly accessible•A script can even use a property when it doesn’t exist, but it will be “undefined”
Using a method•Object name, dot operator, function name, and parentheses•Be careful: we can refer to a method, even when it doesn’t exist•If it doesn’t exist, and we try to execute it, then we get an error
We can test for the existence of a method before calling it:if (sandwich.showPrice) { sandwich.showPrice();}
24
Using HTML Element Objects
Every HTML element is a predefined object
JavaScript (Koch)
<input type="text" name="state" id="stateid" value="TX" readonly="readonly"/>
var stateField = document.getElementById("stateid");
We can get the object that represents a form element by using the value of its “id” attribute as a hook.
The object A predefined browser object that represents the HTML page
A method of the document object
Value of the id attribute
The name and value attributes of a field element are accessible through the name and field properties of the object.alert("The field name is " + stateField.name);alert("Its value is " + state.Field.value);
25
Using a Form Object
Every document object has a nodeList of forms
JavaScript (Koch)
var firstForm = document.forms[0];
firstForm.elements[]
Every form has a nodeList named “elements” that contains all the fields in the form
We can examine all the elements in a form by using a for loop to iterate through the elements in the nodeList that belongs to the form.
In each iteration, we can perform some action on the current element. For example, we could check whether its value is valid.
26
Using a for Loop
Iterating through the elements in a form by using a for loop
JavaScript (Koch)
function addSandwich(theForm) {
var mySandwich = ""; for (var i=0; i<theForm.elements.length; i++) { var element = theForm.element[i]; }
}
A reference to the form object is passed as an argument to this function
The "elements" nodeList is a property of the form object
27
JavaScript Arrays
Arrays are objects in JavaScript
JavaScript (Koch)
var ingredients = new Array();ingredients[0] = "lettuce";ingredients[1] = "tomato";ingredients[2] = "onions";
var count = ingredients.length;
An Array object must be instantiated
The length property contains the number of items in the array
28
JavaScript nodeLists
JavaScript nodeLists are containers of elements Not created directly by the programmer; they are returned by
methods that retrieve nodes based on a criteria The syntax is similar to the syntax of an array, but a nodeList is not
an array The developer cannot modify a nodeList by adding elements;
however, it can be modified dynamically by the browser
JavaScript (Koch)
var paras = document.getElementsByTagName("p");
Returns a nodeList of all <p> elements
29
Using an if Conditional Statement
In each iteration of the for loop in our "addSandwich" function, we can examine the value of the element's "name" attribute so that we can find the fields that specify the quantity and the sandwich ingredients
JavaScript (Koch)
function addSandwich(theForm) { var mySandwich = ""; for (var i=0; i<theForm.elements.length; i++) { var element = theForm.element[i];
if (element.name == "quantity") { mySandwich += element.value + " "; }
}}
Testing for equality The "value" attribute of the text field with the name "quantity"
false true0 value != 0undefined
30
Testing for Equality and Identity
The equality operator is ==
JavaScript (Koch)
var a = 4;var b = '4';if (a == b) { alert("equal");}
The identity operator is === It requires that both operands have the same data type to be equal
The result of "a == b" is true
var a = 4;var b = '4';if (a === b) { alert("equal");}
The result of "a === b" is false
31
Form Field Properties
The object representing a form field has the following properties• type – text, hidden, textarea, checkbox, radio, submit
• form – the parent of this field
• disabled – true or false
• name – the name attribute
• value – the value of the field
JavaScript (Koch)
32
Using an else if Statement
Since there are six possible element names in our form, we need to check them all
JavaScript (Koch)
function addSandwich(theForm) { var mySandwich = ""; for (var i=0; i<theForm.elements.length; i++) { var element = theForm.element[i];
if (element.name == "quantity") { mySandwich += element.value + " "; } else if (element.name == "meat") { mySandwich += element.value; } }}
33
Using the && Operator
Since the radio buttons are both named “cheese,” we also have to test whether the button is checked
JavaScript (Koch)
function addSandwich(theForm) { var mySandwich = ""; for (var i=0; i<theForm.elements.length; i++) { var element = theForm.element[i];
if (element.name == "quantity") { mySandwich += element.value + " "; } else if (element.name == "meat") { mySandwich += element.value; } else if (element.name == "cheese") { if (element.checked == true && element.value == "yes") { mySandwich += ", cheese"; } } }}
AND operatorBoth statements must be true
34
Using the || Operator
Since we will do the same thing for every checkbox that is checked, we can combine their tests
JavaScript (Koch)
function addSandwich(theForm) { var mySandwich = ""; for (var i=0; i<theForm.elements.length; i++) { var element = theForm.element[i];
if (element.name == "quantity") { mySandwich += element.value + " "; } else if (element.name == "meat") { mySandwich += element.value; } else if (element.name == "cheese") { if (element.checked == true && element.value == "yes") { mySandwich += ", cheese"; } } else if (element.name == "lettuce" || element.name == "tomato" || element.name == "onion") { if (element.checked == true && element.value == "yes") { mySandwich += ", " + element.name; { } }}
35
Using the DOM
You can use JavaScript to restructure an HTML document• add elements
• remove elements
• rearrange elements
Level 0 DOM – part of the Netscape 3 standard
Level 1 DOM – the W3C DOM• Since 1998• All elements are nodes in a tree and the document node is the root• Node types: element (1), attribute (2), text (3), comment (8),
document (9)
JavaScript (Koch)
36
Finding Elements in the DOM
We can use an element’s id attribute to retrieve it as an object
JavaScript (Koch)
var zipField = document.getElementById("zip");var myForm = zipField.parentNode;
var paras = document.getElementsByTagName("p");
var tableBody = document.getElementById("sandwiches");
<div id="orderForm"> <table border="1" cellpadding="0"> <tbody id="sandwiches"> <tr><th>Sandwiches</th></tr> </tbody> </table></div>
A single element can be retrieved by its “id” attribute
Once we have an object that represents an element, we can retrieve its parent node
37
Changing the document
Four methods are available for changing the HTML document tree in the W3C DOM• appendChild()
• insertBefore()
• removeChild()
• replaceChild()
These are methods of an element node
JavaScript (Koch)
38
Creating New Elements
The W3C DOM allows us to create new elements that we can insert into the document tree• createElement()
• createTextNode()
These are methods of the document object
JavaScript (Koch)
var paraNode = document.createElement("p");var textNode = document.createTextNode("This is text");
39
Adding a Sandwich to the Order
JavaScript (Koch)
function addSandwich(theForm) { var mySandwich = ""; for (var i=0; i<theForm.elements.length; i++) { var element = theForm.element[i];
if (element.name == "quantity") { mySandwich += element.value + " "; } else if (element.name == "meat") { mySandwich += element.value; } else if (element.name == "cheese") { if (element.checked == true && element.value == "yes") { mySandwich += ", cheese"; } } else if (element.name == "lettuce" || element.name == "tomato" || element.name == "onion"){ if (element.checked == true) { mySandwich += ", " + element.name; } } } var sandwich = document.createTextNode(mySandwich); var row = document.createElement("tr"); var cell = document.createElement("td"); cell.appendChild(sandwich); row.appendChild(cell); var tableBody = document.getElementById("sandwiches"); tableBody.appendChild(row);}
We create a text node from the sandwich string that we constructed from the input values for this form
And we create tr and td elements to add to the form.
Then we add the text node to the td element and add the td element to the tr element
We get a reference to the tbody element where the new row should be added, and then append it there
40
Changing the CSS of an Element
If you use an external CSS stylesheet, the easiest way to change the style of an element is to change the value of its "class" attribute
Use "className" as the name of the "class" attribute, because "class" is a reserved word with a different meaning
JavaScript (Koch)
41
Hiding the Order
We can hide the order when the page is first opened by using a CSS class that sets the display to "none"
JavaScript (Koch)
.invisible { display: none;}.visible { display: block;}
<div id="orderForm" class="invisible"> <table border="1" cellpadding="0"> <tbody id="sandwiches"> <tr><th>Sandwiches</th></tr> </tbody> </table></div>
An element with this class will be invisible because its display is set to "none"
When we first see the web page, this div cannot be seen
42
Showing the Order
After we append a row with a sandwich to the table, we can show the order by using a CSS class that sets the display to "block"
JavaScript (Koch)
.invisible { display: none;}.visible { display: block;}
document.getElementById("order").className = "visible";
An element with this class will be visible because it sets the display to "block"
In the JavaScript, we add this line at the end of the addSandwich function
43
References
Ding, Wei, “JavaScript” UHCL lecture slides, 2008.
Keith, Jeremy. DOM Scripting: Web Design with JavaScript and the Document Object Model. friends of ED, 2005.
Koch, Peter-Paul, PPK on JavaScript. New Riders, 2007.
Schultz, David and Craig Cook, Beginning HTML with CSS and XHTML: Modern Guide and Reference. Apress, 2007.
Yue, Kwok-Bun, “An Introduction to JavaScript” UHCL lecture notes, 2000.