|
Dynamic HTML with Internet Explorer 4 |
|||||
|
Lesson 1 Introducing Dynamic HTML Origins Foundations of Dynamic HTML Dynamic HTML is a development of the 'traditional' HTML we already use to create Web pages of all kinds. HTML stands for HyperText Markup Language, and is designed to be a standard way of representing information so that many different types of client browser can display it. HTML 3.2 is the latest standard to be awaiting final ratification by the World Wide Web Consortium. Since this standard was proposed, more additions continue to be made to new browsers—over and above the requirements to meet the standard. In fact, the standard itself is now in danger of being completely overtaken before it ever reaches the stage of final ratification. Even though Dynamic HTML, also know as HTML 4.0, is not that different from HTML 3.2, there are several subtle changes that require a new standard to be defined. These standards are likely to be accepted by W3C, but considering 3.2 is still to be ratified, it could take a little while. Hopefully there should be less need for new tags and new attributes as a general framework has been established and changes might only need to be made to the scripting languages from now on. Therefore HTML 4.0 should see the standard settling down at long last. Only once there is a stable standard that the major companies adhere to, do we have any chance of achieving a fully standardized and platform-independent way of viewing information from across the planet. You can download full specifications of Microsoft's proposals for Dynamic HTML from: http://www.microsoft.com/sitebuilder/workshop/author/dhtml What's new in Dynamic HTML
Getting Started in Dynamic HTML In this course, I will be assuming that you already have some background in two areas:
You will also need to install Internet Explorer 4.0 on your system. You can do this from http://www.microsoft.com/ie/ie40. The installation uses Microsoft's new Active Setup, which allows you to perform the install over the Internet. Of course, with a 33.6 or X2 modem, this could take quite a while. (Word of advice - save the installation files in case you have to reinstall the browser.) But, Microsoft has download sites all around the world. You can choose to perform the basic installation, which will give you the IE4 browser and a few other tools. This is all you will need for this course. For things such as the Active Desktop or Front Page Express HTML Editor, you will need to choose a more complete installation. (Word of advice - go for the whole enchilada. There is so much cool stuff there, that you won't want to miss out.) |
|
||||
|
|
|
||||
|
A ssignment 1For the first week, you should become familiar with the new environment of IE 4.0. Once you have it installed, try out some of the DHTML samples on the Microsoft site. If you find something you like, or think is cool, feel free to post the URL here. Later this week, I will try to post some of the cool sites that I have found as well. If you aren't very comfortable with scripting than this is your chance to run through the tutorials. I will be more than happy to answer any questions.
========== End of Lesson and assignment 1 =========== |
|
||||
Lesson 2 - Style Sheets, Absolute Positioning and Z-Order
Style sheets are a very important topic when learning about Dynamic HTML. You will use style sheets to separate the content of your documents from the presentation of that content. Through the use of style sheets, you can affect the look of any element on the page. You can also do so in a consistent manner. Say for example, you wanted all paragraph text to be 16 point Blue Comic Sans MS. Rather than applying a <FONT> tag to every paragraph block in your document, you can add a <STYLE> element which will set all paragraph text to these characteristics.
Where style sheets really come in handy is when you want to change the style of the document. Lets say that now instead of 16 point Blue Comic Sans MS, you want 12 point green Tahoma. Before style sheets, you have to go through and change every <FONT> tag manually. With style sheets, all you have to do it make the change in one place. And, as you will see later, with DHTML, you can make this change on-the-fly, maybe in response to some user's action.
Style sheets have three main advantages
All CSS declarations (they're officially termed 'selectors') follow the same format:
For example, to set all level 1 headings to blue, we could use either of the following statements:
This would make the <H1> text look like:
Style Sheet Applied
You can add Style sheets globally to your page in 3 ways:
You can also apply styles to individual block, by include a STYLE string within the tag surrounding the block, like this:
Lastly, you can define a "class," which is a set of styles, but is not assigned to a particular element type. This allows you to apply the style of the class to multiple types of elements.
There are six properties associated with style sheets that you will use to control the layout of the element on the page. These are:
left top z-index position visibility overflow
Left
and top represent the position of the element within its container. These values are stored as strings in units of pixels. For example, an element positioned 100 pixels from the top of its container would have a top property value of "100px" If you want the value as a number, without the px suffix, you should use pixelLeft and pixelTop.Z-index
represents the relative front-to-back position of this element with respect to other elements on the page. The higher the z-index value, the "closer" it will be to the user. This is a big change from previous versions of HTML. Prior to DHTML, the only way to overlap elements on the page was to play tricks with the margin values in CSS. Without CSS, overlapping is impossible. The direct positioning of elements on a web page allow you to create a "2.5D" layout.The position property controls what the top and left properties relate to. If the position property is set to absolute, then top and left will be relative to the container. A value of relative means that the placement origin will be at the position where the element would have been placed normally. A value of static means the values for top and left will be ignored.
The visibility property allows you to determine if an element is visibile to the user. A value of visible, the default, will show the element to the user. A value of hidden means that the element will not be shown to the user. By manipulating the property using script, you can make elements on the page appear and disappear.
The overflow property determines what should happen if the item contained in an element are bigger than the size of the element. A value of none means that the contents will be displayed in their entirety, regardless of the size of the contents. To count pixels, download ScreenRuler from
http://www.infinet.com/~microfox/srulerTxt.html . The unregistered version is a floating ruler that measures only pixels. Also, Allaire's HomeSite 3.x HTML text editor has a ruler that measures pixels.Now its your first chance to show everybody your web development expertise. Try to create a wonderful, artistic, beautiful web page that incorporates at least 5 of the following features. More kudos will go to students who use all seven elements. Remember appearance counts!
====== End Lesson and Assignment 2 =========
The object model is simply an interface between the Dynamic HTML source code in the page, and the browser software routines that create the window and fill it with the elements defined in the page. How it does this filling of the window, or rendering of the page, is unimportant. Dynamic HTML simply defines what the results should be, not how the processes should be implemented.
So, we can think of the browser's object model as being a way of connecting our pages to the browser. The object model exposes a range of objects, methods, properties and events that are present and active within the browser's software to the HTML and scripting code in the page. We can use these to communicate our wishes back to the browser, and therefore to the viewer. The browser will carry out our commands, and update the page(s) it displays.
If you aren't familiar with the items that make up an object model, here is a short definition....
Objects
Modern software design is very much concerned with objects. You can think of these as being self-contained parts of a program such as the browser, which carry out specific functions. The key is that they will usually store their own data, in their own format, and contain the code routines called methods (see the definition below)that are required to manipulate that data.
You can think of an object as being rather like a video recorder, in that we put the tapes in and set the timer, but all the work of recording and playing back goes on inside the black box. We just tell it to record or play back, and we don't need to know what's actually going on inside. The video recorder stores its data (our TV program) itself, in its own format, without us having to worry about how its doing it
Methods
Methods are an object's way of letting us do something with it. Our video recorder has methods built in that allow us to record or play back TV programs. The big advantage of having an object provide methods is that it takes away the worry of knowing what's going on inside the object. Rather than telling the video recorder the exact patterns of magnetism to lay down on the tape, and how to interpret the sound signal, we execute its Record method by pressing a couple of buttons.
Events
If methods are our way of telling an object what to do, events can be thought of as the object's way of telling us that something happened. It's likely that our trusty video recorder will have something we could term an EndOfTape event. This occurs when the end of the tape is reached, and will stop the motor to prevent it tearing the tape off the spool. This is the event being used internally to execute a Stop method of the tape-winding-motor object inside the video recorder.
However, at the same time it's likely that the video recorder will tell us that the end of the tape has been reached as well, by changing the display on the front or by rewinding and automatically ejecting the tape. This allows us to respond to the event, perhaps by putting the tape back in its library case.
Properties
Properties should be no problem to grasp by now. We regularly used the term in the last chapter when we were referring to the style properties of the elements in the page. All we really mean by a property is some setting, or stored value, that applies to an object. The object will usually expose a set of properties that affect the appearance or behavior of the object, and some that just provide information about it.
In our video recorder example there are read/write properties, where we can change the behavior or appearance. These might include the record speed setting, and the time setting on the clock. Read-only properties could be the age, the price, and the working condition. As you can see, there are often read-only properties that we would like to be able to change, but can't—and Dynamic HTML is no exception.
The other terms that you will need to become familiar with are collections and parent-child relations. We will use the frames collection of the window object to explain these concepts.
Collections
A collection is something like the arrays that you meet in programming languages, where each item is held in structure and related to its neighbors. A collection of elements is just a way of holding one or more element objects together in such a way that they can be accessed in code.
window.frames("mainframe") 'both of these refer to frames in a window
window.frames(0) 'this is the first frame, with index zero
The browser assumes that the active window object (which may, of course, be a frame inside another window) is the default object for script in the page. Therefore, in most cases we don't need to specify it. The following code has the same meaning as that above:
frames("mainframe")
frames(0)
Understanding Parents and Children
The expression window.frames(0) we used above refers to the first frame in a window. However, this is the current window, which may not be the window at the top of the object tree. Imagine a case where there are three frames in a window. As far as we are concerned, they are indexed 0, 1 and 2 in the frames collection.
However, this is the frames collection of the main (top) window. If we are using scripting code in the page in the lower-left frame, window refers to our own window and not the top main window. Our window is a child of the main (top) window, and script running in it has to refer to other frames in relation to the current frame. Remember, each frame is in effect a window in its own right.
To refer to an object one step up the hierarchy, such as the window that holds the frames collection that created our frame, we use the parent keyword. To go up the hierarchy two steps, we can refer to the parent of the parent, etc.:
parent.window.frames(0) 'this is the first frame in the parent window
parent.parent.window.frames(0)'and in the parent of this window if there is one
We can always refer to the topmost window in the object model (the browser window itself, in effect) by using the keyword top, instead of having to specify the correct number of parent keywords. This is useful in a complex page with several layers of frames. However, remember that top may not refer to the topmost frame in your layout. If the viewer loads your page into a frame created by somebody else—for example by clicking a link to it on their site—it could refer to that page. Therefore, if you load a new page into the top window, you'll remove their frameset as well.
On page 61 in the text, you can see a diagram of the IE4 browser object model. The parent object is the window object. The gray boxes represent child objects of the window object. There is one collection as part of the window object - the forms collection. Look at the chart and see how the different elements are related. For the time being, don't worry about all of the collections hanging off the document object. We'll get to those in a minute
The window object refers to the current window. It gets kinda tricky when dealing with frames, since a window object may have a frames collection. Each element in the frame collection (a frame object) is in itself a window object, which could have a collection of frames, and so on....
The child elements of the window object are:
The document object is the centerpiece of Dynamic HTML. By providing access through all elements on the page through the document object, you can interpret and modify the contents of the page dynamically - hence Dynamic HTML.
The document object itself has methods, properties, and events. The properties allow access to information about the physical document that was loaded in the browser, the general color settings for the page, and information on the current state of the document. The methods of the document object allow you to write content to the page and also perform command methods on page ranges, which we will see later on in the course. The document object can also receive events from the mouse, the keyboard, and those generated internally.
The document collections organize the elements on the page into a more manageable layout. The document collections are:
all
Collection of all the tags and elements in the body of the document.anchors
Collection of all the anchors in the document.applets
Collection of all the objects in the document, including intrinsic HTML controls, images, applets, embeds, and other objects.embeds
Collection of all the <EMBED> tags in the document.filters
Collection of all the filter objects for an element in the document.frames
Collection of all the frames defined within a <FRAMESET> tag.forms
Collection of all the forms in the page.images
Collection of all the images in the page.links
Collection of all the links and image-map <AREA> blocks in the page.plugins
An alias for collection of all the plugins available in the page.scripts
Collection of all the <SCRIPT> sections in the page.styleSheets
Collection of all the individual style property objects defined for a document.The selection object provides information about the current area that a user has selected on a page. The primary use of this object is to create a textRange object that contains all of the text and elements that the user currently has selected. As we will see later in the course, the textRange object can be use to manipulate the text on the page.
Try to include at least seven of the following in your assignment (the more the merrier):
This is a big assignment, and the Object Model is both complex, yet important to DHTML. Don't worry if you don't fully understand it in a week. If I find that a lot of people are having trouble, then I have no problem spending another week on this topic. So don't worry about being left behind. Remember to wrap animations in the onLoad event.
====== End Lesson and Assignment 3 =========
|
|
||||||||||||
|
Filter effect |
Description |
|
||||||||||
|
Alpha |
Sets a uniform transparency level. |
|||||||||||
|
Blur |
Creates the impression of moving at high speed. |
|||||||||||
|
Chroma |
Makes a specific color transparent. |
|||||||||||
|
Drop Shadow |
Creates a solid silhouette of the object. |
|||||||||||
|
FlipH |
Creates a horizontal mirror image. |
|||||||||||
|
FlipV |
Creates a vertical mirror image. |
|||||||||||
|
Glow |
Adds radiance around the outside edges of the object. |
|||||||||||
|
Grayscale |
Drops color information from the image. |
|||||||||||
|
Invert |
Reverses the hue, saturation, and brightness values. |
|||||||||||
|
Light |
Projects a light source onto an object. |
|||||||||||
|
Mask |
Creates a transparent mask from an object. |
|||||||||||
|
Shadow |
Creates an offset solid silhouette. |
|||||||||||
|
Wave |
Creates a sine wave distortion along the x-axis. |
|||||||||||
|
XRay |
Shows just the edges of the object. |
|||||||||||
|
Style Sheet Transitions Another way to enhance the user interface of an application is to present different parts of the interface when the user needs them, and not before. This has become possible in IE with Dynamic HTML. You have the ability to change the visibility property of any object on the screen, which will make it either appear or disappear. But with plain DHTML, you have no way of controlling how that appearance or disappearance looks. When you set the visibility property of a hidden object to visible, the object just appears. But what if you want to make the object appear as if it is dissolving onto the page, or building from the right. To do this, you need to use the transition filter. Transition Filters The transition filter basically steps in front of IE4’s internal drawing functions, and allows the developer to specify how to display a particular object. Any object that has a visibility property can be used with the transition control. The transitions are added as a filter to the object's style property. This is very similar to adding a visual effect filter. You can either explicitly add the transition inside the objects style tag, or you can dynamically add it in script using the object's style property. There are two types of transitions: the blend transition and the reveal transition. Blend Transition The blend transition allows for a simple fade in or fade out of an object over a specified duration. The fade works by slowly dissolving away the existing object, and showing the new object gradually in its place. You have no control over the way that the fade is done, merely over how long the transition takes. To add the blend transition to an object's style, you would add this to the style sheet: BlendTrans(Duration = duration) |
|
|||||||||||
|
Parameter |
Description |
Values |
||||||||||
|
Duration |
Length of time the transition should take |
seconds |
||||||||||
Reveal TransitionThe reveal transition allows you to specify the visual transition that will take place. As with the blend transition, you can also specify the duration of the effect. To add the reveal transition to an object's style, you would add this to the style sheet: RevealTrans(Duration = duration, TransitionType = transition) |
||||||||||||
|
Parameter |
Description |
Values |
||||||||||
|
Duration |
Length of time the transition should take |
Seconds |
||||||||||
|
TransitionType |
Type of transition to use |
See the transition table below |
||||||||||
Reveal Transition TypesHere is a listing of the types of transitions, along with a short description of what each one looks like. The example at the end of this section will provide a visual example of each of these transitions. |
||||||||||||
|
Transition Name |
Value |
Effect |
||||||||||
|
Box in |
0 |
Draws from the outer edge inward using straight sides |
||||||||||
|
Box out |
1 |
Draws from the center outward using straight sides |
||||||||||
|
Circle in |
2 |
Draws from the outer edge inward using a circle |
||||||||||
|
Circle out |
3 |
Draws from the center outward using a circle |
||||||||||
|
Wipe up |
4 |
Draws from the bottom edge straight upward |
||||||||||
|
Wipe down |
5 |
Draws from the top edge straight downward |
||||||||||
|
Wipe right |
6 |
Draws from the left edge toward the right |
||||||||||
|
Wipe left |
7 |
Draws from the right edge toward the left |
||||||||||
|
Vertical blinds |
8 |
Divides the object being drawn into vertical narrow panels, which are drawn with a wipe right effect simultaneously. |
||||||||||
|
Horizontal blinds |
9 |
Divides the object being drawn into horizontal narrow panels, which are drawn with a wipe down effect simultaneously. Actually looks like you are opening a set of aluminum blinds and revealing the picture beneath. |
||||||||||
|
Checkerboard across |
10 |
Divides the object into a checkerboard pattern and then draws every other panel using a wipe right effect simultaneously. When that effect is complete, the other panels are then drawn using the same effect. |
||||||||||
|
Checkerboard down |
11 |
Same as the checkerboard across transition, but with using a wipe down effect on each panel, rather than a wipe right. |
||||||||||
|
Random dissolve |
12 |
Randomly draws each pixel that makes up the object, so that the object appears to "sparkle" in. |
||||||||||
|
Split vertical in |
13 |
Draws from the left edge with a wipe right and from the right edge with a wipe left simultaneously, so that the object is fully drawn when the two effects meet at the middle. |
||||||||||
|
Split vertical out |
14 |
Starts a wipe left and a wipe right effect simultaneously from the center of the object. |
||||||||||
|
Split horizontal in |
15 |
Draws from the top edge with a wipe down and from the bottom edge with a wipe up simultaneously, so that the object is fully drawn when the two effects meet at the middle. |
||||||||||
|
Split horizontal out |
16 |
Starts a wipe up and a wipe down effect simultaneously from the center of the object. |
||||||||||
|
Strips left down |
17 |
Draws the object diagonally from the top right corner downward and to the left. |
||||||||||
|
Strips left up |
18 |
Draws the object diagonally from the lower right corner upward and to the left. |
||||||||||
|
Strips right down |
19 |
Draws the object diagonally from the top left corner downward and to the right. |
||||||||||
|
Strips right up |
20 |
Draws the object diagonally from the bottom left corner upward and to the right. |
||||||||||
|
Random bars horizontal |
21 |
Draws the object using single pixel wide horizontal lines that are randomly placed. If the transition has not completed in the time defined by the StartPainting method, then the whole image is immediately shown. |
||||||||||
|
Random bars vertical |
22 |
Draws the object using single pixel wide vertical lines that are randomly placed. If the transition has not completed in the time defined by the StartPainting method, then the whole image is immediately shown. |
||||||||||
|
Random |
23 |
Randomly selects from all the possible transitions. |
||||||||||
MethodsOnce you have assigned a transition style to an object, you will then need to use script methods to make the transition appear. There are three easy steps that need to be followed when working with a transition. These steps are the same for both the reveal transition, as well as the blend transition. Step 1: Apply the Transition The first step is to apply the transition. This may sound a little strange, since it sounds like when you "apply" the transition, you are making it appear. If you remember back, the transition filter works by intercepting the normal IE4 redraw methods. So, by applying the transition, you are telling IE4 that you want the transition filter to handle the drawing of the object that it refers to. To "apply" the transition, you will use the Apply method. To call this method, you need a valid reference to the filter itself. This can be obtained through the object's filters collection. Once you have this reference, you can call the Apply method by myTransObject.Filters.item(0).Apply() The transition filter now has control of the redrawing of your object. Step 2: Change the object Since the goal of a transition is to change the appearance of an object from one look to another, you will need to identify what the final state of the object is. Since you now have taken control of the redraw process, any changes that you make to the visual appearance of the object will be held in limbo by the transition filter. For example, if you have the transition filter applied to an <IMG> object, you can change the Source Image property, and a new image will be drawn in its place. If you have the transition filter applied to a container object, like a <DIV>, then you can change any one of the <DIV> block's contents and have the transition filter handle the change in visual appearance Step 3: Play the Transition Now that you have changed the object that the transition filter is controlling, you need to tell the filter to go ahead and begin its redraw of the object. This is called "playing the transition." The transition filter will draw the new object using the specified transition type, in the case of the Reveal transition, or fade the new object over the old, as in the case of the Blend transition. The transition will be done over the length of time specified in the filter's Duration property, or by an optional parameter to the play method. To call the Play method, you would use myTransObject.Filters.item(0).Play(duration) |
||||||||||||
|
Parameter |
Description |
Values |
||||||||||
|
duration |
Option - Length of time the transition should take. Overrides the Duration property of the filter. |
Seconds |
||||||||||
|
Once the drawing of the new object is completed, the transition filter returns control of the redraw for that object to IE4. The filter also fires an event to let you know that the transition has been completed. Events There is one event, OnFilterEvent, which is fired when the transition is completed. If you have more than one object with a transition filter attached to it, you can use the Window.Event.srcElement property to determine which object's transition just completed.Page Transitions Page transitions make it possible to provide multimedia effects as a Web page is loaded or exited. Today, without page transitions, when a new page is loaded, the existing one is cleared from the browser. Then the new page is loaded element by element. The developer of a page has very little control over how the page is drawn on the screen. What Page Transitions Do Transitions are defined by using the META tag, in the HEAD section of a Web page. The developer can specify whether a particular transition should occur as the page is loaded or as it is exited. The transition type and duration properties are set using the variables in the special META tag. When the browser finds a transition META tag, it interprets whether the event should occur before the page is displayed or as it is exited. When that event occurs, the transition filter takes over control of the repainting in the browser, just as it does with the transition style sheet filter. Using Page Transitions To set a page transition, the developer must determine three items. First, they need to decide if the transition if for when the page is loaded, or when it is exited. There is no limitation in having both an entrance and an exit transition for a page. They just need to be defined separately. The developer must also determine how long the transition should take to process. Lastly, they must select the type of visual transition that they would like to see. To add a page entrance transition to a page, you would add this to the <HEAD> section of the page: <META http-equiv="Page-Enter" CONTENT="RevealTrans(Duration=duration,Transition=transition)> To add a page exit transition to a page, you would add this: <META http-equiv="Page-Exit" CONTENT="RevealTrans(Duration=duration,Transition=transition)> The parameters for the revealTrans method are identical to the parameters for the revealTrans style sheet filter. The duration indicates the number of seconds that the transition should take. The maximum value for the Duration parameter is 30 seconds. The transition selects the type of visual transition that will be used to draw the screen. |
||||||||||||
|
|
||
|
Assignment 4 Try to incorporate at least five of the following:
Add some reveal and blend transitions to elements on your page. Be sure to apply them to images as well as other elements. For more examples, look at http://www.microsoft.com/ie/ie40/demos/transall.htm and http://www.microsoft.com/ie/ie40/demos/filters.htm. |
|
============== End Lesson and Assignment 4 =============
|
Lesson 5 What events are, and where they come from When you carry out some action in Windows, say clicking on a window with the mouse, the operating system raises an event. This is simply a signal that something has happened. Windows examines the event to decide what caused it, and what to do about it. This isn't always as simple as it may seem. For example, the user may have clicked on a window that was not currently active (i.e. not part of the application they were working with). In this case, Windows has to work out where the mouse pointer is on the screen and which application is under the pointer, bring this application's window to the front, and tell the other application that it is no longer the active one. And this is only a simplified view. In reality there will be a lot more happening 'under the hood'—a stream of messages is being sent to all the applications by the operating system. Each application can choose to either do something about the message, or simply ignore it. Events in Dynamic HTMLIn the case of the browser and Dynamic HTML, this constant barrage of messages provides a way for us to react to things that are going on in the browser. We can link code in our pages to the events that are occurring, and use them to interact with the viewer of our pages. For example, just clicking the mouse button creates several events—descriptively named onmousedown, onmouseup, and onclick. Each message is collected by the Windows operating system, which then decides what to do with it. If the user pressed the mouse button while the pointer was on the screen over the browser window, Windows sends a message to the browser. It includes information on which button was pressed, what other keys were held down, and where the pointer was on the screen. The browser then decides if it is going to handle the event. If they clicked on one of the browser toolbar buttons, it just gets on and does whatever is required—perhaps printing the page, refreshing it, or loading the user's Home page. If, however, the click was over the page itself, the browser then exposes it, by passing it on to our script code via the browser's object model. At this point, we can react to the event ourselves if we want to. The reverse path is taken if we actually do decide to respond. The instructions in our code are passed back to the browser via the object model. It decides what effect this will have on the page and tells Windows. Windows then updates the screen to show the new page. The great thing is that, as Dynamic HTML programmers, all we have to do is decide which events to respond to, and what instructions to give the browser. Everything else is looked after automatically. Reacting to browser eventsTo be able to react to an event, we have to be able to detect it happening. If we don't react to it, the browser will just carry on regardless—perhaps carrying out some action of its own. And even if we do decide to react, we can still let the browser carry out the original task as well. There are 39 different events that the browser exposes to our script—but for any one element in the page, only a limited number of these are available. For example a heading in the page, such as <H2>Some Text</H2>, only provides 14 events, while an image tag <IMG> provides 25 different ones. In Section A of the book's reference pages, you'll find a description of all the events, and, in Section B, a list of those available for each HTML element tag. Event Handling in VBScriptIn VBScript, we have four ways of connecting our code to an event. The main one we've used so far is to create a subroutine or function whose name is a combination of the element name and the event name. To react to a click on some heading text, we can use:
Alternatively, we can create a routine with almost any name, and link it to the event and the element by declaring the name of the routine in the element tag. And we don't need an ID in this case:
Another way is to use 'inline' script code, which does away with the need for a separate code routine. We simply write the code inside the tag, as the value of the event name attribute. Notice how we have to use single quotes inside the ONCLICK attribute, because this itself is a string: <H2 LANGUAGE=VBSCRIPT ONCLICK="MsgBox 'You clicked me!'"> Some Text </H2> The final method is to use a different script section for each event. This is done by identifying the element and the event in the <SCRIPT> tag:
Event Handling in JavaScriptIn JavaScript (or Microsoft's implementation of JavaScript, called JScript), we don't have as many options for connecting events to our code. And the two things we have to watch out for are:
The most usual way of making the connection between the function and the element is by defining the name of the function in the element tag itself. Notice that we need MyClickCode(), not just MyClickCode, to satisfy the JavaScript syntax requirements. We also have to use the browser's built-in alert dialog, rather than MsgBox, which is part of VBScript:
This is fine for connecting script to specific elements in the page, but what about when we want to connect event handlers to the document itself? In this case, we simply put them all in the <BODY> tag: <BODY ONMOUSEMOVE="MyMouseMoveCode()" ONCLICK="MyClickCode()"> We can also use inline code, within the element tag. This time, we're using the alternative LANGUAGE description of JSCRIPT: <H2 LANGUAGE=JSCRIPT ONCLICK="alert('You clicked me!');">Some Text</H2> And because JavaScript is the default language in the browser, we can omit the LANGUAGE attribute if we want to, making our code more compact: <H2 ONCLICK="alert('You clicked me!');"> Some Text </H2> Finally, we can create the separate <SCRIPT> sections for each event, just like we did for VBScript. However, this time, we have to make sure that the name of the event is all lower-case:
Handling Window Events in JavaScriptWe've seen how we can place event handler declarations, such as onmousemove, in the <BODY> tag of the document to cause them to occur at document level. The other situation is how we handle events at window level. In Internet Explorer, we can place the event handler declarations on the opening <HTML> tag:
Alternatively, we can use a technique similar to the VBScript method of naming an event handler in line with the ID of the element and the event name. This time, we separate the two with a period (full stop) rather than an underscore. For example, the following are both supported in Internet Explorer 4—but bear in mind that this is not the generally accepted method for connecting events and their code. (It works because the functions are themselves actually stored as properties of the element object)
The same works for the main browser objects as well, such as the document and window:
The LANGUAGE attribute in a script or element tag can take one of four values. VBSCRIPT and VBS both instruct the browser to pass the script to its VBScript interpreter, while JAVASCRIPT or JSCRIPT pass it to the Internet Explorer JScript interpreter. Omitting the attribute altogether sends the script to the JScript interpreter as well. Responding to eventsNow that we've found ways of connecting our code to an event, we can start to write the code that instructs the browser—and tells it what we want to do. In general, this involves three tasks—getting information about the event, finding out about the element the event occurred for, and carrying out the task. This is where the links between our code and the elements in the page (as exposed by the object model) come into play. Getting Information about an EventAll the ways you've seen here of connecting code to an event were equally valid in earlier releases of browsers that supported scripting (though the heading element didn't expose its events—only a very limited subset of controls did this previously). Dynamic HTML also adds another way of getting information about an event: the event object. Mouse Information and the Event ObjectThe event object provides a whole range of properties that tell us about an event that has just occurred. We simply query these properties inside our event handler to find the information we need to make a decision on what to do. Here's how we can query the properties of the event object to get information about the mouse button that was pressed, and the position of the moue pointer when the event occurred:
Notice that in this example, we've preceded the event object with the default window object. This is not necessary in JavaScript (or JScript), but must be done in VBScript to prevent a clash between the event object and the VBScript event keyword. Key-press Information and the Event Object If we query the event object for a key-press event, we can use the same techniques as we did for a mouse event to find out where the mouse pointer is, and use the shiftKey, ctrlKey and altKey properties. However, more than that, we can use the keyCode property to find out which key was pressed. In this example, we're reacting to the onkeypress event of the document:
Bubbling and canceling eventsThe event object plays another major role in the way we create script routines in Dynamic HTML. It not only stores the values of the environment as each event comes along, it also plays a part in controlling how these events are propagated to our code. It does this through two properties, cancelBubble and srcElement. The Event Object's Control SystemWhen an event occurs in a page, the event object gets first look at it, and decides which element should receive it. The event object looks to see which element the mouse pointer was over at the time. (If two elements are overlapped, it uses the one with the higher z-index). If there is an event handler for the element and the proper event, then that handler is executed. However, it doesn't stop there. It now looks to see which element is the container of the heading tag, checking for an appropriate event handler. This process continues while there are containers available. This will continue all the way up to the document itself. After an particular event handler is finished, the event is passed on up the hierarcy. If you do not want this top happen, then set the cancelBubble property of the event object to false. Event bubbling, as this process is called, is very useful. For one thing, it helps to minimize the code we have to write, by letting one routine handle an event for several elements. Now that all the elements support events, this is particularly helpful. Using Containers in Dynamic HTMLEvent bubbling allows us to work with the concept of containers. In HTML, when we create a list of items in the page, we group them together in <UL> or <OL> tags:
Notice that we've given the list and each item in it an ID here, and used style classes to create the styles for the list. We've also wrapped the whole list in a <DIV> tag, so that we can position it absolutely and move it around in our code. This time we want to react to the onmouseover event for all the items in the list, by creating one single event handler for the list itself—the container of the list items:
Summary
===== End Lesson 5 ======= |
|
||||||||||
|
|
|||||||||||
Assignment 5Read chapter 5 of IE4 Dynamic HTML Programmer's Reference and run the examples shown. Try to do all of the following:
|
|
||||||||||
|
Lesson 6 - Changing the Contents of the Page The previous lessons of this course covered changing the position and appearance of elements. We can also change the actual element itself, just as though we has changed the HTML source that created it. We can also add elements to, and remove them from a page while it is displayed. The easiest way to manipulate the contents of a page is to use the special properties that are supported by the majority of visible elements. They expose the contents of each part of the document, almost as it appears in the source code. By assigning new values to these properties, we can change the contents of the page that is being displayed. By document, we mean a stream of characters that consists of both text and HTML and which represents the current page. Don't confuse the document with the actual HTML source code though. This is why we said 'almost as it appears in the source code'. The browser translates the source code into its own representation of the page before displaying it, and changing the contents of an element on the page does not update the original HTML source—just the browser's internal representation of it. The Element 'Content' Properties There are four properties that are supported by most of the visual elements in the page: |
|
||||||||||
|
Property |
Description |
||||||||||
|
InnerText |
The complete text content of the element, including the content of any enclosed element, but excluding any HTML tags. Assigning a new string to it replaces only the content of the element, and any new HTML tags are rendered as text, and not interpreted. |
||||||||||
|
OuterText |
The complete text content of the element, including the content of any enclosed element, but excluding any HTML tags. It returns the same string as innerText, but assigning a new string to it replaces the entire element. |
||||||||||
|
InnerHTML |
The complete text and HTML content of the element, including the content of any enclosed element. Assigning a new string to it replaces only the content of the element, and HTML tags within it are rendered correctly. |
||||||||||
|
OuterHTML |
The complete text and HTML content of the element, including the start and end tags of the element and the entire text and HTML content of any enclosed element. Assigning a new string to it replaces the entire element, and the HTML content of the new string is rendered correctly. |
||||||||||
|
The Element InsertAdjacent Methods As well as using the four properties to change an element's contents, we can use two methods that are supported by many of the visible elements: |
|||||||||||
|
Method |
Description |
||||||||||
|
InsertAdjacentText |
Inserts text into or adjacent to the element. Any HTML tags are ignored. Text can be inserted at the start or end of an element within the element's tags, or immediately before or after the element—outside its opening and closing tags. |
||||||||||
|
InsertAdjacentHTML |
Inserts text and HTML into or adjacent to the element. HTML within the string is correctly rendered after insertion. Text and HTML can be inserted at the start or end of an element within the element's tags, or immediately before or after the element—outside its opening and closing tags. |
||||||||||
|
Using TextRange Objects We can also manipulate the contents of a document by using TextRange objects. However, this is more involved that using the 'content-manipulation' properties and methods we've just looked at. A TextRange object has properties that are set to reference part or all of a document, and methods that are used either to change which parts of the document that the TextRange currently references, or to work with that referenced part of the document. We usually resort to using TextRange objects in two particular instances: when the element that we want to access does not support the 'content-manipulation' properties we looked at earlier, and when we come to manipulate the contents of a selection object. This object provides a reference to the current user's selection on screen (from dragging over with the mouse). We can create a TextRange object in two different ways :
We can change the contents of a TextRange by moving the start and end positions. This means that we are effectively changing the text and elements that the TextRange refers to, but not changing the actual text itself. We can do this with the following techniques:
Once we've created our TextRange object, or moved it to a new position, we can get information about the current text and elements it refers to by:
Creating Dynamic Tables Working with HTML tables and their contents isn't a whole lot different from working with the plain text in the page. This shouldn't be surprising, because tables are just a heap of HTML <TABLE>, <TH> and <TD> tags anyway. We can use the techniques we've seen in this chapter to manipulate them as easily as we manipulate text. The Rows and Cells CollectionsWhat makes tables interesting, however, is that Dynamic HTML finally brings the concept of rows and columns to a table created with HTML tags. We can use the rows and cells collections to access individual rows and cells in a table whenever we like:
|
|||||||||||
These collections work in the same way as the collections we've met throughout the book. We can access individual rows in the rows collection using the ID of the <TR> element for that row, or an index number starting at zero for the first row. We can loop through the rows using the For Next construct. Each row in the rows collection is an element representing that <TR> tag, and has its own cells collection representing the cells in that row.
The cells collection is accessed in the same way, using the ID of the <TD> or <TH> tag, or an index number representing that cell's position in the row—where the left-most cell is indexed zero. Each object in the cells collection is an element representing the <TD> or <TH> tag.
Summary
|
|
Assignment 6Here is a list of things that I might like to see you try in a page:
Have fun! |
|
======= End of Lesson and Assignment 6 ========
======= End of DHTML =========