Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM."— Presentation transcript:

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

2 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.

3 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.

4 Scripting To add JavaScript to a page, the 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:

5 Programming in JS Basic 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.

6 Programming in JS Basic 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.

7 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. breakcasecatchcontinuedefault deletedoelsefinallyfor functionifininstanceofnew returnswitchthisthrowtry typeofvarvoidwhilewith

8 The Validation Problem When embedded JavaScript happens to include recognizable tags (for example 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.

9 The Validation Problem Example of embedded JS with XHTML Comments <!-- document.write(document.lastModified); -->

10 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.

11 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.

12 The DOCUMENT OBJECT MODEL (DOM)

13 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.

14 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

15 DOM Hierarchy

16 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: Trigger an Event

17 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.

18 Web Documents Getting Information on the Document Several properties of the document object include information about the current document in general: PropertyExplanation document.URLspecifies the document’s URL. This is a simple text field that can not be modified document.titletitle of the document page, defined by the HTML tag document.referreris 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.lastModifie d is the date the document was last modified (this date is sent from the server along with the page)

19 PropertyDescription document.bgColor document.fgColor Background and foreground(text) colors for the document, corresponding to the BGCOLOR and TEXT attributes of the or their CSS equivalent (background-color and color) document.linkColor document.alinkColor document.vlinkColor These are the colors for links within the document. document.cookieEnables you to read or set a cookie for the document. PropertyDescription document.writePrints text as part of the HTML page in a document window document.location.hrefUsed to load a new document

20 Example Document Last Modified This page was last modified on: <!-- document.write(document.lastModified); --> Writing Markup to ScreenJS document object property

21 Writing Text in a Document 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.

22 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

23 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: SCIS Jose's Page <!-- document.write(' '); var link1 = document.links[0].href; document.write(link1); -->

24 The History Object 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)

25 The History Object 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)

26 Example Navigation Buttons Back and Forward 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‘s toolbar " />

27 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";

28 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.

29 The Location Object Consider the URL: – http://www.jsworkshop.com:80/test.cgi?lines=1#anchor PropertiesDescriptionReturns location.protocolThe protocol part of the URLhttp location.hostnameThe host name of the URLwww.jsworkshop.com location.portThe port number of the URL80 location.pathnamefilename part of the URLtest.cgi loaction.searchquery portion of the URL (if any)lines=1 location.hashanchor name used in the URL#anchor The link object introduced earlier, also includes this list of properties for accessing portions of the URL

30 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);

31 JavaScript Basics

32 JavaScript Basics Variables, 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.

33 JavaScript Basics Variables, 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;

34 JavaScript Basics Incrementing 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 --;)

35 JavaScript Basics Incrementing 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).

36 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. OperatorDescriptionExample + Concatenate (combine strings) message="test" + count + ":"; + Add total = 5+7; - Subtract total = 3-2; * Multiply total = qty * price; / Divide share = total/4;

37 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).

38 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.

39 Useful Operations on 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

40 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 1 st character (min value of x) – the second index (y) is NON-INCLUSIVE (for example y=6 means the 6 th character (0-5). – The two indexes can be specified in any order, the smallest one will be assumed to be the first index.

41 Sub-Strings Assume the following string: alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Substring ExamplesReturns 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

42 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);

43 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

44 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"];

45 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

46 String Arrays Splitting 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(" ");

47 String Arrays Sorting 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 + " "); names.sort(); document.write(names); Note: Sort Method does not work with numeric arrays

48 Code to Sort Numeric Arrays <!-- function numcompare(a,b) { return a-b; } nums = new Array(30,50,5,8,6); sortednums = nums.sort(numcompare); document.write(sortednums); --> 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 compares the numbers in the array needs to be specified as the argument of the sort method.

49 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."); }

50 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.

51 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); }

52 Functions & Objects There are normally 2 good places where you can place a function: – in the of the HTML document, or – on the JavaScript file that is linked to the document through the 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.

53 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 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.

54 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.

55 Calling a Function with 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);

56 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.

57 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.

58 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

59 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.

60 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.

61 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().

62 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;

63 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

64 Example Create 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.

65 Example Create 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();

66 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.

67 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.

68 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.

69 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!");

70 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; }

71 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:

72 Conditional Operators OperatorExplanation ==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

73 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. OperatorExplanation ||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

74 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); }

75 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" }

76 Switch Statement Components 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.

77 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.

78 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 }

79 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.

80 While Loops Construction while (var<=endvalue) { code to be executed }

81 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).

82 Do-While Loops Construction: do { code to be executed } while (var<=endvalue);

83 JavaScript Example Implementations

84 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)

85 Time Display <!-- now = new Date(); localtime = now.toString(); utctime = now.toGMTString(); document.write(" Local time: " + localtime + ” "); document.write(" UTC time: " + utctime); hours = now.getHours(); mins = now.getMinutes(); secs = now.getSeconds(); document.write(" "); document.write(hours + ":" + mins + ":" + secs); document.write(" "); --> JavaScript uses a Date() function to get the current date and time from the server – we store it in a variable called now universal time (UTC) is calculated by calling string transformation.toGMTString() JavaScript stores dates as the number of miliseconds since january 1 st, 1970. Fortunately it includes a number of functions to convert date and times in various ways. JavaScript stores dates as the number of miliseconds since january 1 st, 1970. Fortunately it includes a number of functions to convert date and times in various ways.

86 Connected Series of Windows (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" ); }

87 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');”

88 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

89 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.

90 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

91 Roll-Over Using 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" onmouseover="document.images[1].src='images/T3.gif';" onmouseout="document.images[1].src='images/T1.gif'" /> document.images [0] as Link document.images[1]

92 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.

93 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

94 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();

95 SlideShow function 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 image if (numslides==0) { imgs[i].style.display="block"; } else { imgs[i].style.display="none"; } imgs[i].onclick=NextSlide; numslides++; }

96 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"; }

97 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 tags): – window.onload=MakeSlideShow;

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


Download ppt "COM621 – Interactive Web Development Lecture 3 – JavaScript & DOM."

Similar presentations


Ads by Google