
a. Java
At the most basic level, Java is a programming language developed at Sun Microsystems in 1990. It was originally designed to be used on small consumer-electronic devices such astelevision set-top boxes, but eventually Sun realized that Java could be useful for much more than that.
Borrowing much of its syntax and structure from the widely used C++ language, Java has since become an industrial-strength programming language no more or less interesting for the layperson than any other language--except for one important thing:the Java Virtual Machine.
With most languages, developers translate their programs into the zeros and ones of machine code with a tool called a compiler. This means that the final results can be understood only by a specific operating system.
This isn't necessary with Java.
The Java Virtual Machine instead acts as a go-between to "interpret" Java programs for the computer. This is a break for developers because they only need to write one version of a program to run on any machine. It also means that users don't have to worry about whether the new application they bought will run on their computer, or on their office-mate's computer--or someday maybe even on another kind of device, like a pager, a smart card reader, or a cellular phone.
This promise of portability, what Sun likes to call "write once, run anywhere," is why Java has caused such excitement.
As with any complex technology, Java has its own theory and vocabulary, vocabulary that can confuse nonprogrammers and be manipulated to make Java sound likenothing short of a cure for cancer. But at the most fundamental level, Bill Gates is right: Java is just a programming language.
Isn't Java slow?
No doubt about it, Java applications are slow compared to most major personal-computer applications--word processors, Web browsers, and so on. This is the price that must be paid for being able to run anywhere. But there are ways to speed up Java performance.
Most PC software is written in the C or the C++ programming language, and then translated with a tool called a compiler into the machine code that the main processor can understand. The software is then distributed as compiled code. But since each processor speaks a different machine language, the process means that only one kind of machine can understand the compiled code.
This isn't true with Java applications. Java software is distributed in an intermediate form known as bytecode. Instead of the compiler doing the translation work in advance, the Java Virtual Machine translates bytecode into machine code on the fly, usually as the software executes. This is what makes it possible for Java applets to be written once and run anywhere. But this on-the-fly translation takes time and is why Java programs usually run more slowly than a compiled application.
But there's slow, and then there's really slow. Several factors can affect the performance of a Java application on a specific computer.
The performance of the Java Virtual Machine makes the biggest difference; using an operating system or browser with a faster and more efficient virtual machine will make Java apps run noticeably faster.
Sun is also working on a technology, HotSpot, that will reportedly improve virtual machine performance--but this isn't out yet, and Sun is being cagey about revealing a schedule.
HotSpot includes both a dynamic compiler and a virtual machine to
interpret bytecodes, as shown in the following figure.
Some companies have also come up with a technology called the just-in-time (JIT) compiler to try to get back some of the speed advantages that go with using a standard compiler. These JIT compilers (different companies have created different versions) work with the virtual machine to analyze a Java program and break it down into simpler and more efficient code that can run more quickly.
They're called just-in-time compilers because this simplification process also happens on the fly. In this way, you get some speed-up without sacrificing portability. (Just-in-time compiling may slow down the initial start-up of an applet, but then the applet will run faster every time you execute it.)
While speed is the price Java pays for portability, in general, Java performance can be expected to improve over time; good programmers make faster code than bad programmers do, and many developers are still honing their Java skills.
What Do I Need to Start Building Java Applets?
Users and developers who want to get Java to make software have several options. Nonprogrammers can try simple point-and-click Java tools such as Jamba, Coda, or BeanMachine. These visual tools aren't for anything too complicated, but they will help you build a nifty little animation in minutes.
Real programmers now have several industrial-strength tools to choose from. Microsoft, Symantec, and several other tool vendors sell complete Java development kits. If you're a hard-core coder on a budget, you can download Sun's Java Development Kit for free. It isn't pretty, but it works.
Java Buzzwords
Abstract Window Toolkit (AWT): a class library (see below) that handles common interface elements for windowing interfaces, including Windows, the Macintosh, and Motif. While there are many Java class libraries, this one comes up more than the others do because it addresses interface issues and because many developers complained about Sun's initial implementation.
Applet: a program written in Java and intended to run inside of a Web browser. Java can be used to create full-scale applications, as well, but its most common use today is to make applets.
Bytecode: the form of Java code that the Java Virtual Machine reads. Developers writing in languages such as C++ use tools called compilers to translate their code into native, or machine, code. Java compilers instead turn Java programs into the intermediate form called bytecode. This is slower than compiled code but isn't linked to any particular hardware.
Class: defines characteristics for a group of objects in object-oriented parlance. Class libraries are collections of related classes that solve specific programming problems.
Java Virtual Machine: software that acts like a mini-PC, interpreting the Java code so that the PC itself doesn't have to. A single Java applet or application can run unmodified on any operating system that has a virtual machine, or VM. Sun writes a virtual machine that it licenses to other companies, but operating system vendors such as Microsoft generally write their own.
Java Development Kit (JDK): Sun's free tool for making Java applets and full-scale applications. Other Java tools such as Symantec's Visual Café Pro, are better development environments. But the JDK is a useful collection of Java development tools and documentation for all levels of Java programmers. Sun also rolls out new Java technologies and fixes in its upgrades of the JDK. All Java licensees are contractually obligated to support these changes.
Java DataBase Connectivity (JDBC): an interface that lets Java programs get data from any database. The database vendors choose to support Java by throwing a JDBC driver into their software.
Just-in-time compiler (JIT): Bytecode is more portable but slower than native machine code. To try to make applets run faster, just-in-time compilers from Sun and several other companies translate the bytecode into machine code. But while regular compilers do their work before the user ever sees the software, just-in-time compilers work only after the user downloads an applet. JITs also don't change the original code. This keeps an applet portable while providing performance improvements, although not as much as if the applet were compiled to machine code in advance.
Object-oriented: a method of programming that pairs programming tasks and data into reusable chunks known as objects. Java is an object-oriented programming language, as are older languages such as Smalltalk and C++. Object-oriented code is faster to write, easier to fix, and can be more easily recycled for other applications.
Sandbox: the security model used to keep Java from running amok on your PC. With a sandbox, an applet runs within a confined environment, with no way to corrupt data, delete files, or reformat your hard drive.
b. Java Beans
JavaBeans are what you grind up to make Java applications--at least that's the allusion behind the name.
JavaBeans are actually reusable software components--little chunks of code that perform single functions and can be mixed and matched to create complex applications. For example, let's say an applet pops up an alert letting you know you have new mail. That applet might be made of two JavaBeans: one to keep track of your mailbox and one to display the alert message.
Because Java is an object-oriented language, everything created in Java is an object. The JavaBeans architecture provides a standard mechanism for these objects to identify each other and to exchange information. Developers need some sort of builder application such as Lotus's BeanMachine or Objectshare's Parts for Java to assemble beans into a program.
JavaBeans are similar to ActiveX Controls. In fact, a JavaBean can interoperate with an ActiveX Control. But beans are of course written in Java, so unlike ActiveX, they can run on any Java-enabled platform. The market for beans is still new, so there aren't nearly as many available beans as there are ActiveX Controls. But Sun Microsystems hopes the cross-platform appeal of beans will change that.
What is a Bean? Why isn't a Bean an Applet?
JavaBeans components, or Beans, are reusable software components that can be manipulated visually in a builder tool. Beans can be combined to create traditional applications, or their smaller web-oriented brethren, applets. In addition, applets can be designed to work as reusable Beans.
Individual Beans will function quite differently, but typical
unifying features that distinguish a Bean are:
How
Can Web Page Developers Use JavaBeans?
c. JavaScript v. Visual Basic Script
What is JavaScript?
First thing--forget the name.
JavaScript and Java have only a very loose relationship. Both involve Sun Microsystems and Netscape Communications. Both are object-based but only Java is truly object-oriented. They really just aren't the same thing at all.
JavaScript began life at Netscape as a scripting language called LiveScript. Netscape designed LiveScript as a simple tool to help Web site developers design interactive Web pages. For instance, using LiveScript, a developer could make sure that users had entered data into a form correctly before the data got sent back to the Web server. LiveScript could also send data to Java applets and browser plug-ins. It was simplistic, but performed the necessary function of letting different parts of a Web page interact with one another.
In 1995, Netscape and Sun joined forces to update LiveScript. By December, they were promoting it as an "open Internet-scripting-language standard" and eventually handed it over to a European standards body called ECMA. They also gave it a more marketable--but more confusing--name: JavaScript.
Netscape is now working to synch JavaScript up with ECMA's standardized version called ECMAScript. This process is not complete, but even when it is, most people will still call it JavaScript instead of the unattractive "ECMAScript."
JavaScript is an improvement over LiveScript, but it still isn't a full-fledged programming language like Java. JavaScript is simply an interpreted scripting language. Nearly anyone with some time and a bit of technical curiosity can learn JavaScript. Just don't think that once you know JavaScript you're on the way to learning Java.
JavaScript also requires a JavaScript-enabled browser to do anything and, again, this is not necessarily the same thing as a Java-enabled browser. Navigator and Explorer provide different levels of JavaScript support.
Here's a chart of which browsers support JavaScript:
Windows |
Mac |
WebTV |
| Navigator 2.0 and later | Navigator 2.0 and later | WebTV browser |
| Internet Explorer 3.01 and later | Internet Explorer 3.01 and later | |
| Opera 3.0 |
JavaScript components can be built just like JavaBeans, as
self-contained objects whose interface to their application environment consists of
properties, methods, and events.
What is Visual Basic Script?
Visual Basic Script recently introduced by Microsoft represents a step further towards active web pages. Like JavaScript, Visual Basic Script provides scripting, automation and customisation capabilities for Internet Explorer. It is a subset of the Visual Basic programming language that is fully compatible with Visual Basic and Visual Basic for Applications.
To use Visual Basic Script within a HTML document, the code needs to be wrapped in <SCRIPT> ... </SCRIPT> elements, just like JavaScript (or contained in a separate text file and referenced using the SRC="URL" attribute). As with JavaScript, the LANGUAGE attribute is required, in this case needing the value "VBScript". Visual Basic Script comes into it's own when used in conjunction with ActiveX (OLE) controls, which allow for full automation with any OLE compliant application, but can be used for almost any purpose on a page, allowing for truly interactive web sites to be created relatively easily.
NOTE : Internet Explorer only supports external Visual Basic Script files from 3.02 onwards. The script file is just a text file, containing the functions etc., of the script required by the document and can have any extension (proper MIME type mapping will be required to ensure correct functionality)
The following code section, assigns an action to a button. The action is linked in the script (namely that a message box pops up when the button is pushed) to the button, named 'btnHello' which has been embedded within the page.
<SCRIPT LANGUAGE="VBScript">
<!-- These comment delimiters ensure the code is hidden from those browsers that do not support Visual Basic Script
Sub btnHello_OnClick
MsgBox "Hello, It's a fine day"
End Sub
-->
</SCRIPT>
NOTE : Netscape will not activate the script on pressing such a button. It can be made to act similarly using JavaScript.
The button, called 'btnHello' responds to being clicked by displaying a message box with the text "Hello, It's a fine day". For information on how to embed ActiveX controls, see the <OBJECT> element. (A button suitable for the above example can be embedded into the page using a standard <INPUT TYPE=BUTTON> element.)
As with JavaScript, a complete description of Visual Basic Script is well outside the scope of this reference and you are encouraged to visit http://www.microsoft.com/vbscript/ for more information and a complete copy of the language documentation.
Examples:
Here is a quick (and very simple) example. Using the following script and button in a document, displays a time-dependant greeting.
Example in Visual Basic Script <FORM> <INPUT TYPE="BUTTON" VALUE="Say Hi..." NAME="btnTime"> </FORM> </CENTER> <SCRIPT LANGUAGE="VBScript"> <!-- Sub btnTime_OnClick currenttime=Hour(Now) if ((currenttime < 12) And (currenttime >=6)) Then MsgBox "Good Morning!" if ((currenttime >= 12) And (currenttime < 18)) Then MsgBox "Good Afternoon!" if ((currenttime >=18) And (currenttime < 22)) Then MsgBox "Good Evening! I hope you have had a good day" if ((currenttime >=22) Or (currenttime < 4)) Then MsgBox "It's late, you really ought to get to bed" if ((currenttime >= 4) And (currenttime < 6)) Then MsgBox "It's early, you shouldn't be up yet" End Sub --> |
Same Example in JavaScript <FORM> <INPUT TYPE="BUTTON" VALUE="Say Hi..." onClick="checktime()"> </FORM> </CENTER> <SCRIPT LANGUAGE="Javascript"> <!-- function checktime () { thisday=new Date() hour=thisday.getHours() if ((hour < 12) && (hour >=6)) {alert ("Good Morning!");} if ((hour >= 12) && (hour < 18)) {alert ("Good Afternoon!");} if ((hour >=18) && (hour < 22)) {alert ("Good Evening! I hope you have had a good day");} if ((hour >=22) || (hour < 4)) {alert ("It's late, you really ought to get to bed");} if ((hour >= 4) && (hour < 6)) {alert ("It's early, you shouldn't be up yet");} } //--> </SCRIPT> NOTE : The <SCRIPT> function works in Netscape from version 2.0, but in version 4.0, the button OnClick event handler may need to be changed to OnClick="javascript:checktime()" for it to work properly. |
So What Does Scripting Allow you to Do? (Don't forget to view source code)
For how to write JavaScript see: Thau's five-day JavaScript tutorial
Thau's
JavaScript Tutorial: Day 1
Thau's
JavaScript Tutorial: Day 2
Thau's
JavaScript Tutorial: Day 3
Thau's
JavaScript Tutorial: Day 4
Thau's JavaScript
Tutorial: Day 5
d. HTML 4.0 specifications:
1. Document Object Model (DOM)
The W3C's antidote to this quagmire is the Document Object Model, or DOM (pay attention to the middle word). DOM is an architecture designed to embrace all these technologies, giving them a common framework in which to play. DOM is the W3C's platform- and language-neutral specification for uniting HTML, CSS, and scripts into a model of interoperability that everyone can implement. Netscape, Microsoft, and other companies make suggestions to the W3C on the best way to implement the DOM. What comes outthe other end of that process becomes known to us as Dynamic HTML.
Why Dynamic? It's not called DHTML just because things are going to be flying around all over the place (though that's certainly part of it). In essence, DHTML does two important things.
First, DOM breaks up every element on the page into independent objects, with properties specified via CSS. Then it exposes every object to a framework of programming and scripting languages. In other words, if you want to manipulate the objects on your page via C++, you can. Via JavaScript or VBScript? The DOM is wide open (though don't expect COBOL support right off the bat). That means Web pages and everything on them are now programmable. This is it--the bridge to the future.
Because Web pages gain so much intelligence, they can do things that greatly enhance the user's experience. Right now, one of the biggest differences between using applications locally versus on the Web is that with a Web page you have to sit there and wait for the page to reload every time you click on an element. But what if a Web page could be full of hidden objects, even completely new pages behind sliding "curtains?" Why shouldn't you be able to click an image in the top-left of your screen and have the page's lower-right paragraph change instantly, without contacting the server again? Imagine HTML tables that function like live databases, with you sorting and sifting through material dynamically, just as you would in a dedicated app. It's finally here.
Object orientation is one of the most sensible things that ever happened to the Web. Think of every page, paragraph, image, table--any element--as an object. Then declare that every instance of that object gets a certain style (set of properties or display instructions) attached to it. Declare it once and those properties are propagated throughout the entire page, the entire site even. For example, if you specify that the object known as Paragraph is always indented 27 pixels from the left and starts with a drop-cap, then all your paragraphs will look like that. And that doesn't even scratch the surface
DHTML to the Rescue
Now, there's a new tool on the block. DHTML is a series of programming innovations supported by version 4.0 of both IE and Navigator. It's not a single language, but a combination of several technological advances, which, when used together, provide a dramatic improvement in the way Web pages appear and interact with users. Scripts and style sheets let you use a mouse click or hover-or even the passage of time-to modify or reposition text and graphics at any time. After a page has loaded, words can be rewritten, new words added, and old words deleted or changed, simplifying complex content delivery and rotation within a single page. DHTML's biggest advantage is that once a page has loaded, most user interactivity occurs completely on the client side, without the slightest hit to the Web server.
The most important part of DHTML is a new Web browser object model that greatly increases the powers of embedded scripts. Object models are not new. They are just collections of subroutines (called methods) and variables (called properties) that one program makes available to others. The subroutines and variables in a Web browser's object model are mostly intended for use by embedded scripts, though they can be accessed by other programs as well, giving them control of the browser.
Because the shortcomings of the original browser object models left designers wanting a lot more, a new standard-the Document Object Model (DOM) Specification-has been proposed to the World Wide Web Consortium (W3C). The DOM, supported in varying degrees by both 4.0 browsers, adds several new methods and properties. The most exciting additions allow scripts to modify tables, frames, forms, style sheets, text and images of Web pages that have already loaded and are being displayed. The changes take effect immediately, giving scripts instantaneous and near total control over what users see.
For example, a script can now override the attributes of any <FONT> tag, causing the associated text's typeface, size or color to change. By altering the HREF attribute of an <A> tag, a script can change the destination of a hyperlink. Scripts can also modify any or all of a page's text, or even insert new HTML tags into the text.
The DOM also allows script authors to create several new event handlers, allowing scripts to respond to more user actions than ever before. The onKeyPress, onKeyDown and onKeyUp event handlers are called whenever the user performs a keyboard action. These handlers can filter a user's keystrokes to alter what's typed or block certain keystrokes. They can also respond to certain keys or sequences in any way they like.
Mouse-wielding users haven't been forgotten either. The new onMouseOver, onMouseOut, onMouseDown, onMouseUp, onMouseMove and OnDblClick event handlers, as well as the older OnClick handler, allow scripts to respond to most common mouse actions. For example, an onMouseOver event handler is automatically called whenever the mouse cursor passes over a particular region of the Web page. The handler can highlight the text under the cursor (by changing its color or size) or even dynamically rewrite the text.
Microsoft has also added a proprietary extension called event bubbling that allows one event handler to process events for several parts of a Web page. For example, you can jazz up hyperlinks by having the text color of each link change when the mouse cursor passes over it. This little trick is called a rollover effect. But one link is special. When the mouse cursor hovers above it, you can make a small image appear, in addition to the text color change.
Without event bubbling, you would have to associate event handlers with each link's <A> tag. Most of the tags would have an event handler that simply changed the color of the tag's text, and the one special tag would have an event handler that made an image visible, too.
But thanks to bubbling, all text color changes can be handled by a single event handler bound to the next level of the document hierarchy (perhaps a <DIV> tag that encompasses all the links). Only the special <A> tag needs its own event handler. And that handler just makes the image appear. Then, like the other <A> tags, its mouse events bubble up to the next level where the color change takes place.
By specifying common actions in a high-level event handler, you need to write common code only once. In addition to saving time, the elimination of duplicate code in several low-level event handlers reduces the chance for errors and makes a page's scripts easier to maintain. It can even make pages smaller, allowing them to be transmitted and loaded more quickly.
Netscape has its own way of creating hierarchical event handlers: event capturing. It turns event bubbling upside down, allowing the top-level window and document object's event handlers to respond to a lower-level object's
events. After the top-level event handler has done its
work, it can optionally pass the event downstream to
the lower-level object's own event handler for
additional processing. In theory, event capturing
works about as well as event bubbling. But the DOM
Specification only specifies Microsoft's upward event
bubbling technique.
2. Cascading Style Sheets
Style Sheets and HTML 4.0
The Document Object Model also fully exploits three other new Web standards: Cascading Style Sheet 1.0 (CSS1) Recommendation, CSS Positioning Working Draft and HTML 4.0 Specification. The CSS1 Recommendation gives Web designers much more control over the appearance of text and graphics. You can specify attributes such as text justification, foreground and background color, whether text is visible, and even define the precise spacing between letters. Another cool attribute lets you add shadows to text or even make text semi-transparent. If a script manipulates this attribute, it can make text slowly appear or fade away, or seem to rise above the page.
The CSS1 Recommendation also separates a Web page's formatting from its structure. Older HTML tags, such as <H1>, <H2> and <STRONG>, can still be used to organize an online document, but new <STYLE> tags create style sheets that take over the job of formatting the text. A style sheet's attributes can even be changed by an embedded script, letting you make quick and easy changes to the entire style of a Web page.
The CSS Positioning Working Draft gives you control over the exact position of text and images within a Web page by letting you define x and y coordinates. Now, you no longer have to place information within complex layers of nested HTML tables to control a precise page layout. In addition, CSS Positioning lets you define an element's z coordinate, which will place elements in front of or behind others.
The HTML 4.0 Specification also increases the power
of embedded scripts. The new <SPAN> tag lets you
name portions of a Web page, while other enhancements allow you to name individual <P>, <FONT>and other tags. These named tags become objects in the page's object hierarchy, allowing scripts to dynamically rewrite text found within a particular span, or even modify a tag's attributes or contents.
Although Netscape's and Microsoft's DHTML disagreements are causing the public--especially developers--plenty of headaches, thankfully both companies implement Cascading Style Sheets (CSS) similarly. Because CSS is the cornerstone of DHTML, we'd be in a real mess if they weren't compatible. The real problems arise from the fact that each browser uses different
object models to link Web-page objects and scripts
together. Ideally, there would be just one way to talk to the objects on a page. For that reason--not to mention the fact that CSS is easier to learn than DHTML--CSS will be adopted at a much
faster rate than its interactive sibling.
Learning CSS is like learning HTML: It seems odd at first, but once you master the basics, it's just a matter of tuning your technique. If you don't know HTML, you need to learn it before tackling CSS. Just as DHTML depends on stylesheets, so do stylesheets depend on HTML.
The cascading in CSS derives its name from the way a style cascades down from the general to the specific. Think of parents passing on traits to their kids; though the kids can still control their own destiny. Elements (like paragraphs or footers) inherit properties from stylesheets (parents), though you can customize or override them. We'll show you how to do this in this section, which is designed to help you learn to start building pages that use stylesheets.
CSS 101
Examples are from Microsoft SBN
SBN Style Sheets Gallery
Let's start with some of the basics of working with CSS. A style is simply a collection of display and positioning attributes that a Web author defines. For example, a style could specify 24-point, bold, blue Arial with a 1-point green border, hovering 50 pixels down from the top of the screen.
Every style gets a name, such as H1 or bibliography or ListBullets. If the style's name is the same as a valid HTML element (or tag), then the style is automatically applied to every instance of that element.
If you give a style a name that doesn't correspond to an HTML tag, you must apply the style manually wherever you want it to appear. You do this by modifying an existing tag in your document or creating a new one. For instance, to apply a bibliography style, you might modify a paragraph tag to read <P CLASS="bibliography">.
For the record, what we're calling styles in this article are technically rules, which consist of two parts: a selector and a declaration.
.selector { declaration }
The selector always precedes the curly braces and the declaration consists of everything between them. The selector will be used as a name later when you apply the style. The declaration is made up of a series of properties and their associated values, separated by semicolons.
.puppy { size:dinky; annoying:usually; collar:black; fur-decoration:spotted; }
Not all values work with all properties, though. For instance, in the example above, the property "size" can never take the value "brown," although "collar" could take the property "spotted." Print out a CSS properties chart for future reference. At www.htmlhelp.com/reference/css/, you'll find a good, W3C-sanctioned list of all these new values and properties.
Your Basic Style
The simplest way to use styles is to apply them to existing HTML tags. Start by declaring a style in your document, ideally, inside the <HEAD>
<STYLE TYPE="text/css">
<!--
H3 { font-family:Lucida;
font-style:normal; color:blue }
BLOCKQUOTE { font-family:Arial;
font-style:italic; color:teal;
word-spacing:-0.2em }
-->
</STYLE>
The styles you defined will apply automatically to all instances of <H3> and <BLOCKQUOTE> throughout your document. You didn't have to use these tags-- you could have chosen LI, IMG, B, or any other valid HTML tag.
Notice the STYLE TYPE= declaration (MIME type) and the comment tags surrounding your style. It's important to use those comment tags to keep older browsers from displaying this data on-screen. This technique, by the way, is known as embedding a stylesheet.
Most CSS properties apply to most HTML tags. If they don't, the browser ignores them. Check out www.htmlhelp.com/reference/css/.
Using external stylesheets
Styles can live in external documents, in the head of the current document, or you can insert them on the spot. Each technique uses slightly different syntax, though. For example, you can create an external stylesheet by adding a few global styles to a blank text document, as in the screen above. Then save the file as sitestyle.css. In one of your site's documents, insert the following HTML code inside the header:
<LINK REL=StyleSheet
HREF="sitestyle.css" TYPE="text/css"
TITLE="Test Style">
The document will automatically use the BODY and H3 styles declared in the external CSS file. You can have multiple global stylesheets on your site and call different ones from different documents.
Roll your own
It won't be long before you'll want to apply styles to page elements that aren't necessarily associated with preexisting HTML tags. No problem, as only two things change. First, you must preface your selector (Danger, in this example) with a period.
.Danger {position:relative;
color:beige;
border:4ptlightgreen dotted; left:35pt;
background-image:url(back.image.gif);
text-align:center; height:50pt;
width:420pt; font-size:20pt; font-weight:bold }
Second, you must attach the style to elements manually. For instance, what if you want to highlight only two words in a paragraph with the Danger class? The <SPAN> element was invented for just this reason, to surround arbitrary chunks of text and apply styles to it. Your HTML would then look like this:
<P>As she saw the bucket coming down on
my head she yelled, <SPAN CLASS=Danger>
"Look out!"</SPAN>
The natural order
Because of the nature of inheritance, and because you can link to multiple external stylesheets from one document, there are bound to be conflicts to resolve. The most important thing to remember when CSS isn't doing what you want it to do is this: Go from the general to the specific. Here's a trick question: In what color will the text in <H3> below appear in a 4.0 browser?
<STYLE TYPE="text/css">
<!--
BODY { background: red; color: black }
H3 { font-family:Lucida;
font-style:normal; color:green }
-->
</STYLE>
</HEAD>
<H3><FONT COLOR="Blue">
This is not a love song!
</FONT>
</H3>
The answer: Blue. That's because the font color instructions are closer to the affected text than the CSS-controlled H3. Proximity to the affected content always wins .
Bend the rules
The rules of priority and inheritance make good sense, but there are bound to be times when you want to override them and make a parent or warring style win. To do that, just add ! important to the end of the style, and it'll whip any competition:
H1 {color: teal ! important; }
Distinguishing DIV from SPAN
As you dig into stylesheets, you'll notice these two unfamiliar tags appear frequently. SPAN was invented solely so CSS users would have a nondestructive place to hang their attributes; DIV has existed for a while. It's used to demarcate the presence of any kind of new object on a page. The biggest difference between them is that DIV is a block-level element and implies a line break, whereas SPAN does not affect the flow of the page.
Turn off underlining
Most HTML authors have at some point wondered how to turn off hyperlink underlining. Until now, that's been impossible. With stylesheets, it's as easy as attaching "text-decoration: none" to an Anchor style, like this:
A:link {color: cornsilk; text-decoration: none}
The thin blue line
To add a touch of design to an otherwise text-heavy page, surround a few paragraphs with a thin, color border to set them off. To add this to all your paragraphs, create a style in your document header (see example below) and then just use your normal <P> tags.
P { border-style:solid; border-width:thin; border-color:blue; }
Nail it down
In HTML, the position of any object--text, graphic, or multimedia component--is relative to the rest of the page's structure. If you add a paragraph to your intro, your prize graphic could end up below the fold--out of eyesight on the first page view. CSS changes all that, not just by letting you state every object's exact location (in pixels, inches, or points), but also by letting you hammer it into place for good. Give an object an absolute position, and it will be there, no matter what other text or graphics are competing for that spot. Here's how to do this:
.OurLogo { position:absolute; left:2in;
top:2in; width:3in; height:3in; }
Stack 'em up
So if you can nail down objects, what happens when you try and put two objects in one place on the screen? Objects simply stack up on top of one another quite gracefully. The default stacking order says that the first item laid down will land on the bottom of the pile, and the last will be on top. But you can change the stacking order by altering the "z-index" attribute as follows:
<DIV CLASS="pile" ID="image1"
STYLE="z-index: 3">
<DIV CLASS="heap" ID="image2"
STYLE="z-index: 2">
In this example, image1 is on the bottom and image2 is on the top. You can use any integer (positive or negative) for your z-index, but the highest number will always come out on the bottom and the lowest on top. Try letting a few objects overlap just slightly for some fascinating design effects.
Let your light shine through
Stacked objects can look great, if you plan properly, because your objects' native transparencies are respected. Letters can be seen through transparent .GIFs and vice versa. If that's not exactly what you had in mind, don't forget you also have control over the background properties for every rule. These backgrounds are all valid:
H1 { background-color: #000080; }
.OurLogo { background-color: transparent; }
BODY { background-image: url(/images/foo.gif); }
Magic static backgrounds
When a page scrolls, everything on that page scrolls with it, right? Not necessarily. With CSS, you simply tag the fixed argument to an object to make that object hold its position on the page, even as text and images scroll past or over it. Here's how:
BODY { background : cyan
url(your_image.gif) fixed }
It's the "fixed" part that nails things down. This, of course, will work with anything that takes a background.
Don't break older browsers
CSS was designed to integrate seamlessly with existing HTML, so it won't break old browsers. Still, it's possible to create CSS pages that look terrible in older browsers. The trick to is to build your pages in straight HTML using a 3.0 or earlier browser. Then apply your styles to that document and fine-tune it. Older browsers will ignore new tags they don't understand, and the CSS syntax will override the existing HTML, as long as you apply your styles in the right order.
3. Cascading Style Sheets Positioning Working
Draft
The CSS Positioning Working Draft gives you control over the exact position of text and images within a Web page by letting you define x and y coordinates. Now, you no longer have to place information within complex layers of nested HTML tables to control a precise page layout. In addition, CSS Positioning lets you define an element's z coordinate, which will place elements in front of or behind others.
Then there's layout control. Remember doing all that work to
design your page to perfection, only to discover
you're stymied by the myriad browser-rendering
differences out there? Now, you can, say, tile a .GIF
across just a slice of your page, make that animation
hang exactly one inch from the right margin, overlap
these three letters, and even make elements invisible.
Web layouts finally get to compete with print.
4. Support for DHTML & Scriptlets
Examples are from Microsoft
SBN
DHTML
Here's everything you need to create more-compelling Web pages in IE 4.0--the
tips, the tricks, and the HTML code.
If you still think Microsoft sticks only to its own standards, think again. In the past several months, the company has shown its willingness to play by Internet rules. While the question of whether it rewrote Sun's Java API for the sake of Windows remains unanswered at this writing, it's nevertheless true that Microsoft has thoroughly embraced HTML 4.0 and CSS standards. IE 4.0's push technology is fully standards-compliant (being derived from XML). And Microsoft's DHTML model supports Netscape's JavaScript as well as the company's own VBScript (Communicator does not support VBScript).
But Microsoft extended the standards while embracing them. Examples include scriptlets, which support existing standards but work best when coupled with Win32's COM technology, and a pile of IE-only CSS properties (like filters) that aren't in the official HTML 4.0 spec--yet.
But the trump card is an implementation of DHTML that's much more advanced than Netscape's. In fact, Micro-soft's DHTML is so well-constructed it's even got Mac-heads reconsidering. The game is all about temptation: Create a browser technology so compelling that site builders everywhere won't be able to say no to Microsoft standards. Microsoft's DHTML makes it easy to drop databases into programmable Web pages, turn static sites into intelligent apps, and take Internet object orientation to the next level.
In this section, we're going to look at some cool tricks you can pull off in IE 4.0 with DHTML. Because DHTML is just scripted CSS (not to be confused with scriptlets, Web pages based on HTML and script), everything it does requires programming. We won't go into JavaScript or VBScript here, but in most cases you can cut and paste, then alter the sample code we provide to suit your needs, much as you do with HTML.
Two caveats before you get rolling. First, if you care about backward compatibility with older browsers, test your pages thoroughly before going live. Browser-detection scripts are almost a requirement in some cases.
Second, if building standards-compliant sites is important, be sure to compare Microsoft's online reference manuals and tables with those of the W3C; Microsoft mixes in the extensions with the standards, without saying which is which. Of course, the company submits almost everything it invents to the consortium, but that doesn't imply acceptance.
The Two-Faced Web Page
With a few lines of JavaScript, you can make users think they've retrieved a fresh page in the blink of an eye. Of course, all you're really doing is flipping the display property on and off for objects and elements that have already loaded.
For example, the code below loads a page with a blue background, some text, and an image. Clicking on the image triggers the JavaScript function showMe(), which changes the background to cornsilk while swapping the text block and the image. In all cases, the style.display properties toggle to hide and reveal.
<HTML>
<HEAD><TITLE>Dynamic Styles</TITLE>
<SCRIPT LANGUAGE="JScript">
function showMe()
{
thebody.style.background = "cornsilk";
document.all.aHeading.style.display = "";
document.all.surprise.style.display = "";
document.all.hidethis.style.display = "none";
}
</SCRIPT> </HEAD>
<BODY ID=thebody STYLE = "background:red;
font-family: "Verdana"; color: black; 50pt">
<H3 ID=aHeading STYLE =
"display:none">Surprise!</H3>
<P ID=hidethis>The first page content goes here
<P>
<P ID=surprise STYLE="display:none">
fresh content goes here.
<DIV onclick="showMe()"><IMG
SRC="foo.gif"
WIDTH=113 HEIGHT=113 BORDER=0></DIV></P>
</BODY> </HTML>
JavaScript or VBScript?
DHTML can communicate with several scripting languages (theoretically any programming language), so how do you decide which one to use? Here's one place where theory and reality just don't converge well.
JavaScript has been on the Web longer than VBScript, and many more browsers support it. For the foreseeable future, JavaScript is the de facto standard and your only hope of creating cross-browser DHTML pages. Microsoft uses VBScript on many of its demo pages, but as soon as you surf outside its site, VBScript becomes as rare as dust in an Intel fab. Use it only if you have an IE-centric audience.
Get Rid of Those Dashes
The CSS declarations include lots of dashes, as in { background-color:pink } and {font-family:Verdana }. But in scripts, dashes often mean subtraction. To avoid the confusion, whenever you need to reference a CSS property that includes a dash, just remove the dash and make the next letter uppercase. For example, use style.backgroundColor rather than style.background-color.
The Magic Numbers
JavaScript lets you refer to the objects on a page either by name or by number. We've been using the name, until now. But sometimes it's easier to have DHTML count the number of, say, images on your page so you can refer to them mathematically.
In IE 4.0, this counting occurs automatically, so you can simply reference document.images[3], for example to refer to the fourth image in the document. Why? Because JavaScript, like many computer languages, starts counting at 0, so the first image referenced is document.images[0]. See the next tip for an example of this type of array in action.
Graceful Exits
The filters extension to CSS can create dramatic special effects and transitions when coupled with DHTML. For example, the code below creates a transition (a dissolve) similar to what you can achieve with PowerPoint.
<SCRIPT FOR=window EVENT=onload LANGUAGE=Javascript>
dissolver.filters[0].Apply();
dissolver.innerHTML = "<img src=dali.jpg>";
dissolver.filters[0].Play();
</script>
<div id="dissolver" style="position:relative;
width:347; height:330; top:20; left:30;
filter:revealTrans (transition=12,duration=8)">
</div>
Microsoft offers an online wizard at www.microsoft.com to help create dozens of automatic text and image transitions.
Remote Control
Your applications have all kinds of information tucked away in hidden menus and dialog boxes, so why shouldn't your Web pages? They can. JavaScript already offers some of this functionality, but DHTML improves communication between JavaScript methods and the objects on a page. An object's properties (such as its visibility) can easily be controlled remotely. For instance, you can use a mouseover on one object to change the content or style of an object on the other side of the screen.
For this example, you'll want to remember the difference between a CSS .class (which can occur several times on a page) and a #ID (which can occur only once on a page and is used for scripts in which the object needs to be treated as a unique element).
<STYLE TYPE="text/css">
<!--
#header2 { font-family: Symbol; font-style:normal;
color:pink; }
-->
</STYLE>
<h1 onmouseover="header2.style.fontFamily = 'Lucida';"
onmouseout="header2.style. fontFamily = 'Verdana';">
This is heading 1</h1></P>
<H2 ID=header2>This is heading 2</H2>
When the document loads, header2 is rendered in Symbol font. But when the mouse rolls over heading 1, heading 2 switches to the Lucida typeface.
Replacing Page Content
Because DHTML is so good at manipulating page content in real time, you can pull off some pretty cool tricks by marking off sections of a document with one of IE 4.0's special callouts, which include: innerTEXT, innerHTML, outerTEXT, and outerHTML.
These four properties work similarly. The TEXT varieties will take any content and strip out the HTML, rendering only the text. The HTML varieties respect the input's HTML. The inner and outer varieties control whether you're referencing content inside or outside the specified element. Let's use innerHTML to change part of a page based on some form input. This example, as written, requires no other JavaScript or CSS declarations to work.
<div id=ThisWillChange>This sentence is about to
change, depending on what the
user types in to the text box.
</div>
<P>
<input id=TextField type=text style="width:550">
<input type=button value="Click me to change"
onclick="ThisWillChange.
innerHTML = TextField.value">
The innerHTML property says whatever appears on the page as HTML content between the start and close of the referenced ID will be affected by the operation. In this case, it's replaced by a value the input form returns. If a user includes HTML code in her input, the output will be rendered accordingly. Change the property to innerText and the same output will display the HTML code along with the output. Hint: This is a good start toward building an interactive HTML tutorial: Users can type in code, click on a button, and see the results instantly.
A New Kind of Online Database
One of DHTML's more practical applications is its data-binding technology, which attaches database content to Web layouts and lets users sort, filter, and perform calculations on the fly. Data-binding has two flavors: Advanced Data Connector, or ADC (for tapping into large, remote databases) and Tabular Data Control, or TDC (for manipulating small, downloadable data sets, like contact lists, and smaller inventory reports).
With TDC, the data is all inside the browser, the page doesn't need to be reloaded from the server to display a new subset of the content, and users can page through databases one record at a time without ever calling out to the server to refresh the page. This can be done via the Previous/Next buttons, radio buttons, or other on-screen controls.
Finally, if you do want standard HTML tables but don't feel like doing the tedious formatting, data binding can create complex tables for you, using information from a database. Simply state the OBJECT name and create a single row naming the fields you want to extract; DHTML will do the rest of the grunt work for you, on the fly.
Data binding sounds dry but is bound to have huge implications for online databases, personal data storage, weblications, and other functions. Go to Microsoft's web site, where you'll find tons of documentation and sample code.
Put Your PIM Online
Ever found yourself in a hotel in, say, Podunk, New Jersey, and realized you'd left an important phone number in your office PIM? Why not use data binding to put your contacts on a private Web page so you always have instant access? Alternatively, you can use this data-binding technique to put the company contact list on your intranet. First, export your contact list in standard pipe (|)-delimited format, like this:
name | phone | email | address | title
and save it as contacts.txt. Then insert this into a Web page:
<object id="PIM"
classid="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83"
border="0" width="0" height="0">
<param name="DataURL"
value="contacts.txt">
<param name="UseHeader" value="True">
</object>
<TABLE CELLSPACING=0 CELLPADDING=0>
<TR>
<TD ALIGN=RIGHT VALIGN=TOP>
<LABEL FOR=name>Name: </LABEL></TD>
<TD ALIGN=LEFT VALIGN=TOP WIDTH="10"></TD>
<TD ALIGN=LEFT VALIGN=TOP>
<DIV id=name TYPE=text
DATASRC=#contacts DATAFLD="name">
</DIV></TD>
</TR>
Repeat the table row for each field you want to page through, changing the DATAFLD line to match the name of each field. Repeat as many rows as you like; order isn't important. Now, upload contacts.txt to your Web server alongside this HTML document, and you're wired from wherever you are.
Adding Page Content
You don't have to replace the contents of a string, and you can add to what's already there. Instead of using innerHTML, use the insertAdjacentHTML or the insert-AdjacentText property, which places the specified string before or after existing content. These properties take one of four parameters: BeforeBegin, AfterBegin, BeforeEnd, and AfterEnd.
<SCRIPT LANGUAGE=
"Javascript">
function insertPara()
{ document.body.
insertAdjacentHTML
("BeforeEnd", "
This wasn't here before, was it?"); }
</SCRIPT>
<input type=button value="Click me to change"
onclick=" insertPara()">
"This wasn't here before, was it?" appears below the button as soon as you click on it.
Why scriptlets over Active X or Java?
One reason for Visual Basic's enormous popularity is the component model it has pioneered. For building small to medium-size GUI applications, it yields productivity improvements and ease of use that programmers raised on Charles Petzold's classic Programming Windows still find hard to believe. Because a sophisticated Web-based application is essentially a small to medium-size GUI application, the obvious question is how to bring the component model of Visual Basic and Delphi to Web development. Essentially, there have been two approaches: ActiveX Controls (the same controls used so successfully in the current versions of VB and Delphi), and Java applets.
Except on Intel-based Intranets, ActiveX controls have essentially been nonstarters. In spite of some attempts at extending them to other platforms, they remain in essence binary code that's standard for Win32 platforms. Their security model is also weaker than Java applets'. ActiveX controls support only code signing, rather than the three-prong approach supported by Java--virtual machine, security manager, and signing.
Java applets (especially when recast as JavaBeans) show more promise. Still, the number of sites using Java is surprisingly small, and many corporate sites refuse to allow downloaded Java applets to be run for fear of some as yet undiscovered security bug. In addition, Java is not the easiest language in the world for Web developers to learn, and a critical mass of JavaBeans has not yet appeared.
What Is a Scriptlet?
It is hard to know how an idea sees the light of day, but clearly some folks at Microsoft had the insight that DHTML pages have at least at one level exactly the same features as Visual Basic controls, including:
*properties to describe how the pages look and feel;
*methods to control how they behave;
*events that the objects can be programmed to respond to.
From that point, it must have been no great leap to decide to build a reusable object technology by allowing DHTML pages to be treated as self-contained objects. Thus a scriptlet is a complete Web-ready HTML page that includes information that allows you to work with it as a control: You can get and set its properties, call its methods, and so on. More precisely, we might say that a scriptlet is a Web page based on DHTML that can be reused as a component with any application that supports such components.
Scriptlet Pros and Cons
The advantages to using scriptlets are:
*It is much easier to learn DHTML and scripting than Java.
*DHTML pages can be reused.
*Scriptlets have excellent performance; they're as fast as DHTML.
*Scriptlets are lightweight, like any other page, with
minimal overhead.
*Scriptlets may eventually be truly cross-platform, with no virtual machine compatibility problem
*Scriptlets are as secure as DHTML. Like Java applets, scriptlets must be loaded from the same Web servers as their container pages.
The disadvantages are:
*Scriptlets are not yet truly cross-platform. There is no guarantee that Netscape will adopt scriptle technology. Microsoft's support, currently available only in Internet Explorer 4, depends on the company's Component Object Model (COM), which is not a cross-platform technology.
*A programmer working strictly in DHTML is limited, compared with what a skilled programmer can do in a full-fledged programming language such as Java. (But a DHTML programmer can do a lot; for example, you could build a "nervous text" scriptlet that works exactly like the famous Java applet of that name.)
*There is no way to keep a scriptlet's code hidden.
Scriptlet Mechanics
Any DHTML page can be embedded as a scriptlet via a new MIME type that Microsoft has submitted to W3. You use it in the <OBJECT> tag, as in the following prototype:
<object type="text/x-scriptlet"
data= "ScriptletUrl
.html">
</object>
The scriptlet is named in the data parameter in the form of a standard URL. Notice that unlike ActiveX controls, there is no inscrutable CLASSID in the scriptlet object tag. As with any use of the <OBJECT> tag, you can also pass parameters to the scriptlet with tags like these:
<param name="ImageName" value="
PCMagLogo1.jpg"> <param name="Speed"
value="100">
Like Visual Basic controls, scriptlets need to expose properties, methods, and events to the users of the component. When you build a scriptlet using VBScript, the coding style is very close to the way you build an ActiveX control in VB5.
Let's start with methods. They are simply the functions or procedures that begin with a public_prefix. (Case, as with
any VBScript code, is irrelevant.) For example, the signature for the following could give a public Start method to an
animation scriptlet:
Sub public_Start()
'code goes here
End Sub
Any functions or procedures not prefixed with public_ are private to your scriptlet.
Properties use two prefixes in pairs: public_get_ and public_put_ (equivalent to VB5's Property Get/Let) If you leave out the corresponding public_put to a public_get, you have a read-only property. For example:
Sub public_put_AnimationSpeed(Speed)
gives you a way to set an animation's speed property. (VBScript, unlike JavaScript, maintains a distinction between Sub routines, which don't return a value, and functions, which do.)
Following standard object-oriented programming principles, you can use private instance fields (data members) to encapsulate the property values. It is true that a variable with the public_ prefix is the equivalent of a read/write property, but most programmers would discourage that formulation, preferring to permit access to private data fields only through explicit member functions.
Note that when you refer to a property or method of the scriptlet from a page that uses it, you do not include the prefix. For example:
Animation Scriptlet .AnimationSpeed = Speed
is how your code using the scriptlet would look.
Important Events for Scripting
| Important Events for Scripting | |
| Event | Generated When |
| OnMouseOver | Mouse pointer moves to the element. |
| OnMouseOut | Mouse moves out of the element. |
| OnMouseDown | Mouse button pressed inside the element. |
| OnMouseUp | Mouse button released inside the element. |
| OnMouseMove | Mouse pointer moves in inside the element. |
| OnClick | Left mouse button is clicked on the element. |
| OnDblClick | Left mouse button is double-clicked on the element. |
| OnKeyPress | Key is pressed and released. Holding a key down triggers multiple events. |
| OnKeyDown | Key is pressed . Triggers one event no matter how long the key is held down. |
| OnKeyUp | Key is released. |
Go to Topic 5