98
COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Embed Size (px)

Citation preview

Page 1: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

COM621 – Interactive Web Development

Lecture 3 – JavaScript & DOM

Page 2: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JavaScript• The World Wide Web began as a simple repository of information, but

it has grow into much more. As the Web has evolved, the tools have also evolved.

• Simple markup tools like HTML have been joined by true programming languages including JavaScript.

• JavaScript, although a programming language, it is a very simple language. Once you create a web page with HTML, you can easily use JavaScript to improve the page.

• JavaScript programs can range from a single line to a full scale application, such as a game.

Page 3: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JavaScript

• Although JavaScript’s name appear to connote a close relationship with Java, they are actually very different. – Java is a typed language with static objects – JavaScript is more dynamic.

• The main similarity between the two is the syntax of their expressions, assignment statements and control statements.

Page 4: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Scripting

• To add JavaScript to a page, the <script> tag needs to be used. This tag will tell the browser to start treating the text as a script and the corresponding closing tag will tell it to return to HTML mode.

• When more complicated scripts are created, you can use external JavaScript files the same way you use external CSS.

• In order to link them to the document you will need to use a script line with the language, type and src properties set accordingly:

<script language="javascript" type="text/javascript" src="JS01.js" ></script>

Page 5: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Programming in JSBasic Rules

• JavaScript is a simple language, but you need to be careful to use its syntax correctly. There are a few basic rules you should understand to avoid errors.

Case Sensitivity

• Almost everything in JavaScript is case sensitive: you cannot use lowercase and capital letters interchangeably. Some general rules:

– JavaScript keywords are always lowercase– Built in objects such as Math and Date are capitalized.– DOM object names are usually lowercase, but their methods are often a

combination of capital and lowercase. Usually capitals are used for all but the first word, as in toLowerCase and getElementById.

Page 6: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Programming in JSBasic Rules

Variable Object and Function Names • When you define your own variables, objects, or functions, you can

choose their names. Names can include uppercase letters, lowercase letters, numbers, and the underscore (_) character. Names must begin with a letter or underscore.

Spacing • Blank space (known as whitespace) is ignored by JavaScript. You

can include spaces and tabs within a line, or blank lines, without causing an error. Blank space often makes the script more readable.

Page 7: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Reserved Words &Comments

• There are 25 reserved words in JavaScript:

• JavaScript has 2 forms of comments:

– Whenever two adjacent slashes (//) appear on a line, the rest of the line is considered a comment.

– /* May be used to introduce a comment, and */ to terminate it, in both single and multiple line comments.

break case catch continue default

delete do else finally for

function if in instanceof new

return switch this throw try

typeof var void while with

Page 8: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The ValidationProblem

• When embedded JavaScript happens to include recognizable tags (for example <br /> in the output of the JavaScript) these tags often cause validation errors.

• Therefore it is recommendable to enclose embedded JavaScript in XHTML comments when explicitly embedding JavaScript.

Page 9: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The ValidationProblem

• Example of embedded JS with XHTML Comments<script type="text/javascript" language="javascript"><!--document.write(document.lastModified);--></script>

Page 10: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JS Best Practice

• When writing JavaScript it is good not only to know and follow the rules but also following some best practices might save yourself and others some headaches in the future:

– Use comments liberally: These make your code easier for yourself and others to understand making it easier to edit when needed later. Comments are also useful for marking the major divisions of a script.

– Use a semicolon (;) at the end of each statement, and only use one statement per line: This will make your scripts easier to debug.

Page 11: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JS Best Practice

– Use separate JavaScript files when possible: This separates JavaScript from HTML and makes debugging easier, and also encourages you to write modular scripts that can be reused.

– Avoid being browser-specific: As you learn more JavaScript, you will learn some features that only work in one browser. Avoid them unless absolutely necessary, and always test your code in more than one browser.

– Keep JavaScript optional: Don’t use JavaScript to perform an essential function in your site – for example, the primary navigation links. Whenever possible, users without JavaScript should be able to use your site, although it may not be quite as attractive or convenient.

Page 12: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The DOCUMENT OBJECT MODEL (DOM)

Page 13: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

DOM• One advantage that JavaScript has over basic HTML is that scripts can

manipulate the web document and its contents.

• Your script can load a new page into the browser, work with parts of the browser window and document, open new windows, and even modify text within the page dynamically.

• To work with the browser and documents, JavaScript uses a hierarchy of parent and child objects called the Document Object Model (DOM).

• These objects are organized into a tree-like structure, and represent all of the content and components of a web document.

Page 14: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

DOM

• The Objects in the DOM have properties – variables that describe the web page or documents, and methods – functions that enable you to work with parts of the web page.

• When you refer to an object, you use the parent object name followed by the child object name or manes, separated by periods.

– For example, JavaScript stores objects to represent images in a document as children of the document object.

– The following refers to the image9 object, a child of the document object, which is a child of the windows object:window.document.image9

Page 15: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

DOM Hierarchy

Page 16: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Windows Objects

• The windows object represents a browser window

• There can be several window objects at a time, each representing an open browser window.

• Example:– window.alert(‘message’) – This method displays a

message in an alert box:<p onMouseOver="window.alert('Mouse Over Me');">Trigger an Event</p>

Page 17: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Web Documents

• The document object represents a web document or page. Web documents are displayed within browser windows, so the document object is a child of the window object.

• Because the window object always represents the current window (the one containing the script), you can use window.document to refer to the current document. You can also simply refer to document, which automatically refers to the current window.

Page 18: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Web DocumentsGetting Information on the Document

• Several properties of the document object include information about the current document in general:

Property Explanation

document.URL specifies the document’s URL. This is a simple text field that can not be modified

document.title title of the document page, defined by the HTML <title> tag

document.referrer is the URL of the page the user was viewing prior to the current page (usually a page with a link to the current page)

document.lastModified is the date the document was last modified (this date is sent from the server along with the page)

Page 19: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Property Description

document.bgColordocument.fgColor

Background and foreground(text) colors for the document, corresponding to the BGCOLOR and TEXT attributes of the <body> or their CSS equivalent (background-color and color)

document.linkColordocument.alinkColordocument.vlinkColor

These are the colors for links within the document.

document.cookie Enables you to read or set a cookie for the document.

Property Description

document.write Prints text as part of the HTML page in a document window

document.location.href Used to load a new document

Page 20: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

ExampleDocument Last Modified

<p>This page was last modified on:<script language="javascript" type="text/javascript"><!--document.write(document.lastModified);--></script></p>

Writing Markup to Screen JS document object property

Page 21: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Writing Text in aDocument

• The document.write method prints text as part of the HTML in the document window.

• This statement is used whenever you need to include output in a web page.

Page 22: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Links and Anchors

• There can be multiple link objects in a document, each one includes information about a link to another location or an anchor

• link objects can be accessed with the links array, each member of the array is one of the link objects in the current page.

• A property of the array, document.links.length, indicates the number of links in the page

Page 23: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Links and Anchors• Each link object (or

member of the links array) has a list of properties defining the URL.

• The href property contains the entire URL, and other properties define portions of it (These are the same properties as the location object that will be defined later.

• A property can be referred to by indicating the link number and the property name:

<a href="http://www.scis.ulster.ac.uk">SCIS</a><br /><a href="http://www.scis.ulster.ac.uk/~jose">Jose's Page</a>

<script language="javascript" type="text/javascript"><!--document.write('<hr />');var link1 = document.links[0].href;document.write(link1);--></script>

Page 24: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The HistoryObject

• This object holds information about the URLs that have been visited before and after the current one, and it includes a method to go to previous or next locations

• The history object has one property that can be accessed:– history.length – keeps track of the length of the

history list (number of different locations tat the user has visited)

Page 25: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The HistoryObject

• The history object has 3 methods that can be used to move through the history list:– history.go() – opens a URL from the history list.

This method’s argument is a positive or negative number. i.e. history.go(-2) is equivalent to pressing the back button twice.

– history.back() loads the previous URL in the history list

– history.forward() loads the next URL in the history list (if available)

Page 26: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

ExampleNavigation Buttons

<body><h1>Back and Forward</h1><p>This page allows you to go back or forward to pages in the history ist. These buttons are equivalent to the back and forward buttons in the browser&lsquo;s toolbar</p>

<form action="" method="post"><input type="button" onclick="history.back();" value="<-- BACK" /><input type="button" onclick="history.forward();" value="FORWARD -->" /></form></body>

Page 27: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The Location Object

• This is the third child of the window object.• This object stores information about the

current URL stored in the window.• For example, the following statement loads a

URL into the current window:

window.location.href="http://www.google.com";

Page 28: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The Location Object

• The href property contains the entire URL of the window’s current location.

• Portions of the URL can be accessed with various properties of the location object.

Page 29: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The Location Object

• Consider the URL:– http://www.jsworkshop.com:80/test.cgi?lines=1#anchor

Properties Description Returns

location.protocol The protocol part of the URL http

location.hostname The host name of the URL www.jsworkshop.com

location.port The port number of the URL 80

location.pathname filename part of the URL test.cgi

loaction.search query portion of the URL (if any) lines=1

location.hash anchor name used in the URL #anchor

The link object introduced earlier, also includes this list of properties for accessing portionsof the URL

Page 30: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The Location Object

• The location object has two methods:location.reload() reloads the current document.

This is the same as the reload button on the browser’s toolbar

location.replace() replaces the current location with a new one.This is similar to setting the location object’s properties yourself. The difference is that the replace method does not affect the browser’s history. (the back button cannot be used to go to the previous location.

setTimeout(function() {document.write(alert('Relocating to Google'));window.location.replace("http://www.google.com");},3000);

Page 31: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JavaScript Basics

Page 32: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JavaScript BasicsVariables, Strings and Arrays

• Variables are named containers than can store data (for example a number, a text string, or an object).

• Some computer languages require you to declare a variable before you use it. JavaScript includes the var keyword for that purpose, but in many cases you can omit it as the variable will be declared the first time a value is assigned to it.

• A variable’s scope is the area of the script in which that variable can be used. There are two types of variables:

– Global Variables have the entire script (and other scripts in the same HTML document) as their scope. They can be used anywhere, even within functions.

– Local Variables have a single function as their scope. They can be used only within the function they are created in.

Page 33: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JavaScript BasicsVariables, Strings and Arrays

• To declare a global variable, you declare it in the main script, outside any functions.

• You can use the var keyword to declare a variable (and you should get used to using the var keyword when declaring variables as you will avoid errors and make your scripts easier to read).

• A local variable belongs to a particular function. Any variable you declare with the var keyword in a function is a local variable.

• Additionally, the variables in the function’s parameter list are always local variables. (In functions, the var keyword must be used to create local variables, this forces JavaScript to create a local variable, even if there is a global variable with the same name).

• To assign values to a variable, you can use the equals (=) sign. You can use any expression to the right of the equal sign, including other variables. i.e. var count = count+1;

Page 34: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JavaScript BasicsIncrementing and Decrementing

• Because incrementing and decrementing variables is quite common, JavaScript includes two types of shorthand for this syntax:

– The += operator (i.e. count +=1;). – Similarly the -= operator (count -=1;)– The increment/decrement operators (i.e. count++; or

count --;)

Page 35: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JavaScript BasicsIncrementing and Decrementing

• You can also alternatively use the ++ or -- operators before a variable name (i.e. ++count;). However, these are not identical. The difference is when the increment or decrement happens:

– If the operator is after the variable name, the increment or decrement

happens after the current expression is evaluated. i.e (alert(count++); with the current value of count at 10 will display an alert box with the value 10 and then increment count.)

– If the operator is before the variable name, the increment or decrement happens before the current expression is evaluated. i.e (alert(++count); with the current value of count at 10 will display an alert box with the value 11 – increments before it evaluates).

Page 36: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Expressions & Operators

• An expression is a combination of variables and values that the JavaScript interpreter can evaluate to a single value.

• The characters that are used to combine these values are called operators.

Operator Description Example

+ Concatenate (combine strings) message="test" + count + ":";

+ Add total = 5+7;

- Subtract total = 3-2;

* Multiply total = qty * price;

/ Divide share = total/4;

Page 37: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Expressions &Operators

• When more that 1 operator is used in an expression, JavaScript uses rules or operator precedence to decide how to calculate the value.

• The Operators Table in the previous slide lists the operators from lowest to highest precedence. (highest precedence is evaluated first).

Page 38: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Strings• Strings are used to store a group of text characters. They are named

similarly to other variables. JavaScript stores strings as String objects.

• There are two ways to create a new String object:

– Assigning the string to a variable i.e. test = "This is a test";– Using an object oriented syntax i.e. test = new String("This is a test");

• The new keyword is used to create objects. • You can assign values to a string in the same way as you do for a

variable. Also the concatenation operator (+) can be used to combine the values of two strings.

Page 39: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Useful Operationson Strings

• Calculating the Length:– stringname.length – returns the number of

characters in the “stringname” string• Convert the String Case:– stringname.toUpperCase() – converts all

characters in the string to uppercase– stringname.toLowerCase() – converts all

characters in the string to lowercase

Page 40: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Sub-Strings

• The Substring method allows you to work with portions of a string

• Given a string stored in the variable text, text.substring(x,y) will return the character of the string from x to y:– Indexing starts with 0 for the 1st character (min value of x)– the second index (y) is NON-INCLUSIVE (for example y=6

means the 6th character (0-5).– The two indexes can be specified in any order, the

smallest one will be assumed to be the first index.

Page 41: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Sub-Strings

• Assume the following string: alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Substring Examples Returns

alpha.substring(0,4) ABCD

alpha.substring(10,12) KL

alpha.substring(6,7) G

alpha.substring(6,6) null

RETURNING CHARACTERS

alpha.charAt(0) A

alpha.charAt(25) Z

alpha.charAt(27) null

Page 42: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Arrays• An array is a numbered group of data items that can be treated as a single

unit. Arrays can contain string, numbers, objects or other types of data. Each item in an array is called an element of the array.

• To assign a value to an array, an index is used in brackets. Indexes begin with 0, i.e– marks[0]=66;– marks[1]=40;– marks[2]=73;– marks[3]=57;

• You can also declare an array an specify the elements at the same time:– marks = [66,40,73,57];

• Note: if you use the new keyword, you will need to use parenthesis instead:– marks = new Array (66,40,73,57);

Page 43: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Arrays

• You can access the elements of an array using the same notation that was used to assign values, for example, the following script calculates the average of the 4 marks in the marks array.

marks = new Array (66,40,73,57);average_mark= (marks[0]+marks[1]+marks[2]+marks[3])/marks.length;document.write(average_mark);

marks.length property returns the number of elements in the array, in this case 4

Page 44: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

String Arrays

• JavaScript does not make a distinction between numeric and string arrays, so they are declared in the same way:– names = new Array(30);– names[0] = "Henry J. Tillman";– names[1] = "Sherlock Holmes";

• As with numeric ones, the contents can also be specified upon creation:– names = new Array("Henry J. Tillman","Sherlock Holmes");– names = ["Henry J. Tillman","Sherlock Holmes"];

Page 45: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

String Arrays

• String array elements can be used anywhere a string would be used

• string methods can also be used with string arrays:– document.write(names[0].substring(0,5)) –prints

Henry to the screen

Page 46: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

String ArraysSplitting and Joining

• JS includes a string method called split, which splits a string into its component parts.

• To use this method, the string and the character to divide the parts should be specified:

• JavaScript also includes an array method, join, which performs the opposite function:

test = "John Q. Public"parts = test.split(" ")

parts[0] = "John"parts[1] = "Q."parts[2] = "Public"

fullname = parts.join(" ");

Page 47: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

String ArraysSorting

• JavaScript includes a sort method for arrays which returns an alphabetically sorted version of the array.

names = new Array(4);names[0] = "John Public";names[1] = "Henry Tillman";names[2] = "Mickey Mouse";names[3] = "George Bush";document.write(names + "<br />");names.sort();document.write(names); Note: Sort Method does not work with numeric

arrays

Page 48: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Code to SortNumeric Arrays

<script language="javascript" type="text/javascript"><!--function numcompare(a,b) {

return a-b;}nums = new Array(30,50,5,8,6);sortednums = nums.sort(numcompare);document.write(sortednums);--></script>

numcompares returns a negative number is a belongs before b, 0 if they are the same and a positive number if a belongs after b

To sort numerical arrays, a function that comparesthe numbers in the array needs to be specified as theargument of the sort method.

Page 49: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Functions & Objects

• Functions are a group of JavaScript statements that can be treated as a single unit.

• To use a function, it must be first defined. For Example:

function Greet() {alert("greetings.");}

Page 50: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Functions & Objects

• This function will display an alert message to the user. – The function begins with the function keyword, – followed by the function’s name (Greet) – followed by the input arguments or parameters (in

this case there are none so empty parenthesis “( )” are used).

– The first and last lines of the function use the braces { and } to enclose all of the statements in the function.

Page 51: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Functions & Objects

• Function parameters are used to obtain some user input to make the function more useful.

• The previous example will simply create an alert box with the word “greetings” on it, but if we add a parameter, we can customize this function:

function Greet(who) {alert("greetings" + who);}

Page 52: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Functions & Objects

• There are normally 2 good places where you can place a function: – in the <header> of the HTML document, or – on the JavaScript file that is linked to the document

through the <script> tag in the header.

• If placed in the latter, it will allow the function to be re-used by other pages by simply linking the JavaScript file to other pages effectively creating your own library of functions.

Page 53: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Functions & Objects• If the function is implemented in a page and the page is loaded, you will

notice that the page does nothing. This is because the function needs to be called for it to work.

• To call a function, use the function’s neame as a statement in a script. You will need to include the parenthesis and the values for the function’s parameters. – For example, to call the Greet(who) function you will need to use the following

statement (inside <script> tags in the body of your HTML file):

Greet("Jose");

• This statement tells the JavaScript interpreter to transfer control to the first

statement in the Greet function. It also passes the parameter “Jose” to the function. This value will be assigned to the who variable inside the function.

Page 54: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Functions & Objects

• Functions can return values to the script that called them. This allow functions to be used to calculate values.

• For example, we can create a function that calculates the average of 4 numbers.

function Average(a,b,c,d) {result = (a + b + c +

d)/4;return result;

}

This function creates a local variable called result in which the result of the average calculation is stored (adding the 4 arguments together and dividing this sum by 4).

In order to send this result back to the script that calls the function, the return keyword is used.

Page 55: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Calling a Functionwith Arguments

• In order to execute the function, we need to call it in the body of the page and give the arguments to the function:

total = Average (40,50,55,70,76,82);document.write(total);

Page 56: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Objects• So far we have used variables to represent different kinds of data in

JavaScript. We have also seen that JavaScript also supports objects, a more complex kind of variable that can store multiple data items and functions.

• The difference between a variable and an object is that the latter can store more than 1 value at a time, as well as functions for working with values.

• There are 3 kinds of objects in JavaScript:

– DOM objects, – built-in objects and – custom objects.

• The syntax for working with them is the same.

Page 57: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Custom Objects• To create an object, you will need to use the new keyword to instruct the

interpreter to create the object.

• Each object has one or more properties (variables that will be stored within the object). – Like variables, each object property has a value. – To read a property’s value, you simply include the object name and the property name,

separated by a period, in any expression. – You can change a property’s value using the = operator, just like a variable.

• Along with properties, each object can have one or more methods.• These are functions that work with the object’s data

– (for example the JS statement used to reload a page: location.reload();) When you use reload(), you are using a method of the location object.

– Like functions, methods can accept arguments in parentheses, and can return values.

Page 58: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Example

• As an example, we will now create an object to store a business card that can be used with scripts that work with a business card database that contains names, addresses, and phone numbers for a variety of people

Page 59: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Example

Step 1: Defining an object • The first step in creating an object is to name it and its

properties. • We will call the object a Card object. • Each object will have the following properties:

– name, address, workphone, mobilephone.• The first step is to create a function to make new Card

Objects. • This function is called the constructor for an object.

Page 60: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Example• Constructor Function:

• Notice the this keyword, this is used to create an object definition. Use this to refer to the current object.

• The constructor accepts several parameters from the statement that calls the function, and then assigns them as properties of an object.

• Because the function is called Card, the object is the Card object.

Page 61: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Example

• The next step is to create a method to work with the Card object.

• Because all Card objects will have the same properties, it might be handy to have a function that prints out the properties in a neat format.

• We can call this function PrintCard().

Page 62: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Example

• Print Card Function:

• To make this function a method of the Card object you need to make PrintCard() part of the function definition for Card objects.

• This is done by adding the following line to the end of the Card function: this.PrintCard = PrintCard;

Page 63: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Example

• This added statement looks just like another property definition, but it refers to the PrintCard() function.

• This will work so long as the PrintCard() function is defined with its own function definition.

• Methods are essentially properties that define a function rather than a simple value.

Notice the use of UpperCase Names to differentiate methods from properties in the Card creation function

Page 64: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

ExampleCreate an Instance

• To use an object definition, you create a new object with the new keyword. This statement creates a new card object called Jose

– jose = new Card("Jose Santos", "University of Ulster", "x75034" , "07773-000000");

• After this statement executes, a new object is created to hold jose’s information.

• This is called an instance of the Card object. • There can be several instances of an object you define.

Page 65: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

ExampleCreate an Instance

• Another way to define an instance is by assigning the information after the fact, for example, the following script creates an empty card object called wayne and then assigns its properties:

• After you have created an instance of the Card object using either of these methods, you can use the PrintCard() method to display its information. For example to display the properties of the “jose” card you will use this statement:

wayne = new Card();wayne.name = "Bruce Wayne";wayne.address = "Wayne Manor - Gotham";wayne.workphone = "0800-228626";wayne.mobilephone = "0800-192963";

jose.PrintCard();

Page 66: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Conditionals &Loops

• Statements in a JavaScript program generally execute in the order in which they appear, one after the other.

• Because this isn’t always practical, most programming languages provide flow control statements that let you control the order in which code is executed.

Page 67: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Conditionals &Loops

• Functions are one type of flow control although a function might be defined first thing in your code, its statements can be executed anywhere in the script.

• There are two other types of flow control in JavaScript: – conditions, which allow a choice of different

options depending on a value, and – loops, which allow repetitive statements.

Page 68: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The IF statement

• The capability to test and compare values is one of the most important features of a computer language.

• This allows the scripts to behave differently based on the values of variables, or based on input from the user.

• The if statement is the main conditional statement in JavaScript.

Page 69: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The IF statement

• The if statement in JavaScript consists of two parts:– The Condition– The Action

• This statement includes a condition (if a equals 1) and an action (display a message). This statement checks the variable a, if it is equals to 1 then displays an alert message. Otherwise, it does nothing.

if (a==1) window.alert("Found a 1!");

Page 70: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The IF statement

• When using the if statement, you can do one or more actions. If more than one action is being carried out, then they need to be enclosed in braces { }:

if (a==1) {window.alert("Found a 1!");a = 0;}

Page 71: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Conditional Operators

• The condition part of the expression for an if statement has its own syntaxis, it is called the conditional expression.

• A conditional expression usually includes two values to be

compared. These values can be variables, constants or even expressions in themselves.

• Between the two values to be compared, there is a conditional operator. This operator tells JavaScript how to compare the two values:

Page 72: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Conditional OperatorsOperator Explanation

== is equal to

!= is not equal to

< is less than

> is greater than

<= is less than or equal to

>= is greater than or equal to

Page 73: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Logical Operators

• Often, you will want to check a variable for more than one possible value, or check more than 1 variable at once. JavaScript includes logical operators, also know as Boolean operators, for this purpose.

Operator Explanation

|| logical OR test for any of the condition to be TRUE

&& logical AND test for all the conditions to be TRUE

! NOT – used to invert an expression

Page 74: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

The else keyword

• An additional feature of the if statement is the else keyword.

• It tells the JavaScript interpreter what to do is the condition is not true. i.e.

if (a==1) {window.alert("Found a 1!");a = 0;}else {window.alert(“Incorrect value: “ + a);}

Page 75: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Switch Statements

• The switch statement is used in JavaScript to test multiple conditions on a single variable and execute different blocks of code depending on which condition was met.

• This is the basic syntaxis for the switch statement:switch(n){case 1: execute code block 1 break;case 2: execute code block 2 break;default: code to be executed if n is different from case 1 and 2}

switch(x){case "a": execute code block a break;case "b": execute code block b break;default: code to be executed if n is different from case "a" and "b"}

Page 76: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Switch StatementComponents

• The initial switch statement. This statement includes the value to test (in this case n) in parentheses.

• Braces { and } enclose the contents of the switch statement.• One or more case statements. Each specifies a value to

compare with the value specified in the switch statement. If the values match, the statements in the code block after the case are executed; otherwise the next case is tried.

• The break statement is used to end each case. This skips to the end of the switch.

• Optionally, the default case can be included and followed by one or more statements that are executed if none of the other cases were matched.

Page 77: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

For Loops

• Loops are useful any time you need a section of code to execute more than once.

• The for keyword is the first tool to consider for creating loops.

• A for loop typically uses a variable (called a counter or an index) to keep track of how many times the loop has executed, and it stops when the counter reaches a certain number.

Page 78: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

For Loops• Construction:

• There are three parameters separated by semicolons:

– var=startvalue – this sets a variable to be the counter or index and gives it an initial value. i.e. a=0;

– var<=endvalue – this is a condition that must remain true to keep the loop running. i.e. a<10;

– var=var+increment – the third parameter is a statement that executes with each interaction of the loop. This is called the increment expression because it is usually used to increment the counter. i.e. a++

for (var=startvalue; var<=endvalue; var=var+increment){code to be executed}

Page 79: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

While Loops

• Another keyword for loops in JavaScript is while.

• Unlike for loops, while loops don’t necessarily use a variable to count.

• Instead, they execute as long as a condition is true.

• In fact, if the condition starts out as false, the statements won’t execute at all.

Page 80: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

While Loops

• Constructionwhile (var<=endvalue) { code to be executed }

Page 81: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Do-While Loops

• JavaScript 1.2 introduced a third type of loop: the do…while loop.

• This type of loop is similar to an ordinary while loop with one difference: – The condition is tested at the end of the loop

rather than at the beginning (guaranteeing that the loop will run at least once if the condition is false).

Page 82: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Do-While Loops

• Construction:

do { code to be executed }while (var<=endvalue);

Page 83: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

JavaScript Example Implementations

Page 84: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Time Display

• One common and easy use for JavaScript is to display dates and times. Because it runs on the browser, the times it displays will be in the user’s current time zone:

• After starting the script, we need to determine

the local time and store it in a variable: (remember, JavaScript commands are case sensitive)

Page 85: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Time Display<script type="text/javascript" language="javascript"><!--now = new Date();localtime = now.toString();utctime = now.toGMTString();document.write("<b>Local time:</b> " + localtime + ”<br />");document.write("<b>UTC time:</b> " + utctime);hours = now.getHours();mins = now.getMinutes();secs = now.getSeconds();document.write("<h1>");document.write(hours + ":" + mins + ":" + secs);document.write("</h1>");--></script>

JavaScript uses aDate() function to getthe current date and time from the server –we store it in a variablecalled now

universal time (UTC) iscalculated by calling string transformation.toGMTString()

JavaScript stores dates as the number of miliseconds sincejanuary 1st, 1970. Fortunately it includes a number of functions toconvert date and times in various ways.

Page 86: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Connected Series ofWindows (pop-ups)

• The goal is to provide a connected series of windows which can be popped up from one of your WEB pages to provide some information.

• Create a function that will open a new window given

its URL using the DOM object window.open:

function openWin(URL) {aWindow = window.open(URL, "Window 1", "width=400, height=400,

scrollbars=yes" );}

Page 87: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

• Create 3 HTML pages the will be opened as pop-ups (call them page1, page2, page3).

• Create a hyperlink in the main page that will open the new window, the message should read along the lines: click here to open window 1.

• The href property of the hyperlink needs to be set to: "javascript:openWin(’page1.html');”

Page 88: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

• To Add some navigation on the opened window place a button to navigate to a second page (page2.html) and another to close the window:

• On the second page an additional button to go back to page1.html could be added for full navigation capabilities

<form action=””><input type="button" value="Close Window" onclick="window.close();" /><input type="button" value="Next Page" onclick="window.location.href='page2.html';" /></form>

Page 89: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Roll-Over Images

• The goal is to change images when the mouse is moved over the images to create some sort of animation or effect.

• From the internet, download 2 images of the same object/character in different positions (for clarity, we will call the images T1.gif and T3.gif for this example). Place your images in the images folder of your site.

Page 90: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Roll-Over Images

• The implementation can be done as a link (clickable image) or simply as an effect using only the image.

• Note on the code the use of the DOM images array

Page 91: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Roll-OverUsing DOM and mouse

Actions

<a href="javascript:openWin('http://en.wikipedia.org/wiki/Penguin');" onmouseover="document.images[0].src='images/T3.gif';"onmouseout="document.images[0].src='images/T1.gif';"><img name="T1" alt="penguin" height="68" width="55" border="0" src="images/T1.gif" /></a>

<hr /><img name="T1" alt="penguin" height="68" width="55" border="0" src="images/T1.gif"onmouseover="document.images[1].src='images/T3.gif';"onmouseout="document.images[1].src='images/T1.gif'" />

document.images [0] as Link

document.images[1]

Page 92: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

SlideShow

• The goal is to create a small slideshow using the W3C DOM

– Download 5 images and place them in the body the HTML document where the slideshow will be displayed.

– Use an embedded stylesheet and assign each image tag a “slide” class. Set the CSS property for the image class to display as a block.

Page 93: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

SlideShow

• Create two functions to handle the slide show as described:– the first one (called MakeSlideShow) will find and

store all the images in a variable and its length is going to be used to limit the number of slides displayed. It will also hide all the slides except the first one. And will call the function to call the next slide (NextSlide) when there is a click event on the slide

Page 94: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Declarations

• Before the functions are created, we need to declare the global variables that will be used in the functions:– numslides: a counter that will contain the total number of

slides– currentslide: a counter that will store the slide being

displayed– slides: an array to store the images used in the slide-show

var numslides=0, currentslide=0;var slides = new Array();

Page 95: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

SlideShowfunction MakeSlideShow() {

// find all images with the class "slide"

imgs=document.getElementsByTagName("img");for (i=0; i<imgs.length; i++) {

if (imgs[i].className != "slide") continue;

slides[numslides]=imgs[i];// hide all but the first imageif (numslides==0) {

imgs[i].style.display="block";} else {

imgs[i].style.display="none";}imgs[i].onclick=NextSlide;numslides++;

}}

Page 96: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

SlideShow

• The second function (NextSlide()) will hide the current slide, increment the slide counter, compare that is not the last slide, and display the next slide. If the slide is the last one, then it will reset the current slide counter to 0.

function NextSlide() {

slides[currentslide].style.display="none";currentslide++;if (currentslide >= numslides)

currentslide = 0;

slides[currentslide].style.display="block";}

Page 97: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

SlideShow

• To make the slideshow work, we need to start it, we can use the window.onload method to do this: (type in the head of the document inside <script> tags):

– window.onload=MakeSlideShow;

Page 98: COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM

Additional Examples

• Additional Examples: (accompanying document)– Rotating Billboards– Date-Time Manipulations– Getting and Displaying data with forms