1.16k likes | 1.21k Views
7.1 JavaScript Execution Environment - The JavaScript Window object represents the window in which the browser displays documents - The Window object provides the largest enclosing referencing environment for scripts - Its properties are visible to all scripts in the
E N D
7.1 JavaScript Execution Environment - The JavaScript Window object represents the window in which the browser displays documents - The Window object provides the largest enclosing referencing environment for scripts - Its properties are visible to all scripts in the document (they are the globals) - Other Window properties: - document - a reference to the Document object that the window displays - frames - an array of references to the frames of the document - forms - an array of references to the forms of the document - Each Form object has an elements array, which has references to the form’s elements - Form elements are usually referenced by name, but this is a problem for radio buttons
7.2 The Document Object Model - Under development by w3c since the mid-90s - DOM 2 is the latest approved standard - The DOM is an abstract model that defines the interface between HTML documents and application programs - It is an OO model - document elements are objects - A language that supports the DOM must have a binding to the DOM constructs - In the JavaScript binding, HTML elements are represented as objects and element attributes are represented as properties e.g., <input type = "text" name = "address"> would be represented as an object with two properties, type and name, with the values "text" and "address" - The property names in JavaScript are usually just lowercase versions of the corresponding HTML attribute names
7.3 Events and Event Handling - In event-driven programming, code is executed as a result of a user or browser action - An event is a notification that something specific has occurred, either with the browser or an action of the browser user - An event handler is a script that is implicitly executed in response to the appearance of an event - Because events are JavaScript objects, their names are case sensitive - all are in lowercase only - Event handlers can be specified in two ways: 1. An HTML tag can have an attribute that is associated with a specific event and the handler code, in the form of a string literal, is assigned to the attribute 2. The handler can be implemented as a function and the function’s name is assigned to the object property associated with the event at the HTML element - Don’t use document.write in an event handler, because the output may go on top of the display
7.4 Events, Attributes, and Tags Event Tag Attribute abort onAbort blur onBlur change onChange click onClick error onError focus onFocus load onLoad mouseout onMouseOut mouseover onMouseOver reset onReset resize onResize select onSelect submit onSubmit unload onUnload - The same attribute can appear in several different tags e.g., The onClick attribute can be in <a> and <input> --> SHOW Tables 7.1 and 7.2 - Specifying a handler by assigning the attribute: onClick = "alert('Mouse click!');" onClick = "myHandler();"
7.5 Using the load and unload Events - These events are triggered when the loading or unloading of a document is completed <!-- This is ch7_1.html --> <html> <head> <title> onLoad and onUnload event handlers </title> <script language = "JavaScript"> // The onload event handler function load_hello () { alert("Your page has been loaded - hello!"); } // The onunload event handler function unload_goodbye () { alert("Your page is now unloaded - goodbye!"); } </script> <head> <body onLoad = "load_hello();" onUnload = "unload_goodbye();"> </body> </html>
7.6 Event Handlers for Button Events • - Radio buttons • <input type = "radio" name = "button_group" • value = "blue" onClick = "handler()"> • - Can’t use the element’s name to identify it, • because all buttons in the group have the same • name • - Must use the DOM address of the element, e.g., • var radioElement = document.myForm.elements; • - Now we have the name of the array of elements • of the form • for (var index = 0; • index < radioElement.length; index++) { • if (radioElement[index].checked) { • element = radioElement[index].value; • break; • } • } • - NOTE: There is no error checking in this code • - Now, we can use a switch on element, as in • switch(element) { ...
7.6 Event Handlers for Button Events (continued) --> SHOW ch7_2.html - Event handlers can be specified by assigning them to properties of the JavaScript objects associated with the HTML elements - The property names are lowercase versions of the attribute names - If the event handler is a function, just assign its name to the property, as in document.myForm.elements[0].onclick = myHandler; - This sets the handler for the first element in the form -This would need to follow both the handler function and the HTML form - If this is done for a radio button group, each element of the elements array must be assigned --> SHOW ch7_2x.html
7.6 Event Handlers for Button Events (continued) - Disadvantage of specifying handlers by assigning them to event properties is that there is no way to use parameters - The advantage of specifying handlers by assigning them to event properties are: 1. It is good to keep HTML and JavaScript separate 2. The handler could be changed during use 7.7 Checking Form Input - A good use of JavaScript, because it finds errors in form input before it is sent to the server for processing - Things that must be done: 1. Detect the error and produce an alert message 2. Put the element in focus (the focus function) 3. Select the element (the select function)
7.7 Checking Form Input (continued) - The focus function puts the element in focus, which puts the cursor in the element document.myForm.phone.focus(); - The select function highlights the text in the element - To keep the form active after the event handler is finished, have it return false - Example – comparing passwords - If a password will be used later, the user is asked to type it in twice - The program must verify that the second typing of the password is the same as the first - The form just has two password input boxes to get the passwords and Reset and Submit buttons - The event handler is triggered by the Submit button
7. Checking Form Input (continued) - Handler actions: 1. If no password has been typed in the first box, focus on that box and return false 2. If the two passwords are not the same, focus and select the first box and return false if they are the same, return true --> SHOW ch7_3.html & its output - Another Example – Checking the format of a name and phone number - The event handler will be triggered by the change event of the text boxes for the name and phone number - If an error is found in either, an alert message is produced and both focus and select are called on the text box element - Another event handler is used to produce a thank you alert message when the input is ok
7.8 The navigator object • - Indicates which browser is being used • - Two useful properties • 1. The appName property has the browser’s name • 2. The appVersion property has the version # • - Microsoft has chosen to set the appVersion of IE5 • to 4 (?) • 7.9 Event Propagation • - As with exception handling, it is valuable to be • able to propagate events, so that one handler can • deal with events from more than one source • - The DOM 2 model of event propagation bubbles • events upward in the hierarchy, toward the • document or window level • - There are two categories of events – those that • bubble and those that don’t
7.9 Event Propagation (continued) • - Events that are allowed to bubble can be handled • at the element level, but they also bubble upward • unless told not to with stopPropagation • - IE5 and NN6 support bubbling, but NN4 does not
Chapter 8 Sebesta: Programming the World Wide Web
8.1 Browser Support for Dynamic Documents - IE5 supports most of CSS and dynamic HTML standards - IE5 also supports some non-standard things, such as advanced visual effects - NN4 supports Netscape JSS and layers, but few of the standard things (except CSS-P) - NN6 support for standards is similar to that of IE5 - A dynamic HTML document is one whose tag attributes, tag contents, or element style properties can be changed after the document has been and is still being displayed by a browser - To make changes in a document, a script must be able to address the elements of the document using the DOM addresses of those elements - NN4 uses a non-standard DOM structure, which makes the few changes it can make more difficult
8.1 Browser Support for Dynamic Documents (continued) - The standard DOM allows base element addresses to be gotten through their names, but the NN4 DOM does not support this - Example: <body> <form id = "myForm" > <input type = "button" id = "onButton"> … </form> </body> - The standard DOM address of the button can be gotten with the getElementById method, as in document.getElementById("onButton").style - For NN4, the whole path must be included, as in document.myForm.onButton - To build scripts that work for both NN4 and the standard, you must determine whether NN4 is being used and set the DOM address accordingly
8.1 Browser Support for Dynamic Documents (continued) - The script can determine the browser using the navigator object if ((navigator.appName == "Netscape" && (parseInt(navigator.appVersion) == 4)) dom = document.myForm.onButton; else dom = document.getElementById("onButton").style; - HTML elements are sometimes referenced through a value of a variable or a function parameter, rather than through its id - In these cases, the DOM address must be built for NN4 with eval and string catenation, as in function changer(elemId) { if ((navigator.appName == "Netscape") && (parseInt(navigator.appVersion) == 4)) dom = eval('document.' + elemId); else dom = document.getElementById(elemId).style; ... }
8.2 Element Positioning - This is CSS-P, not DHTML - Without CSS-P, the only ability to position elements in the display of a document is with tables - CSS-P is completely supported by IE5 and NN6, and partially by NN4 - The position of any element can be dictated by the three style properties: position, left, and top - The three possible values of position are absolute, relative, and static - Absolute Positioning <p style = "position: absolute; left: 50px; top: 100 px;"> --> SHOW absPos.html and Figure 8.1 - If an element is nested inside another element and is absolutely positioned, the top and left properties are relative to the enclosing element
8.2 Element Positioning (continued) --> SHOW absPos2.html and Figure 8.2 - Relative Positioning - If no top and left properties are specified, the element is placed exactly where it would have been placed if no position property were given - But it can be moved later - If top and left properties are given, they are offsets from where it would have placed without the position property being specified - If negative values are given for top and left, the displacement is upward and to the left --> SHOW relPos.html Figure 8.3 - Static Positioning - The default value if position is not specified - Neither top nor left can be initially set, nor can they be changed later
8.3 Moving Elements - If position is set to either absolute or relative, the element can be moved after it is displayed - Just change the top and left property values with a script --> SHOW mover.html & Figures 8.4 and 8.5 8.4 Element Visibility - The visibility property of an element controls whether it is displayed - The standard values are visible and hidden - The NN4 values, show and hide, are used internally, though NN4 recognizes the std. values - Suppose we want to toggle between hidden and visible, and the element’s DOM address is dom if (dom.visibility == "visible" || dom.visibility == "show") dom.visibility = "hidden"; else dom.visibility = "visible"; --> SHOW showHide.html
8.5 Dynamic Colors and Fonts - Supported by IE5 and NN6 - Background color is controlled by the backgroundColor property - Foreground color is controlled by the color property - Can use a function to change these two properties - Let the user input colors through text buttons - Have the text button elements call the function with the element address and the new color Background color: <input type = "text" size = "10" name = "background" onchange = "setColor('background', this.value)"> - The actual parameter this.value works because at the time of the call, this is a reference to the text button
8.5 Dynamic Colors and Fonts (continued) function setColor(where, newColor) { if (where == "background") document.body.style.backgroundColor = newColor; else document.body.style.color = newColor; } --> SHOW dynColors.html - Changing fonts - Can change the font properties of a link by using the mouseover and mouseout events to trigger a script that makes the changes - In this case, we can put the script in the HTML onmouseover = "this.style.color = 'blue'; this.style.font = 'italic 16pt Times';" onmouseout = "this.style.color = 'black'; this.style.font = 'normal 16pt Times';” --> SHOW dynLink.html and Figures 8.6 & 8.7
8.6 Dynamic Content - The content of an HTML element is addressed with the value property of its associated JavaScript object --> SHOW dynValue.html and Figure 8.8 8.7 Stacking Elements - The top and left properties determine the position of an element on the display screen, which is a two-dimensional device - We can create the appearance of a third dimension by having overlapping elements, one of which covers the others (like windows) - This is done with the z-index property, which determines which element is in front and which are covered by the front element - The JavaScript variable associated with the z-index property is zIndex - Element stacking is supported by IE5, NN6, & NN4
8.7. Stacking Elements (continued) - The stacking order can be changed dynamically - Make the elements anchors, so they respond to mouse clicking - The href attribute can be set to call a JavaScript function by assigning it the call, with 'JAVASCRIPT' attached to the call code <a href = "JAVASCRIPT:fun()"> - The function must change the zIndex value of the element - A call to the function from an element sets the zIndex value of the new top element to 10 and the zIndex value of the old top element to 0 - It also sets the current top to the new top --> SHOW stacking.html and Figures 8.9, 8.10, & 8.11
Chapter 9 Sebesta: Programming the World Wide Web
9.1 Introduction - Applets are relatively small Java programs whose execution is triggered by a browser - The purpose of an applet is to provide processing capability and interactivity for HTML documents - The ‘standard’ operations of applets are provided by the parent class, Applet public class class_name extends Applet { … } - The Applet class descends directly from Panel, which descends directly from Component - The use of applets has been restrained by the lack of support for Swing - Specifically, the JVM that comes with NN4 does not support Swing, so NN4 users cannot execute applets that use it - Use of applets is still widespread, and there is heavy use in intranets, where all browsers can be required to support the latest JVM
9.1 Introduction (continued) - Applets are an alternative to CGI and embedded scripts - Comparisons: - CGI is faster than applets and JavaScript, but it is run on the server - JavaScript is easier to learn and use than Java, but less expressive - Java is faster than JavaScript - Java graphics are powerful, even with just AWT (JavaScript has none) - JavaScript does not require the additional download from the server that is required for applets - Java may become more of a server-side tool, in the form of servlets, than a client-side tool
9.2 Primary Applet Activities - Browser actions: a. Download and instantiate the applet class b. Call the applet’s init method c. Call the applet’s start method - This starts the execution of the applet - When the user takes a link from the document that has the applet, the browser calls the applet’s stop method - When the browser is stopped by the user, the browser calls the applet’s destroy method - Every applet must override at least one of the three methods, init, start, or paint (paint is inherited from Component)
9.3 The paint Method - Always called by the browser (not the applet itself) - Takes one parameter, of class Graphics, which is defined in java.awt - The parameter object is created by the browser - The protocol is: public void paint(Graphics grafObj) { … } - The simplest use of paint is to display text, using the drawString method - Three parameters: a String literal, the x coordinate of the left end of the string, and the y coordinate of the base of the string (the coordinates are given in pixels)
9.3 The paint Method (continued) /* welcomeMessage.java An applet to illustrate the display of a string */ import java.applet.Applet; import java.awt.*; public class welcomeMessage extends Applet { public void paint(Graphics grafObj) { grafObj.drawString( "Welcome to my home page!", 50, 50); } } - Font Control - The Font class, defined in java.awt.Font, has three variables that specify the font name, style, and size of the font used by drawString The size parameter is in points - The styles are PLAIN, BOLD, and ITALIC - To change the font, create a Font object with the desired parameters and set it with the setFont method of Graphics, which takes a Font parameter
9.3 The paint Method (continued) /* welcomeMessage_2.java An applet to illustrate the display of a string in specific font, font style, and font size */ import java.applet.Applet; import java.awt.*; public class welcomeMessage_2 extends Applet { Font myFont = new Font("TimesRoman", Font.ITALIC, 24); public void paint(Graphics grafObj) { grafObj.setFont(myFont); grafObj.drawString( "Welcome to my home page!", 50, 50); } } 9.4 The <object> Tag - Used to specify an applet in an HTML document - Creates a space in the document display for applet output (like <img> does)
9.4 The <object> Tag (continued) <object codetype = "application/java" code = "applet_class_file" width = "applet display width" height = "applet display height"> </object> - The display width and height are in pixels - The applet_class_file is the compiled version <!-- ch9_2.html To test the applet, welcomeMessage_2 --> <html> <head> <title> Test welcomeMessage_2 </title> </head> <body> <object codetype = "application/java" code = "welcomeMessage_2.class" width = "500" height = "100"> </object> </body> </html>
9.4 The <object> Tag (continued) 9.5 Applet Parameters - Applets can be sent parameters through HTML, using the <param> tag and its two attributes, name and value - Parameter values are strings - e.g., <param name = "fruit" value = "apple"> - The applet gets the parameter values with getParameter, which takes a string parameter, which is the name of the parameter String myFruit = getParameter("fruit");
9.5 Applet Parameters (continued) - If no parameter with the given name has been specified in the HTML document, getParameter returns null - By checking the return value against null, a default value can be set - If the parameter value is not really a string (although parameters are all sent as strings), the value returned from getParameter must be converted, as in String pString = getParameter("size"); if (pString == null) mySize = 24; else mySize = Integer.parseInt(pString); - The best place to put the code to get parameter values is in init - Parameters are stored in instance variables
9.5 Applet Parameters (continued) <body> <object codetype = "application/java" code = "welcomeMessage_3.class" width = "500" height = "100"> <param name = "size" value = "35"> </object> </body> 9.6 Simple Graphics (AWT) - Coordinate system: (0, 0) is at theupper left corner - The methods that draw graphic figures are called through the Graphics object (the parameter to paint) - Lines are drawn with drawLine(x1, y1, x2, y2) - Draws a line from (x1, y1) to (x2, y2)
9.6 Simple Graphics (AWT) (continued) - Rectangles are drawn with drawRect and fillRect - Both take four parameters, the coordinates of the upper left corner of the rectangle and the width and height of the rectangle (width and height are in pixels) - Rectangles with rounded corners can be drawn with drawRoundRect and fillRoundRect - These two take two more parameters, which specify the numbers of horizontal pixels and vertical pixels in the rounding /* rectangles.java */ import java.applet.Applet; import java.awt.*; public class rectangles extends Applet { public void paint(Graphics grafObj) { grafObj.drawRect(10, 10, 80, 60); grafObj.fillRect(120, 10, 60, 80); grafObj.drawRoundRect(10, 120, 80, 60, 20, 30); grafObj.fillRoundRect(120, 120, 60, 80, 40, 40); } }
9.6 Simple Graphics (AWT) (continued) - 3D rectangles can be created with a 5th parameter, true (not pushed) or false (pushed) - Polygons are drawn with drawPolygon, which takes three parameters, two arrays of coordinates of edge endpoints, and the number of edges public void paint(Graphics grafObj) { int xCoordinates [] = {30, 50, 64, 64, 50, 30, 16, 16, 30}; int yCoordinates [] = {10, 10, 24, 44, 58, 58, 44, 24, 10}; grafObj.drawPolygon(xCoordinates, yCoordinates, 9); }
9.6 Simple Graphics (AWT) (continued) - drawPolygon can also take a single parameter, which is a Polygon object, whose constructor takes the same three parameters as drawPolygon - Ovals are like rectangles (same parameters) 9.7 Color - The Color class has predefined objects for common colors Color.white, Color.black, Color.gray, Color.red, Color.green, Color.blue, Color.yellow, Color.magenta, Color.cyan, Color.pink, Color.orange
9.7 Color (continued) - An object for any color can be created with the Color constructor, as in Color myColor = new Color(x, y, z); - The color of the Graphics object can be set with setColor, as in grafObj.setColor(Color.cyan); - The foreground and background colors of the applet display are set with methods from Panel 9.8 Interactive Applets - Applet extends Panel, which extends Component - The Component class includes GUI components as subclasses - Panel objects are used to enclose GUI components - The Applet class is itself a GUI component
9.8 Interactive Applets (continued) • - Labels • - Label objects are static strings • Label labl1 = new Label("Click this button"); • - Plain buttons • Button myButton = new Button( • "Click here for fun"); • - Checkboxes • Checkbox box1 = new Checkbox("Beer"); • Checkbox box2 = new Checkbox("Pretzels"); • - Radio buttons – just checkboxes in a • CheckboxGroup • pop = new CheckboxGroup(); • Checkbox box1 = new Checkbox("Coke", pop, • true); • Checkbox box2 = new Checkbox("Pepsi", pop, • false);
9.8 Interactive Applets (continued) • - Text boxes • TextField myName = new TextField(30); • - A Panel object is needed to contain components • Panel myPanel = new Panel(); • myPanel.setBackground(Color.yellow); • myPanel.setForeground(Color.blue); • myPanel.add(box1); • - Layout Managers • - Default is FlowLayout – just like a browser • - GridLayout is like HTML document panels • Panel buttonPanel = new Panel(); • buttonPanel.setLayout( • new GridLayout(3, 2, 10, 10)); • - Three rows of two components each, with 10 • pixels between the components • --> SHOW Pizza.java
9.8 Interactive Applets (continued) - The Java Event Model - Related to the JavaScript event model - Event handlers are called event listeners - Connection of an event to a listener is through event listener registration - Done with a method of the class that implements the listener interface - The panel object that holds the components can be the event listener for those components - Event generators send messages (call methods) to registered event listeners when events occur - Event handling methods must conform to a standard protocol, which comes from an interface - We only consider the “semantic” events (there are also “low-level” events)
9.8 Interactive Applets (continued) - Semantic Events ActionEventclick a button, select from a menu or list, or type the enter button in a text field AdjustmentEvent adjust a scroll bar ItemEventselect a checkbox or list item TextEventchange the contents of a text field or text area - For these four events, we have the following interfaces and handler methods: Interface Handler method ActionListener actionPerformed AdjustmentListener adjustmentValueChanged ItemListener itemStateChanged TextListener textValueChanged - The methods to register the listener is the interface name with “add” prepended - e.g., button1.addActionListener(myPanel);
9.8 Interactive Applets (continued) - Event handlers get an event object as a parameter, through which information about the event can be gotten with methods, such as getState - e.g., button1.getState() returns true if the button is on, false otherwise - When an event handler has just a few lines, it can be implemented as an instance of an anonymous nested class - Example: a button that sets a font button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { text.setFont(newFont); } }); --> SHOW RadioB.java
9.9 Concurrency in Java - Our only interest in concurrency here is to illustrate how threads can be used to create animation in an applet - A thread of control is a sequence of program points reached as execution flows through the program - A nonconcurrent program has a single thread of control; a concurrent program has more than one - Java supports lightweight concurrency through its threads - The concurrent program units in Java are methods named run, whose code can be in concurrent execution with other run methods and with main - There are two ways to implement threads, as a subclass of Thread and by implementing the interface Runnable - The Thread class - Two essential methods, run and start - run is the concurrent method - start tells the run method to begin execution
9.9 Concurrency in Java (continued) - All Java programs run in threads - For applications, when execution is to begin, a thread is created for main and its start method is called - For applets, when the browser finds one, it creates a thread and calls the applet --> SHOW Names.java, output, delayer, and output - Thread States - New - created, but start hasn’t been called - Runnable or ready - ready to run, but is not currently running - In the ready queue - Running - actually has the processor - Blocked - was running, but is not now, because it was interrupted (i/o, end of time slot, gave up its time slot, etc.) - Dead - either its stop was called or its run method completed its execution
9.9 Concurrency in Java (continued) - Thread methods - yield is a request from the running thread to give up the processor; a static method - sleep(time) - blocks the thread for at least as many milliseconds as the parameter specifies; also a static method - sleep can throw InterruptedException, which must be caught - stop - now deprecated, because of safety problems - Now we override it and just set the thread reference to null (destroys the thread) - An example - an animated digital clock - An applet must implement Runnable, its start and stop methods, and the repaint method of Graphics - repaint is called after the applet display has changed
9.9 Concurrency in Java (continued) - Our applet is named Clock - Its start method creates a new Thread object, sending this to the constructor. This sets the new Thread object’s target to the Clock object, which forces the thread to get its run method from the Clock object - After creating the Thread object, start is called to start its execution - The run method sets a variable to the currently executing thread, and then loops as long as the thread is clockThread - The loop gets the new time with a new Date object and repaints the display every second
Chapter 10 Sebesta: Programming the World Wide Web
10.1 Introduction - SGML is a meta-markup language - Developed in the early 1980s; ISO std. In 1986 - HTML was developed using SGML in the early 1990s - specifically for Web documents - Two problems with HTML: 1. Fixed set of tags and attributes - User cannot invent new tags or attributes - So, the given tags must fit every kind of document, and the tags cannot connote any particular meaning 2. There are no restrictions on arrangement or order of tag appearance in a document - One solution to the first of these problems: Let users define their own tags (with assigned meanings) (i.e., design their own “HTML”s using SGML)