Dynamic Web and Internet Technologies lecture 3 Introduction
Dynamic Web and Internet Technologies lecture 3 Introduction to scripting Java. Script Modifying the page Reacting to events BIT 3100
Refferences Core Java. Script 1. 5 Reference http: //developer. mozilla. org/en/docs/Core_Java. Script_1. 5_Reference A re-introduction to Java. Script http: //developer. mozilla. org/en/docs/A_reintroduction_to Java. Script Reference http: //www. w 3 schools. com/jsref/ Java. Script Tutorial http: //www. w 3 schools. com/js/ BIT 3100
Why Scripting? Scripting languages are simple (usually) interpreted programming languages. Scripts are used on client side: program to be run on client machine by browser and on server side: program to be run on server with results sent to browser. We concentrate on client-side scripts. We can use these to add interactivity to Web pages. BIT 3100
Client-side scripting Scripts can be embedded in the web page. Most popular scripting language is Java. Scripts can access and change the contents of a Web page. Assist in completion and checking of forms. Provide user control with client-side of page appearance and content. Page is no longer static and fixed. BIT 3100
Java. Script Is Usually implied in DOM scripting i. e programmatically accessing the Document Object Model DOM Scripting has its roots in DHTML Strictly used with the Web BIT 3100
Javascript Basics Java. Script is a scripting language originally developed by Netscape (there is now a version developed by Microsoft called Jscript) It allows you to add interactivity to your web pages Java. Script scripts are embedded directly into web pages BIT 3100
Javascript Basics They can be in the <head> or in the <body> of the page depending on what you want the script to do Javascript involves the scripts and the objects manipulated by the scripts- both will be explained below. Some of the ways that Javascript can be used on a page: Determining the type of browser that is accessing your page and direct it to the proper version of the page Checking the information that is entered into a form Performing simple calculations without using the server Adding date and time information to a page in real time Changing images on a page in response to user actions BIT 3100
Java. Script Not to be confused with Java, but some similar syntax. Much simpler - not fully object-oriented. Not compiled - interpreted. Interpreter reads and executes Java. Script, not bytecode. Weakly typed => Don’t have to declare types. BIT 3100
Java. Script The Structure: The Java. Script code goes into to the body of the html document at the point where it is to be displayed. It is inserted within a pair of html <script> tags. The opening script tag includes the attribute language="Java. Script" to distinguish it from other possible scripting languages (such as JScript or VBScript). The code is embedded within html comment tags (<!--. . . -->), to hide it from older browsers that can't interpret Java. Script Code –otherwise the code will show up on the web page when viewed by non. Java. Script enabled browsers. BIT 3100
Example - Last Updated Script <! Doctype html> <head></head> <body> <script language="Java. Script"> <!-- Hide Java. Script. . . var Last. Updated = document. last. Modified; document. writeln ("This page was last updated " + Last. Updated); // End Hiding --> </script> </body> </html> BIT 3100
Java. Script example The same code could have been written in one line, like this: document. writeln ("This page was last updated"+document. Last Modified); "document. writeln( )" is a predefined Javascript method that writes whatever is within the parentheses onto the displayed web page. The portion within the quotation marks can contain any userdefined value such as "Last Updated" or "Last Modified". "document. last. Modified" is a Java. Script property which evaluates to the date and time that the html source document was last opened and altered. " + " is an operator which is used to connect or "concatenate" the two values within the parentheses. BIT 3100
Java. Script example Now for the two-line version of the code: var Last. Updated = document. last. Modified; document. writeln ("This page was last updated " + Last. Updated); The first line of this version is a variable statement. " var " signals that a new user-defined variable is being created. Last. Updated is an arbitrary (user-defined) name for the variable, essentially it is used as a shortcut for the "document. last. Modified" property in the subsequent statement. BIT 3100
Java. Script and Comments Sometimes recommended to place Java. Script inside HTML comments to "hide" it from browsers or applications that can't interpret it: HTML Comment delimiter Java. Script comment <script type="text/javascript"> <!-// My first Java. Script document. writeln("Hello World") // --> </script> BIT 3100
Java. Script Syntax Java. Script syntax is similar to Java but simpler. Key difference is we don't declare types: it is "weakly typed". But use "var" to declare variables. Also don't need to end statements with a semicolon Java. Script assumes that a new line means a new statement. var greeting="hello" var name =“Willy" document. writeln(greeting + " " + name) BIT 3100
Input from user Can get input from user simple dialogue boxes (prompt, confirm, alert) Example: var name=prompt(“what is your name”) document. writeln("<p> Hello " + name + ". ") document. writeln("I hope you like my page </p>") Note how HTML markup included in output BIT 3100
Loops and conditionals Java. Script has normal loop constructs (for, while etc) and conditionals. Example loop: - if – else statement var aname = prompt("What is your name? ") if(aname=="John") document. writlen("Hello. ") else if(aname=="Jean") document. writeln("Bonjour. ") else document. writeln("Who are you? ") BIT 3100
Java. Script functions Functions are easily defined. Usually place the script in head of document, and call it from body: <head> <script type=“text/javascript”> function greet(aname) { document. writeln(“Hello” + aname) } </script> </head> <body> <script type="text/javascript"> var yourname = prompt("What is your name") greet(yourname) </script> BIT 3100
Example- Using Images - Slide Show <html> <head> <script language=javascript> <!-- Hide from older browsers var slides = new Array("tropic. jpg", "trin 2. jpg", "cabo. jpg", "trin 3. jpg", "chess. jpg", "ncal. jpg") var this. Slide=0 function previous. Slide( ) { if (document. images && this. Slide > 0) { this. Slide = this. Slide -1 document. BIT 3100. src=slides[this. Slide] } } function next. Slide( ) { if (document. images && this. Slide < 5) { this. Slide = this. Slide +1 document. BIT 3100. src=slides[this. Slide] BIT 3100
Example- Using Images - Slide Show } } // End hiding --> </script> </head> <body> <center> <h 3><font color="#BF 5500"> BIT 3100 Slides</font></h 3> <img src="tropic. jpg" name=" BIT 3100"><p> <h 3> <a href = javascript: previous. Slide( ) > Previous</A> <a href = javascript: next. Slide( ) > Next</A> </h 3> </center> </body> </html> BIT 3100
Java. Script functions- Example This script introduces a new type of variable - an array. Arrays are used for storing multiple values or objects. In this example, six image objects are loaded into an array named "slides. " The first image listed in the array (tropic. jpg) can be reffered to as slides[0], the second image is slides[1], the third is slides[2], and so on. The second variable in the Slide Show script (this. Slide) is used as an index for the slides array. The variable's initial value is set to 0, so the initial image refered to by slides[this. Slide] would be slides[0] or tropic. jpg. BIT 3100
Java. Script functions- Example Two functions are created for this script: "next. Slide( )" changes the displayed image to the next image in the array; "previous. Slide( )" changes the displayed image to the previous image in the array. Both functions operate in a similar manner. The "next. Slide( )" function starts with a condition that checks to see if the browser understands image objects and also checks whether the current value of this. Slide is less than 5 (i. e. the index value of the last image). If the condition is true then "this. Slide" is increased by 1. The final statement - document. BIT 3100. src=slides[this. Slide] - instructs the Browser to search within the document for an image named “BIT 3100" and change the source to the new slide. Calling a Function from a link Rather than using "on. Click" or some other event handler, both functions are called directly from the html link. The generic code for this method of calling a function is: <a href = javascript: my. Function( ) >name. Of. Link BIT 3100
Components of Javascript Objects: Javascript is object-oriented These are parts of the web browser that can be manipulated as whole entities Another way to think of an object is as a black box which contains a chunk of information or data A <window> is an example of a javascript object. However, it has qualities which are also objects (with their own qualities). Here is an relationships: example BIT 3100 of objects and their
Document Objects Using Java. Script can access and modify many of the “objects” in a document. Containment Hierarchy of document objects Window etc frame link document anchor text form radio BIT 3100 location applet image checkbox etc
Document Objects This is a hierarchy of objects that illustrates their relationships (this illustration doesn't include them all) This is a version of a document object model Understanding these relationships will be useful when you are creating your own javascripts When you create scripts, you want to arrange the proper objects in the proper order BIT 3100
Document methods and properties Like in Java, each object has methods and properties/values: document. writeln(“hello”) document. bg. Color=“blue” Use document’s writeln method. . Change document’s bg. Color property. For serious Java. Script have to look up properties/methods available. BIT 3100
Document properties Properties: Objects have properties, or qualities that define them Think of properties as the information in the object that can be read, changes, or otherwise directly accessed Properties typically define the visual appearance of the object They also define the current settings of the object Normally, we will assign properties with the attributes placed in the HTML markup Here's an example: A web page is an object which is called a document One property of a document is its background color BIT 3100
Document properties The property can be expressed on dot. syntax as: document. bgcolor If you want to change this color, you specify a value for this property: document. bgcolor="cyan" A property can be used with several different objects Also, a property of an object can be an object with its own properties BIT 3100
Document methods Methods are built-in actions or functions that an object can perform. As with properties, what built-in methods an object can perform differs for every object. Again, let's visit the document and text objects and look at some of their methods: Document Text clear() close() open() write() blur() focus() select() First, note that methods have a trailing set of parentheses after them. That is standard notation, but realize that some methods take arguments, or values, inside the parentheses, while others do not. BIT 3100
Document methods We will look at both kinds. var text = "This is a new page" document. open() document. write(text) document. close() These three document methods are typically used in conjunction to write new content to a page. The open() function opens a layout stream for writing, write() writes to it and close() closes the writing stream. [Note: document method open() does not open a new window that is the job of the window method called open(). ] BIT 3100
Event Handlers Java. Script is an programming language. object-oriented event-driven This means that Java. Script code responds to userinitiated events by creating and manipulating objects (and their data values). Most objects in the DOM have specific events to which they can respond. For each of these events, there is a corresponding event handler which catches the event and points the script to what it should do in response. To respond to an event you need to register an event handler in your HTML code. BIT 3100
Event Handlers Here's how the on. Mouse. Over= event handler is registered in a link object: <a href="somefile. html" on. Mouse. Over="some. Function(); return true">*text or image here*</a> When a mouse-over event occurs for this particular link object, the Java. Script function "some. Function( )" is called. This function would be one that you as the script-writer defined elsewhere in the page. This event handler is peculiar in that it requires a "return true" statement at the end in order to complete successfully (on. Submit = and on. Mouse. Out= require this as well). BIT 3100
Event Handlers Event handler User action on. Abort Stopped loading the page on. Blur Left the object on. Changed the object on. Clicked on the object on. Error while script is executing on. Focus Made object active on. Load Object has loaded on. Mouseove Cursor passed r over the object on. Mouseout Cursor moved off the object on. Selected the object on. Submitted a form on. Unload Left the page BIT 3100
Form Validation Java. Script widely used to validate and "autocomplete" forms before they are submitted. The "onsubmit" event handler is used to validate. We write a Java. Script function that checks the form contains all the necessary data, and prompts user for missing entries. Function should return "false" if data is incomplete. This stops form being submitted. BIT 3100
Form Validation In head In body <script language=“Java. Script”> function check() { if(document. f 1. yourname. value=“”) { alert(“Enter your name”); return(false); } else return(true); } …. <form id=“f 1” onsubmit=“return check()”; > <input type=“text” name=“yourname”> BIT 3100
Java. Script Statements <html> <head><title>My Page</title></head> <body> <p> <a href="myfile. html">My Page</a> <a href="myfile. html" on. Mouseover="window. alert('Hello'); "> My Page</A> </p> Java. Script written An Event inside HTML </body> </html>
Example Statements <script language="Java. Script"> window. prompt('Enter your name: ', ''); </script> Another event <form> <input type="button" Value="Press" on. Click="window. alert('Hello'); "> </form> Note quotes: " and '
HTML Forms and Java. Script is very good at processing user input in the web browser HTML <form> elements receive input Forms and form elements have unique names Each unique element can be identified Uses Java. Script Document Object Model (DOM)
Naming Form Elements in HTML <form name="addressform"> Name: <input name="yourname"> Phone: <input name="phone"> Email: <input name="email"> </form>
Forms and Java. Script document. formname. elementname. value Thus: document. addressform. yourname. value document. addressform. phone. value document. addressform. email. value
Using Form Data Personalising an alert box <form name="alertform"> Enter your name: <input type="text" name="yourname"> <input type="button" value= "Go" on. Click="window. alert('Hello ' + document. alertform. yourname. value); "> </form>
Tips Check your statements are on one line Check your " and ' quotes match Take care with capitalisation Lay it out neatly - use tabs Remember in the workbook denotes a continuing line Be patient Presentation slides adapted from scom. hud. ac. uk/scomsjw/Web%20 Authoring%20 Module/Lecture%20 Slides/introjs. ppt
Referencing Objects In your scripts, you will frequently be referencing objects (remember: Java. Script is an object-oriented language). The DOM hierarchy provides a road map of how to refer to any particular object via the dot syntax. This is how you reference the document object: window. document or document Since there is only one window object, we can leave off the "window" reference and the browser still knows which document we are talking about (Note: this changes when there are frames). BIT 3100
Referencing Objects Now, suppose you have the following html code: <body> <form name="boxes"> Enter first name: <input type="text"name="f. Name"> Enter last name: <input type="text" name="l. Name"> </form> </body> How would you reference the first text entry box? One way is: document. boxes. f. Name BIT 3100
Referencing Objects Look back to the DOM hierarchy and you will see that to get from the top window to a text object you must follow this path: window --> document --> form --> text, or using dot syntax: window. document. form. text. (Or just document. form. text. ) However, as there can be more than one form in a document and more than one text field in a form, we cannot simply use "form" and "text" to cite them Instead, we should name the form and text boxes and cite them by their names, which leads to (leaving off the optional "window" reference): document. boxes. f. Name to reference the first text entry box. BIT 3100
Document Object Model Standards have been developed for how we refer to elements of the page. i. e, allowed methods and properties. These standard methods define the "Document Object Model". We will start with the simplest and most widely supported version ("level 0"). It allows us to access and modify most, but not all elements of the page. It is now strictly superceded by the W 3 C standard "level 1" and "level 2" DOM BIT 3100
Referring to Document Objects (DOM 0) Each object has properties allowing us to access the lower level objects in the hierarchy. e. g. , document. forms returns an array of forms in the document. Normally an array of objects is returned, and we access a specific one (e. g. , first form) using array subscripting. document. forms[0] We can access the input elements using "elements": document. forms[0]. elements[0] Example BIT 3100
DOM 0 We can also access elements by name/id. <form id="form 1" …. > <input type="text" name="text 1" …> </form> Use document. form 1. text 1. value BIT 3100
DOM 1 DOM 0 is now strictly superceded. If possible, use DOM 1 (or DOM 2). DOM 1 has a set of very general methods for accessing any element on the page. E. g. , document. get. Element. By. Id(ID) document. get. Elements. By. Tag. Name(Name) Also general properties such as "first. Child" and "node. Value". BIT 3100
DOM 1: Example <script type="text/javascript"> function Change. Title(text){ document. get. Element. By. Id('t 1'). first. Child. node. Value = text } </script>. . . <h 1 id="t 1"> Old Title </h 1> <form action=""> <p> <input type="button" value="Change Title" onclick="Change. Title('New Title')"/> </p> BIT 3100
Summary Java. Script is interpreted language which can be embedded in web pages. Can be used to add simple interactivity. Can modify bits of document (document objects), get input from user, and react to simple events. Often used to validate form input. BIT 3100
Assignment Create a good User Login page using Javascript to pick the correct values and redirect to another page if correct or wrong values are entered. This page should reference to you group websites Do research on DOM HTML DOM XML DOM 1 & 2 Hand in Two weeks from today…. 24/10/2012 BIT 3100
- Slides: 51