Be careful with FRAMES place your Meta Tags with some basic text inside the tag; put Meta Tags on ALL sub-pages mix them up on each page so they appear different to the engine; in your META "keywords" use up to 1,000 characters, including spaces and commas; use your most important keyword, for that specific page, in the tag on each page; manually submit your URL(s) to each search engine to verify it was received.
Practice Link Trading: Link your web site to lots of relevant sites and ask them to link to yours. When your web site has many other web sites linking to it, it will gain higher positions in the search results of several top search engines: AltaVista, Excite, Google, Infoseek, Inktomi, Northern Light and HotBot.
Make sure each of your pages has a
tag that provides a concise, helpful description of the page's contents. Most search engines display the text of your tag as the "headline" for your entry in the search results list. Most spiders also extract search keywords from your tag, so your page will be more likely to reach its intended audience if it contains words that your audience is likely to use when searching for the information on your page.
Do you find yourself faced with a Web site whose text stretches slothfully across the screen? Boring? It doesn't have to be that way, even if you suffer from Htmlphobia. Webgrammar to the rescue!
You already know the basic codes for the page, right?
Let's see how to make it a bit easier for the reader. We'll begin by taking a page with nothing but text from margin to margin and doing a "Before" and "After" scenario.
Go to http://www.webgrammar.com/tut-1.html. That's your first example. Is there anything there that compels you to read on? Or do you think it looks like blobs of ink on white paper?
I created this page using the heading tags for the article's title, letting the rest of the text go to the browser default (in most cases, Times New Roman for PCs and Times Roman for Macs).
Exit the first page and click on http://www.webgrammar.com/tut-2.html. Same words, different formatting.
The first thing I changed was the body tag. Instead of by itself, I used .
I chose the page (body) background color from the color list at HTML Goodies, http://www.htmlgoodies.com/colors.html.
Did you know that older browsers will default to a gray background if the designer doesn't specify another color or white? So, if you designed everything for a white background, code , followed by
.
Interested in placing your text ad in this spot? Click Here
I wanted the entire page indented, and for this I used the blockquote command immediately following the body tag. Make sure the very end of the document reads:
.
Next I centered my heading, using <"CENTER"> and <"/CENTER"> to surround it. But I wanted three more things to make the heading stand out. I called out the type of font to use, the font color, and bolded the text. The code looks like this:
Marketing Tips for Your Small Business
Why do I use Arial and Helvetica? To accommodate both PC and Mac users.
Before going to the article itself, I used a horizontal rule to set off the heading from the body. Because I wanted a partial width, I used this command: . This is fun. You can specify just how wide the horizontal rule will be, and where it's placed! To have the rule run the entire width of a page, just use .
To launch the article, I used tags around the first paragraph. I wanted a bit of a change in indenting. You will notice that the entire page is enclosed in blockquote. It's okay to have one set of blockquote tags inside another.
Throughout the site, you'll find some text bolding, but I recommend you use it lightly. And never have your entire text in bold. It's like using all caps: it shouts, pushing the reader away. Your goal is to draw the reader to your text and make it ever so easy for him/her to understand. Graphic backgrounds behind text may be beautiful, but if they obscure the words, you've missed the point.
On to bullets. There are three types you can use. The default is "disc," and the other two are "square" and "circle." Here's a sample of how to call out the square (shown in the article):
Your text
Throughout the article, whenever I used a URL, I spelled it out, e.g., http://www.webgrammar.com/marketing.html. I usually bold the text inside the tags, as well. The reason for spelling it out is that there's less room for error, and if necessary, the reader can copy and paste the text into the browser's address / location window. Generally, however, the code transforms the text into a hot link that takes the visitor to the designated location.
Another way to manipulate text is to use the tags. The text will come out in a monospace font like Courier, but you can control the text using the typing techniques of pressing the space bar to move text to the right, and pressing the Enter key to move to the next line. I used these tags for the signature lines, to give more interest to the page and set them apart.
I ended and set apart the article by using an tag.
A few more tips:
1. Don't manually underline text - visitors expect underlined text to be a hyperlink. If you want emphasis, use bold or a different font color.
2. Left-justified text is much easier to read when you are writing an article or presenting consecutive paragraphs. Be selective about centering text in the body of a page: poems may read better centered, as may small phrases, but never center bulleted or numbered lists or articles. Make it readable, useable.
3. Avoid using italics. Given the low resolution of today's monitors (72-100 dpi), italics make text even more difficult to read.
Are you still skeptical of your ability to make a few changes in an existing Web document? Why not go to Notepad, and create a simple document? Name it simpledocument.html. Save it to your hard drive or your Desktop. It's saved as ASCII text with an html extension. Work on it, using some of the above examples and a paragraph or two of your own words. Save regularly as you work.
When you're finished, close it and go to your browser. Click File/Open, find the document and open. You'll then be able to view it in living color. And if it's awful, no one will know: it's not on the Internet . . . it's just on your hard drive!
If you have more questions about shockingly simple Web design, go to Webgrammar's Place Design Page. I have links to some of the Web's finest tutorials. And if you have any questions regarding simple stuff, contact me and I will either help you or find you an expert.
P.S. To learn more about italics, fonts, desktop publishing, and screen resolution, go to http://www.ossweb.com/presentations.Article by Judy Vorfeld, of Ossweb.com
Want to make your site LOOK like it loads faster? Always use HEIGHT and WIDTH attributes in your image tags, it makes the text on your page show up without having to wait for images to load.
You can filter the options available in a select form element by removing option elements from the list. Do this by setting the option to null in the select element's options array:
The select form element consists of one or more options designated by the OPTION tag. You can add to this list dynamically by creating a new option and then appending the item to the select element's options array. To add an option to a list, first create the new option:
opt = new Option("Display Value", "value");
Then, check the length of the options list and add the option to the end of the list:
ct = document.forms[0].selectelement.options.length;
document.forms[0].selectelement.options[ct] = new Option("Display
Text", "value");
CAPTURING EVENTS IN NETSCAPE NAVIGATOR
Netscape's Navigator allows you to capture events on certain objects such as the document or window, or on a specific layer. You use the captureEvents and releaseEvents functions to capture and release an event, respectively. For instance, to capture the mousedown event on the browser document object, use the following:
The first line starts the capturing of the mousedown event anywhere in the document, and the second assigns the function "test" as the event handler. To release the mouse event, use this:
document.releaseEvents(Event.MOUSEDOWN)
In the next tip, we'll show an example of cross-browser event handling.
CROSS-BROWSER MOUSE EVENT HANDLING
In our last tip, we showed you a technique for capturing the mousedown event on the document object. In this tip, we'll look at a cross-browser event handling routine. First, you have to capture the event with Navigator:
if (navigator.appName == "Netscape")
document.captureEvents(Event.MOUSEDOWN);
Next, for both Internet Explorer and Navigator, assign an event handler function to the mousedown event:
document.onmousedown=process_test
Last, create the mousedown event handler function:
function test(evt) {
if (navigator.appName == "Netscape")
alert(evt.pageX);
else
alert(window.event.clientX);
}
Netscape sends its version of the Event object through the event handler function, and IE provides access to its event object on the window object. In the function, cross-browser code is used to access each browser's event object. Then, the horizontal position of the mousedown event is printed out in an alert box, again using the browser-specific event property (pageX for Navigator, clientX for IE).
In the next tip, we'll continue this exercise on cross-browser event handling by moving a DIV block to wherever the mousedown event occurs.
INTERACTIVE MOVEMENT OF A DIV BLOCK
In the last couple of tips, we described how to capture events for Navigator and then how to handle events for both Internet Explorer and Navigator. This tip concludes this event handling example by capturing the mousedown event for the document, and moving an absolutely
positioned DIV block to the location where the mouse event occurs.
Now, clicking anywhere on the page moves the "Hello" message to that location.
MODIFYING THE HTML PAGE BASED ON OPTION SELECTION--INTERNET EXPLORER
You can replace the content of an absolutely positioned DIV or SPAN element with content selected from an option in a select list. Our last tip demonstrated how to do this for Netscape's Navigator. This tip demonstrates the technique to use for Internet Explorer. For instance, to change a header to different sizes, create the positioned DIV block:
You must use the mnemonics for the angle brackets (< for < and > for
>);, otherwise, the HTML will be implemented instead of displayed.
Next, add in the JavaScript change function, which writes the new
string to the DIV block:
function change() {
// get entry
indx = document.forms[0].elements[0].selectedIndex;
str = document.forms[0].elements[0].options[indx].text;
if (navigator.appName == "Microsoft Internet Explorer")
test.innerHTML = str;
}
Microsoft has provided the innerHTML attribute, which can be used to replace the existing HTML of the specified element--in this case, the absolutely positioned DIV block "test."
MODIFYING THE HTML PAGE BASED ON OPTION SELECTION--NAVIGATOR VERSION
You can replace the content of an absolutely positioned DIV or SPAN element with content selected from an option in a Select list. This tip demonstrates how to do this for Netscape Navigator. For instance, to change a header to different sizes, create the positioned DIV block:
You must use the mnemonics for the angle brackets (< for < and > for
>); otherwise, the HTML will be implemented instead of displayed.
Next, add in the JavaScript change function, which writes the new
string to the DIV block:
function change() {
// get entry
indx = document.forms[0].elements[0].selectedIndex;
str = document.forms[0].elements[0].options[indx].text;
if (navigator.appName == "Netscape") {
document.test.document.write(str);
document.close();
}
Each absolutely positioned block such as the DIV block shown here has its own version of the document object. You can write to this document object to replace the existing page contents. Make sure you close the DIV's document to force the browser to redraw the element.
The next tip will demonstrate how to change the page contents for Internet Explorer.
EVENT HANDLING REFERENCES
Read more about Navigator's event handling in chapter 10 of Netscape's client-side JavaScript User Guide at http://www.pcworld.com/r/tw/1,2061,tw-dhtml1,00.html
Read more about Internet Explorer's event handling in Microsoft's MSDN Online Web Workshop reference page for the event object at http://www.pcworld.com/r/tw/1,2061,tw-dhtml2,00.html
INTERNET EXPLORER FILTERS
Microsoft's Internet Explorer has some interesting filter effects that you can apply to most Web page objects. For instance, one of the filters is the "glow" filter, which creates a glowing "edge" around whatever content is being modified:
In this example, the DIV block is positioned, absolutely, at 20 pixels from the top-left side of the page, and a red glow is applied to the block contents--an H1 header with the word "Hello." You can read more about filters at http://msdn.microsoft.com/workshop/author/filter/filters.asp
Note: These work only with IE 4.x and up (not with Navigator).
ACCESS AN ONLINE DHTML TUTORIAL
You can discover more about the basics of Dynamic HTML by accessing an online DHTML tutorial I created, located at: http://www.yasd.com/samples/dhtml/tutorial.htm
The tutorial was originally created for CNET's December 1998 builder.com convention.
CREATING A SHADOW EFFECT
You can create a shadow effect for your text by creating foreground and background copies of the text and stacking them, offsetting the foreground text slightly from the background. You use the CSS z-index attribute to determine which block of text is placed in what position in the stack.
For instance, the following creates a shadowed header, with the darker background shadow placed behind and a bit above and to the left of the foreground text. Both text blocks are set to a font of Arial, as you want the text to be identical except for position, color, and z-index.
Hello, World!
Hello, World!
C
REATING ANIMATION EFFECTS WITH DHTML AND A TIMER
Animate your pages by creating a function that moves content based on timer events. For instance, you can create a positioned DIV block as follows:
Hello, World!
You can animate this block by using the window object function "setTimeout" to create a timer event that calls the animation function, and start the timer by calling setTimeout in the onLoad event for the document:
In the animate function, test for a condition and reset the timer if the condition isn't met. In our example, the block is moved until the left position is at 300 pixels:
var pos = 10;
function move() {
if (pos < 300) {
pos+=10;
if (navigator.appName == "Microsoft Internet Explorer")
hello.style.pixelLeft = pos;
else
document.hello.left=pos;
setTimeout("move()",200);
}
}
PROTECT YOUR MOUSE-SENSITIVE CONTENTS UNTIL THE PAGE IS LOADED
One problem with using mouse-capturing events is that the Web page client can be moving his or her mouse over your page before the page is loaded and before all the necessary objects have been loaded. This can generate an Object Not Defined type of error that can be disconcerting to the page client.
To prevent this, hide your mouse-sensitive content until after the page is loaded, and then show the content in a function that can be called by the onLoad event handler:
LAYERED FORMS
You can hide and show HTML different forms by enclosing the forms completely within absolutely positioned DIV blocks, and then setting the enclosing block's visibility. You can't, however, split a form across many positioned DIV blocks because of Navigator's implementation of "layers" (created with the LAYER tag or using positioned DIV blocks).
REPLACING PAGE CONTENT--NAVIGATOR
You can replace the content of a layer with Navigator by using a combination of document.write and document.close on the layer. For instance, you can create a positioned DIV block using something similar to the following:
Hello
You can replace the content by doing the following:
document.test.document.write("
Hello, World!
");
document.test.document.close();
Each layer gets its own document object, and the write method creates new content in the document. The close method then forces a redraw of the new content. Note that any CSS applied to the block is removed when the contents are replaced.
CLIPPING CONTENT
You can clip content by setting the CSS clipping region to be much
smaller than that required for the content:
Use clipping as the basis for creating animated scrolling effects. For
instance, to scroll "down," set the top and bottom clip values to 0,
rect(0 100 0 0), to totally clip the object. Then, use script to
unscroll the object to its full height:
if (navigator.appName == "Netscape")
document.objectname.clip.bottom=300;
else
objectname.style.clip="rect(0 100 300 0)";
You can create a scroll animation by setting the object's height in
increments until the full object is exposed.
CREATING A BORDER EFFECT
Add a pretty border to highlight an image by using the CSS border
properties. For instance, the following surrounds an image with an
outset style of border, 8 pixels wide and magenta colored:
DEBUG EVAL BY PRINTING OUT EVAL STRING
If you use eval to evaluate (implement) DHTML effects, you can debug
the results by assigning the evaluation DHTML to a string and printing
this out with an alert box:
var str = docobj + "layername" + styleobj + "visibility='hidden'";
alert(str);
eval(str);
Using this technique, you can make sure that the parts you are pulling
together form a syntactically correct whole.
NEW AND IMPROVED DOM IN 6.0 BROWSERS
Internet Explorer 5.0 and the upcoming Navigator 5.0 support the W3C
recommended Document Object Model (DOM), Level 1. Because of this
cross-browser support, creating DHTML effects that work with both
browsers has just become a whole lot easier. Read more about the DOM
at the World Wide Web Consortium (W3C) Web site at: http://www.w3.org We'll also be covering more on the DOM in next month's tips.
REPLACING PAGE CONTENT--INTERNET EXPLORER
Microsoft has provided an attribute, the innerHTML attribute, which
can be used to replace the HTML content of an element. For instance,
you can create a positioned DIV block using something similar to this:
Hello
You can replace the content by doing the following:
test.innerHTML = "
Hello, its me
";
Note that innerHTML preserves the CSS setting for the block. To remove
the CSS, use the outerHTML attribute instead.
ALIGNING HTML TABLES
You're probably aware that you can align an image to the right, left,
or center of other Web page contents, but you may not be aware that
you can do the same with an HTML table.
Sizing a table to be narrower than the Web page creates a sidebar for
the page contents, much as it would appear in print media such as
magazines. For instance, you can align a table to the right of
existing Web page contents using a table tag definition similar to the
following:
The ALIGN attribute is deprecated with HTML 4.0, but current browsers,
including the Mozilla Open Source browser, still support this
attribute--at least for now.
TRANSITION EFFECTS WITH CLIP
You can create a cross-browser transition effect using the CSS clip
property. For instance, to transition between a header of one color to
another, you can create the original and transitions headers in
separate DIV blocks, layered on top of each other; the "transition to"
block is located at the topmost (highest z-index position):
This is your DHTML!
This is your DHTML!
The "transition to" block is clipped all the way to the left, by
setting the right-side clip value to the same value as the left-side
clip value--0 pixels.
Next, create a function that will "add" to the current right-clip
value when a timer event occurs:
var right = 0;
function transition() {
if (right < 300) {
right = right + 10;
if (navigator.appName == "Microsoft Internet Explorer")
two.style.clip="rect(0px " + right + "px 150px 0px)";
else
document.two.clip.right = right;
setTimeout("transition()",100);
}
}
The right side of the clipping region is increased with each timer
event, creating a transition effect as the "hidden" content is
displayed, incrementally. The whole effect is started by a first call
to the transition function, based on whatever event you choose.
This effect works with Navigator 4.x and Internet Explorer 4.x and up.
MOZILLA AND MOZILLAZINE
Until Navigator 5.0 is released, you can try out the examples with the
pre-alpha and alpha binary releases of Mozilla, available at
http://www.mozilla.org
Read more about Mozilla at the MozillaZine site:
http://www.mozillazine.org
MOZILLA AND NAVIGATOR 5.0
Navigator 5.0 beta should be released . . . some time, we hope soon.
This version of the browser is based on the Mozilla Open Source effort
and should support HTML 4.0, CSS 1 and 2, XML, and other standards.
In the next few weeks, the DHTML tips will cover examples compliant
with these standards that work with Internet Explorer 5.0 as well as
Navigator 5.0. Read more about what Navigator will, and won't, support
in an article I wrote for DevX at:
http://www.pcworld.com/r/tw/1%2C2061%2Ctw-dhtml1209xx%2C00.html
PSEUDO CLASSES AND ELEMENTS
According to the CSS2 specification released by the World Wide
Consortium (W3C), styles can be applied other than just to elements
within the document tree. For instance, we know that we can change the
color of the font contained in all paragraphs, using a style setting
such as this:
P { color: red}
We can also apply a style to a specific named paragraph, using
something like this:
P.test { color: red}
However, sometimes we might want to apply a style to an element based
on its position relative to other elements, or to an element in a
specific state. The pseudo classes and elements extend the CSS to just
such uses.
For instance a popular pseudo-class is :hover, applied to the anchor
element (A), and which only applies when the Web page reader's mouse
is over the hypertext link:
TipLink Reference
This example works with Internet Explorer 5.0 and Mozilla build M11
(Navigator 5.0 Open Source).
PSEUDO-ELEMENTS
As mentioned in the last DHTML tip, some styles are applied to
elements and classes outside the HTML document tree. This tip is about
the :first-letter pseudo-element, which applies to the first letter of
the contents defined by the element.
To demonstrate, we'll create a style sheet that sets the first-letter
pseudo-element text to be larger than the other content text, a red
color, and bold. The text is also floated to the left so that text
appears dropped compared to the other text. The styles and the
document elements to create the effect are
Tips
Another psuedo-element is :first-letter, which applies the first
letter of the pseudo-element tag
This example works with Mozilla (Navigator 5.0 Open Source).
HIDDEN HTML NOTES
Do you ever leave sticky notes on the refrigerator at home for your housemates to see? Do you ever leave sticky notes on your own computer monitor or desk for you to see? These kinds of temporary reminders are handy--even in cyberspace. FrontPage offers Comments. You can use Comments to leave yourself notes on some aspect of page design or to pass ideas along to others on a team who may follow your contributions to the page. The Comments appear when a page is being edited but not when it's being browsed. To include Comments:
Place your cursor on the position on the page where you want the Comment.
Choose Insert + FrontPage Component.
In the Insert FrontPage Component dialog box, select Comment and click OK.
Type your notes in the Comment dialog box that opens.
When you're done, click OK.
Your comment appears in colored text on the page, preceded by the word Comment." Remember: You can see Comments only in the Editor, not in a browser.
IDENTIFYING SCRIPT WITH TYPE
Since JavaScript was first released, the type of scripting language and the version of scripting engine has been identified using the LANGUAGE attribute:
Some content
Some content
Some content
Some content
Some content
Some content
This example works with Internet Explorer 5.0 and Mozilla M11 and up
(Navigator 5.0 Open Source).
ACCESSING AN ELEMENT USING THE DOM
The W3C (World Wide Consortium) has issued a recommendation for the
Document Object Model, Level 1 specification. Any browser that
implements this specification will then support DOM access of
elements.
The W3C has also provided a ECMAScript (scripting) binding for the
DOM, providing methods and objects that can be accessed using
client-side script. For instance, you can create a "named" (id)
element in a page:
Some document content
In script, you can dynamically access this element by name using the
DOM method getElementById:
var itm = document.getElementById("test");
This method works only with browsers that support DOM Level 1.
ACCESSING HTML ELEMENTS THROUGH HTML OR CORE DOM
The W3C Document Object Model (DOM), Level 1, has two defined models.
The Core model is a lower-level DOM, and page elements can be accessed
using a method such as getElementsByTagName, and then looking for the
element by the id:
theelements = document.getElementsByTagName("P");
alert(theelements["test4"].id);
The second model is the HTML DOM, a higher level model consisting of
objects defined for each type of HTML element, such as HTMLFormElement
and HTMLParagraphElement. You can get a specific element using the
getElementById and providing the id:
itm = document.getElementById("test4");
alert(itm.id);
ACCESSING HTML ELEMENTS THROUGH THE HTML DOM
The last tip demonstrated how to access HTML elements using the W3C
Core DOM, a lower level set of objects that can be used to access
objects within a Web page.
The second model supported in the W3C Level 1 DOM is the HTML DOM, a
higher level model consisting of objects defined for each type of HTML
element, such as HTMLFormElement and HTMLParagraphElement. You can get
a specific element using the getElementById and providing the id:
itm = document.getElementById("test4");
alert(itm.id);
ALTERING HTML ELEMENT ATTRIBUTES THROUGH HTML DOM
The last tip demonstrated how to access an HTML element using the W3C
Core DOM. You can also modify the alignment of the paragraph using the
HTML model as follows:
itm = document.getElementById("test4");
itm.align="center";
This example works with Internet Explorer 5.0 and Mozilla M11 and up
(Navigator 5.0 Open Source).
CHANGING THE CURSOR WHEN IT'S OVER AN ELEMENT
The CSS2 style specification has a cursor property that can be used to
change the cursor style when the Web page reader moves his or her
mouse cursor over the element. For instance, you can change the cursor
to a crosshair when the mouse cursor is over the DIV block by using
this:
This works with CSS2-compliant browsers only.
DIFFERENCES BETWEEN VISIBILITY AND DISPLAY
You can hide content within a Web page in two ways. The CSS Visibility
attribute allows you to hide or show content, but the content still
maintains its position within the Web page and still affects the page
layout.
The Display attribute, on the other hand, can be set to a value of
"none," and not only is the element removed from the page display, it
is also removed from the page layout:
This works with CSS2-compliant browsers only.
USING THE STYLE ATTRIBUTE TO MOVE A PAGE ELEMENT DYNAMICALLY
CSS is applied to an HTML element through the use of the STYLE
attribute. The STYLE attribute can also be used to access and
dynamically change the CSS styles for a specific element, if the
browser supports the dynamic modification of CSS styles.
To demonstrate, the position of a page paragraph can be changed by
accessing a paragraph element and modifying the left and top CSS2
attributes, defined in the paragraph's STYLE attribute:
Tips
Some content
This example works with Internet Explorer 5.0 and Mozilla M11 and up
(Navigator 5.0 Open Source).
CHANGING SELECTION ATTRIBUTES
Level: Beginner
Category: Forms
Browsers Targeted:
* Internet Explorer 3
* Internet Explorer 4
* Internet Explorer 5
You can change selection boxes from list boxes to combo boxes by
changing their size attribute. If size is 1 or less, then select boxes
act like drop-down list boxes, while setting size greater than 1 will
display that many entries in the list box, as follows:
With a size of "4", four items will appear in the list box. If
size="1", then the box becomes a drop-down box instead.
CREATING DROP CAPS
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
Drop caps (enlarged letters that start out a page or paragram) can be
implemented fairly easily using a few basic CSS properties. One of the
most potent is the float property, which causes the contained element
to float to the left or right of the container. A simple drop cap may
look something like the following:
T
his is an example of a drop cap at work.
In general, drop caps work best when done within tags. You may
also want to turn it into a general style rule in a style sheet--this
will make it simpler to use drop caps more than once in your
documents, and it makes your code easier to maintain.
This is an example of a drop cap at work.
The margin-top may vary somewhat depending on the typeface that you
are using and the size of the font, so you should experiment with it
when designing your page. Note as well that such drop caps don't
currently work with Netscape Navigator 4.x, as Navigator doesn't
recognize the float CSS property.
CREATING SIMPLE TOOLTIP TEXT
Level: Beginner
Category: HTML Attributes
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
A well-known feature of HTML is that you can use the ALT attribute on
an image tag to create a pop-up ToolTip (a light yellow text box
describing the image). What is less well known is with IE4 and above
you can also set the TITLE attribute for nearly any element in HTML to
do the same thing. For example, you could set the TITLE for a set of
unfamiliar terms so that it contains definitions for that term, as
follows:
There are a number of ways that you can handle the manipulation of
distributed systems, including RMI, DCOM, CORBA, and XML.
When you hover over the words in question, a ToolTip will pop up,
explaining the abbreviation. Note that because you can't keep HTML
notation in attributes, you can display only unformatted ToolTip
information.
DETERMINING DELIVERY DATES
Level: Advanced
Category: Scripting
Browsers Targeted: All
My wife has a baby on the way, and one of the things that I always
have trouble with is keeping track of what stage of development the
baby is in. Fortunately, you can use a few JavaScript Date objects to
create a mini-baby tracker.
This particular project makes use of three distinct dates--the
estimated conception date of the baby (if that's unknown, most
physicians place it ten days after the end of the last menstrual
period), the current date, and the estimated date of birth. In
addition to providing a useful service, this example shows how you can
determine one date from an offset of another date.
The key to understanding this is to realize that internally, all dates
are stored as the number of milliseconds from a specific target date;
in the case of JavaScript (and in general), that date has been
arbitrarily set to January 1, 1970. By representing dates in this
fashion, you can effectively do simple arithmetic on the date to get
another date.
For example, if you subtract one date from another, the result is the
number of milliseconds between the two dates. Similarly, the getTime()
function returns the number of milliseconds from January 1, 1970, to
the date specified. Thus, to find the due date, I calculated the
number of milliseconds in 280 days, the normal period of gestation for
a human fetus, and added it to the number of milliseconds from the
reference date to the date of conception.
Just a cautionary note: Please be aware that this technique should not
replace one's doctor or midwife. Babies are notorious for missing
their "due" dates, since there are many things far more important in a
doctor's visit than the estimated time that the baby will pop out into
the world.
<script>
function calcDates(){
var monthNames=new Array("January","February",
"March","April","May",
"June","July","August","September","October",
"November","December");
var conceptDate=new Date(conceptionDate.value);
var currentDate=new Date();
var numMS=currentDate-conceptDate;
var numDays=Math.floor(numMS/(1000*60*60*24));
var numWeeks=Math.floor(numDays/7) var
dueDate=new Date(conceptDate.getTime()
+1000*60*60*24*280);
var buf="You are currently "
var daysIntoWeek=numDays-numWeeks*7;
if (daysIntoWeek==0){
buf+="entering into "; }
else {
buf+=daysIntoWeek + " days into ";
}
buf+="Week "+numWeeks+" of your pregnancy."
buf+="Your anticipated due date is
"+dueDate.getDate()+" "+monthNames
[dueDate.getMonth()]+" "+dueDate.getYear()+".";
results.innerHTML=buf;
}
</script>
Please enter the date you believe the baby to have been conceived:
<input type="text" name="conceptionDate" id="conceptionDate"
value="6/10/99" />
<input type="button" name="calcDates" id="calcDates" value="Get
Dates" onclick="calcDates()" /><br />
<div id="results" />
JUMPING WITH ELEMENT IDS
Level: Intermediate
Category: DHTML
*Category: Scripting
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
Anchored name tags, though a staple of earlier HTML, have largely
become obsolete as the power of the HTML DOM has increased. Before you
start adding anchors for links to jump to, you may want to consider
instead the use of the method scrollIntoView(), if you are working
strictly with an Internet Explorer browser. This method, when applied
to an object, will scroll the page until that element is visible. If
you know the id of the item to move to, you can write a simple
JavaScript method jumpTo that will let you jump to that item:
Click on the button to jump
to the new text.
This will be the text that the image "link" jumps
to.
KERNING YOUR TEXT
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
You can do a limited amount of text kerning with the letter-spacing
CSS attribute. This determines the amount of space between letters and
can be expressed in any system units. For example, you might want to
make the letters A, V, and A overlap slightly in a logo word, AVAnte.
You can use letter spacing to reduce the space between them:
AVAnte
MAKE YOUR HTML XML COMPLIANT
Level: Beginner
Category: Design
Browsers Targeted: All
When designing HTML code, get into the habit of making your code XML
compliant. There are advantages to this compliance: As XML becomes
more prevalent as a way of generating Web pages, XML-compliant code
can be more readily searched, requires far less handling, and can be
kept internally in a database, making for easier maintainability.
Fortunately, HTML code is pretty close to being XML, so the changes
that you need to make are fairly minor:
* Make sure that any open tag has a corresponding closing tag. For
example, a number of HTML processors use the
mark erroneously as a
paragraph marker, rather than as the start of a paragraph container.
By making sure each
tag has a corresponding
, you move back
into the container/contained relationship that defines XML.
* Some tags in HTML have no corresponding close tag (such as the
or tags). In this case, you can still add a closing tag in most
circumstances and the browser won't complain, even though by the
browser's DTD, the syntax is incorrect.
* Attributes should always be quoted, although whether you use a
single quote or a double quote is a personal decision. Unfortunately,
many HTML editors follow the peculiar convention of quoting an
attribute only if the unquoted attribute would cause a
misinterpretation of the attribute (for example, if the attribute
value had a space in it). These are legitimate (though bad form) HTML
syntaxes but aren't valid XML.
* Some attributes don't have any attribute value associated with them,
such as the SELECTED attribute in an OPTION tag. Again, this is valid
HTML but not valid XML. However, with almost all values, if you set
the attribute value to the name of the attribute, the browser won't
complain, and you'll make your code XML compliant. For example, the
following code shows HTML that is both XML compliant and HTML
parseable:
* Some blocks of information require whitespace support (such as a
script block) or contain HTML code shown as samples. You can use the
XML tags tags to tell the parser to not attempt to
interpret the text contained within as XML expressions. For example,
the following script block makes use of exactly such a convention:
That's pretty much all you need to do. The encoding is a little more
hassle when dealing with a WYSIWYG environment, but by keeping your
code compliant you dramatically increase what can be done with it and
make it easier to retrieve, and you can cut down on the maintenance of
static files as a result.
PRINTING FROM IE5
Level: Intermediate
Category: JavaScript
Category: Printing
Category: Events
Browsers Targeted:
* Internet Explorer 5
One of the more welcome developments of the IE5 browser is the
capability to print from code. This particular feature performs
exactly the same action as choosing Print from the menu--the command
window.print causes the Print dialog box to pop up, letting users
specify print information. Once the user clicks OK, the browser fires
the onbeforeprint event on the window, prints the document, then fires
the onafterprint event. The reason for the two events is to let you as
an application developer change the state of the displayed page to
reflect what you want to have printed, then restore it to its original
state once the page has been spooled to the printer.
SETTING BORDERS
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
Borders can be used to provide useful special effects, if used
properly. If you're working with borders in Internet Explorer, you can
call on several useful CSS properties. Each border supports three
distinct properties: style, width, and color. Style lets you change
the visual appearance of the border, with possible values including:
* solid (a single solid line)
* double (two concentric lines of at least three pixels width)
* inset (a border where the upper and left-hand sides are darker than
the bottom and right-hand sides)
* outset (the inverse of inset)
* groove (a border that appears incised around the container)
* ridge (a border that's excised around the container)
* dotted (a border consisting of alternating dots and spaces)
* dashed (a border consisting of alternating dashes and spaces)
* none (turns bordering off)
Note that Internet Explorer treats dotted and dashed lines as solid
lines under Windows and UNIX but recognizes those styles on the
Macintosh. Certain styles, such as double, grooved, and ridged,
require that the width of the border be set to at least 3.
You can apply these attributes one at a time through the CSS border
property, using the border-style, border-color, and border-width
properties, respectively, or you can apply them as a single triplet
attribute, in the order border:style width color;. For example, to set
the border to be a red-tinted, three-pixel inset rectangle, you'd set
the container's style property in one of two possible ways:
This is
a three pixel wide inset red rectangle.
or
This is also a three pixel wide
inset red rectangle.
You can also effectively apply a border to each side individually,
through the border-left, border-top, border-right, and border-bottom
characteristics separately, or through combinations of side and
property (such as border-bottom-style). Thus, you could create
something like an annotation style, with the left-hand border colored
green to indicate that the text block is an annotation:
This is an annotated comment, noted by the green
line to the left.
This is part of the main text
TRACKING MOUSE COORDINATES
Level: Intermediate
* Category: CSS
* Category: JavaScript
* Category: Events
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
You can use the onmouseover event to locate the position of the mouse
relative to a container. This event method, applied to a given object,
can read the window.event object to return the current location of the
mouse relative to any number of coordinate systems--relative to the
current element (x,y), relative to the client window
(clientX,clientY), relative to the screen (screenX,screenY), and
relative to the offset of the element from the client window
(offsetX,offsetY).
<script>
function showMousePosition(){
mouseX=window.event.x;
mouseY=window.event.y;
window.status="Mouse Coordinate is ("+mouseX+","+mouseY+")";
buf="x="+mouseX+",y="+mouseY+"\n";
buf+="clientX="+window.event.clientX+",
clientY="+window.event.clientY+"\n";
buf+="screenX="+window.event.screenX+",
screenY="+window.event.screenY+"\n";
buf+="offsetX="+window.event.offsetX+",
offsetY="+window.event.offsetX; coords.innerText=buf;
}
</script>
<div style="width:400px;height:200px;border:outset 2px
red;background-color:red;" onmousemove="showMousePosition()"
onmouseout="window.status='';">Roll the mouse over this rectangle to
see <b>onmousemove</b> at work.<br />
<div id="coords" />
</div>
WEB BUILDING WITH CLASS
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 3
* Internet Explorer 4
* Internet Explorer 5
* NS4
One of the difficulties in implementing cascading style sheets
effectively across platforms comes from the fact that Internet
Explorer 5.0 supports a tag attribute called style that can be used to
implement specific CSS attributes on a given HTML element but Netscape
Navigator does not.
Before abandoning the use of CSS for Netscape, however, check out the
class attribute. With class, you can create a style sheet (either
locally or externally) that defines specific styles for the elements
that use the class, and the styles will hold across platforms. Here's
an example:
This is a test of the redline style.
Here is an example of the blue-boxstyle, showing
how you can create a standard box of text in either Netscape or
Internet Explorer.
WORKING WITH THE CLIPBOARD IN IE5
Level: Advanced
Category: Scripting
Browser Targeted:
* Internet Explorer 5
The Internet Explorer 5 browser supports several standard Windows
features at a much higher level than its predecessors. One of the more
useful of these features is the ability to save and retrieve
information from the Clipboard programmatically. The clipboardData
object provides a pointer to the Clipboard interface and exposes three
methods:
* setData(dataFormat,helperData): This method is used to copy
information to the Clipboard. If the first argument is the string
"Text", then helperData can be any string expression. On the other
hand, if the argument is "URL", then the argument passed in helperData
must be a URL.
* getData(dataFormat): This method returns what was placed on the
Clipboard in the given format. If the first argument is the string
"Text", then the result is itself a string. On the other hand, if the
argument is "URL", then the return value is specifically formatted as
a URL.
* clear([dataFormat]): This method removes any item with the format
specified (of type "Text", "URL", "File", "HTML", or "Image"
respectively) or removes all items on the Clipboard if no argument is
provided.
The following example illustrates how copy and paste works:
ADDING FAVORITES IN INTERNET EXPLORER
Level: Intermediate
Category: Scripting
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
>From Internet Explorer 4.0 and above, you can invoke the
addFavorites() method on the windows.external object to add a
particular entry in the Favorites list by passing the URL of the
favorite you wish to add as well as a title to describe the favorite.
Note that this passes these values to the addFavorite dialog box
instead of adding the favorites invisibly--an obvious security
feature.
For example, to add a reference to the VB-XML site, you'd simply
invoke the code as follows:
<script language="JavaScript">
function addFav(url,title){
window.external.addFavorite(url,title)
}
</script>
<input type="button" onclick="addFav
('http://www.vbxml.com','VB-XML')"
value="Click Here to add the VB-XML site
to your Favorites" />
CHANGING LIST ICONS
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 3
* Internet Explorer 4
* Internet Explorer 5
If you want to jazz up your bulleted lists, you may want to think
about using list style images, which is a URL to a graphic that is
used in place of the standard HTML bullets. These are set in CSS
through the list-style-image property, and they can also be set
programmatically through the style.listStyleImage property, as
follows:
This is a blue bulleted point
This is a green bulleted point
This is a red bulleted point
This bullet has no attached image.
This blue
point is generated from a
style.
Click on
the
bullet at left to change its color
ENHANCING TOOLBAR BUTTONS
Level: Advanced
Category: Browser
Category: Scripting
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
Dragging buttons to the toolbar is a powerful feature of the IE4 and
IE5 browsers. However, you can expand this functionality significantly
by setting the links themselves to JavaScript functions, executables,
or both. For example, one frequently encountered problem is when you
are in a framed window and you jump to a new page that doesn't release
you from the old frameset. You can create an Unframe button on your
toolbar that uses a simple JavaScript function, as follows:
Unframe
Drag this link to your toolbar to create an UnFrame button. Once the
button is set up, click on the frame you want to expand, then click
the button.
UnFrame
One disadvantage to this approach, as you may have already discovered,
is that if you have your security setting high enough, the button will
raise a security warning in some of the newer browser implementations.
This functionality is also available through the context menu as an
add-in from Microsoft. For more information, check out
http://www.microsoft.com/ie
SELECTIONS AND TEXT RANGES
Level: Intermediate
Category: TextManipulation
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
"Dynamic HTML" is a handy label to describe several technologies, but
at its core, DHTML consists of CSS, a few specialized tags, and the
ability to replace text within documents. The Internet Explorer
browser has always had fairly robust text-handling capabilities, and
with IE4 and above you can do many things with these features that are
comparable to the features of many word processing programs.
The basis of most text manipulation in the IE browser comes from the
.textRange object. A text range can be thought of as the internal
representation of text from one point in the document to another. A
text range differs from a selection, though, in that a text range
simply points to the locations of the start and end of a block of
text, while a selection consists of a text range that is considered
"active"--in other words, a selection is the current text range in
what may be any number of such ranges defined in the document.
You can retrieve (or set) the active text range from the current
selection, since the selection has a createRange method that creates a
localized text range based on the selection. For example, the
following code will report the text of what you just selected, and is
invoked on a mouseup event whenever you release the mouse within the
specified
tag:
Select a portion of
this text to display the selected range.
One thing to note about the text range function here is that it
doesn't contain the text itself--it contains only pointers into the
document's character structures. Thus, you can retrieve the literal
text of a selection by using the .text property, as well as retrieve
the HTML (with closing--or opening--tags added if the selection
crosses container boundaries) with the .htmlText property.
The property .htmlText is read-only, although .text is not--you can
replace text through it. However, if you wanted to replace selected
text, you could use the .pasteHTML method to accomplish this. For
example, the following code will highlight selected blocks in a
different color, along the lines of a magic marker, by placing
tags around the selection that set the color of the text to green.
Note that this may act strangely when interacting with the code
samples.
CREATING COLLAPSIBLE TREES
Level: Advanced
Category: CSS
Category: Scripting
Browsers Targeted:
* Internet Explorer 4
* Internet Explorer 5
Collapsible trees have become a staple in the DHTML world.
Fortunately, they are not terribly difficult to implement, if you use
a little bit of class. The principle trick is to understand that most
tree lists are created by embedding list containers (either
or
tags), within list elements (for example,
elements). By
hiding or showing the embedded container tags with the display CSS
attribute, you can cause the contents of those tags to contract or
expand as need be.
Of course, the difficulty here is that to expand or contract the
contained subtags, you have to send a message to that element to hide
or show it. Obviously, you don't want to have each node within the
tree contain script if you can help it--in addition to being
complicated to write, such an arrangement could be hard to maintain.
One way around this is to place an event tag on the outermost
container (the
or element that holds the top level nodes),
then use a little bit of the HTML DOM to determine what specific
element was touched.
NOTE: The activeListElement is essentially the last
tag that was
clicked on. Similarly, oldListElement is the element previously
selected; it is maintained principally to handle enabling or disabling
text selections.
While the example doesn't show it, you can assign id's to the
respective list elements, then use activeListElement.id to retrieve
the most recent item picked (activeListElement is initially set to
nothing). Similarly, you can retrieve the first child of any list
element (which should be a span) to get the actual text. If you just
attempt to read the text from the list element directly, you will
receive the text of the element plus all its children, not the text of
the tree node itself. The itemText shown in the onTreeItemSelected
method displays how you can retrieve the text of the node.
TreeView Node: Click on each solid disk to
close the node (if it has children) or the
open disk to open the node.
* A
* 1
* 2
* 3
* B
* 1
* a
* b
* c
* 2
* 3
* C
* 1
* 2
* 3
This fairly powerful capability would probably do better encapsulated
in a behavior, or at the very least turned into a self-contained
class. I leave that as an exercise to the reader.
FLASHING BORDERS
Level: Intermediate
Category: CSS, Scripting
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
Okay, sometimes it's fun to just play with CSS and make tags that are
as
gratuitous and empty as the old
MAILING YOUR FORMS
Level: Intermediate
Category: Forms
Browsers Targeted
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 4
* Netscape Navigator 3
The rise of server-side languages like ASP and JSP have made it much
easier
to process forms, but in certain situations it may prove handy to send
information as e-mail messages. Doing so is surprisingly simple,
especially
as most contemporary browsers support the necessary protocols: in the
action
attribute of your forms, specify a mailto: protocol rather than an
HTTP one.
When you send the information, the contents of the form will be output
as an
HTML-encoded string.
With many browsers, you can also pass information into the e-mail form
itself. You can set up input fields with the names associated with
each of
the respective fields of an e-mail address (to, cc, bcc, subject, and
body).
Typically, the to address will provide additional addresses along with
the
ones supplied by the mailto: protocol.
The behavior of the e-mail differs depending on whether you select a
method
of GET or POST. When you use action="GET" in your form, your browser
will
launch your e-mail program (if it's been configured to do so) and
populate
the respective fields. Then it is up to the user to send or not send
the
letter as appropriate. If you send the information as a POST, however,
your
user will receive a notice that information is being sent directly to
the
server, with the option to cancel the transmission if desired. When
sent in
this manner, the entire form is sent as an HTTP-encoded string rather
than
populating individual fields, and the result gets sent to the
recipient as
an attachment to an e-mail.
The following demonstrates how you could use this information to send
structured e-mail messages:
SETTING HOME PAGES IN IE5
Level: Intermediate
Category: Behaviors
Category: Scripting
Browser Targeted:
* Internet Explorer 5
Microsoft's Internet Explorer 5.0 ships with built-in behaviors that
you can use to better control the browser. Among them is the homePage
behavior, which can help you both determine whether a given page is
the user's home page and set the browser's home page to the current
page.
Because this component is a behavior, it is available only once the
window has fully loaded (i.e., the window.onload event fires). Once
this happens, the behavior exposes three methods:
* isHomePage(url) returns true if the current page is the page
specified by the URL.
* navigateHomePage() automatically jumps to the current home page.
* setHomePage(url) lets you set the home page to a given URL or file
path.
This code illustrates a very simple application that will let you set,
test, and navigate to your home page from code:
THE FUNCTION() FUNCTION
Level: Intermediate
Category: JavaScript
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 4
* Netscape Navigator 3
No, the title is not a misprint.
JavaScript is a remarkable little language, taking some of the
advantages of
its parent, Java, but also using its interpreted nature to good
effect. One
of the more useful techniques, albeit one that is not often used, is
the
ability to create functions dynamically, using the Function()
function. This
particular function lets you define a function dynamically at runtime,
making it especially useful for creating complex expressions and
retaining
them as distinct entities.
For example, suppose you wanted to build a table dynamically that
could
output values based on an arbitrary function. The function can be
modified
by the user, which is where things get sticky from the standpoint of
many
programming languages--there's a clear divide between the user world
and the
program space . . . until the user wants to have access to that space.
Fortunately, while interpreted languages have a few drawbacks
(primarily
having to do with efficiency), they are marvelously adept at handling
the
bridge between the user space and the program space. Indeed, for
JavaScript
objects, the distinctions get very fuzzy indeed. Anyway, back to the
Function() function: You can create a new function by passing the name
of
each parameter that you want to include, followed by the expression
body, to
the Function() function, then passing this to a variable: fn=new
Function(param1,param2,fnBody).
For example, you could create a simple expression that would return
the
distance between two points:
Going back to the example described earlier, the code below
illustrates one
approach that you could take. Note that you have to include a full
JavaScript body with the appropriate return statement preceding the
expression that you want to evaluate. One danger to this approach is
that
the expression being passed could also be used to perform side effects
on
the page itself. For example, try passing the expression
document.body.style.color="white";
document.body.style.backgroundColor="blue";
return x*x;
into the function definition area and see what happens.
Note: While the Function() function is part of JavaScript, the sample
code
below will only work with Internet Explorer.
USE XMP TO SHOW SOURCE CODE
Level: Beginner
Category: DHTML
Browsers Targeted:
Internet Explorer 3
Internet Explorer 4
Internet Explorer 5
Netscape Navigator 4
One of the lesser known, but more powerful HTML tags, is the
, or
eXaMPle, tag. This particular tag works much as the
PREserve
tag, retaining spaces, tabs, carriage returns, and other white space
characters in the final output. Additionally, it displays the text
using a mono-proportioned font (typically Courier). However, it does
one thing that
does not--it also keeps HTML tags in their
original form, whereas PRE converts them into tags. In this sense,
works much like XML's CDATA type, keeping its contents in their
original form.
Note that because does make the output appear exactly as the
source, you can't explicitly format anything within an XMP block.
However, you can apply a style or class attribute to the XMP tag
itself, which will in turn change the format of the internal text. For
example, if you wanted to make the example codes use an 8-point blue
sans-serif font instead of the default black Courier, you could set up
the style as follows:
Sample
This is a test.
FILE SYSTEM OBJECT
Level: Intermediate
Category: Scripting, ASP
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
If you are using the Internet Explorer browser in a local context (for
example, viewing pages that are on a local network server or your own
machine, or as part of an application), you can take advantage of the
File
System Object to load text files into your page (or update text
files). The
File System Object (or FSO) can give you access to any number of
file-related features, including generating directories, checking to
see
whether a file exists, retrieving file paths, and writing files to the
system.
You can also use the FSO on the server, where it has greater benefit.
For
example, the following ASP code will load in a text file and output
all
lines of text (numbered by position in the file) that include the
search
term:
<%
function getLines(filename,expr)
dim fs ' File System Object
dim ts ' Text Stream Object
dim ct
' Create the File System Object
set fs=CreateObject("Scripting.FileSystemObject")
' Create a text stream object from the fso
set ts=fs.openTextFile(server.mapPath(filename),1)
' Initialize the counter
ct=0
'While there are still lines
while not (ts.eof)
' read the line
line=ts.ReadLine
' see if it has the expression
if instr(line,expr)>0 then
'output it to the browser if it does
response.write cstr(ct)+":"+line
end if
' increment the counter
ct=ct+1
wend
ts.close
end function
getLines "myFile.txt","accounting"
%>
USE @IMPORT TO LOAD STYLESHEETS
Level: Intermediate
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Netscape 4.5+
While you can use LINK to load in stylesheets, the CSS @import
property can
also be used to import stylesheets, as follows:
In addition to being more conformant with the W3C CSS standards,
@import
provides some added benefits--by placing an @import style within an
external
stylesheet, you can create a limited inheritance--the browser loads
the
first stylesheet, discovers upon parsing that the first stylesheet
references a second, then parses the second. In this way, you can
define a
generalized stylesheet (the second sheet referred to here), then
define
local or page variations (the first sheet), and finally include
immediate
style rules in the current document.
DHTML COLLAPSING TREEVIEW
Here's something that the Visual Basic coders among you might find
interesting if you have some Web development experience, either with
VB
DHTML applications, or HTML pages using VBScript. If you don't have
such
experience, you will soon! Find out how to build a collapsible
treeview
using DHTML. Along with gaining an understanding of a useful
technique, you
will be learning some neat features of DHTML, such as event bubbling
and
working the DHTML hierarchy. Find out more from the VB Pro at
http://www.inquiry.com/techtips/thevbpro/10_minute_solutions/10min0999.asp
DHTML-PLAYTIME IS OVER
Here's an article for those who may be new to DHTML or who think that
all
you can get from it is a nifty mouse rollover effect. Find out why
Dynamic
HTML lets you build much friendlier user interfaces, but you'll have
to
standardize on one brand of browser for any nontrivial functionality.
Go to
http://www.dhtml-zone.com/articles/md20998/md20998.asp
DYNAMICALLY CHANGE THE COLOR OF AN IMAGE
Let's say that you've got an online store that sells T-shirts of
different
colors. Being able to change dynamically the color of a T-shirt based
on a
user's selection would be handy in displaying your collection of
available
T-shirts. Want to know how to do it? This is another one of many
articles
posted on inquiry.com. Go to
http://www.inquiry.com/techtips/dhtml_pro/10min/10min0299/10min0299.asp
GET READY FOR NAVIGATOR 5.0 DHTML
If you're a Netscape Navigator user, you might want to know what
version 5.0
has for you. Check out some of its features--including the ability to
work
with cross-browser and cross-version DHTML scripting objects. And,
since
nothing in life is perfect, you might find out a few of its
disadvantages,
too. Go to DevX.com's site to learn about this and a raft of other
DHTML-related stuff:
http://www.inquiry.com/techtips/js_pro/10min/10min0200/10min0200.asp
Y3K
Level: Intermediate
Category: JavaScript
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape 4
* Netscape 3
The world survived the Y2K bug pretty much intact, but you may have
noticed
on some systems on the Web that the time did read either 100 AD or
2100 AD.
This is an example of the dangers of not agreeing to standards. The
Microsoft parser implements the JavaScript Date object's getYear
function as
a four-character string: Jan 1, 2000, has a getYear() value of "2000".
Netscape's JavaScript implementation, on the other hand, has a
getYear()
value of "100". A simple script can guarantee that you'll always get
the
right year:
The prototype method is another seldom-used but extremely powerful
JavaScript function. You can add subclass methods with prototype by
defining
the basic function, then attaching it as a prototype to either a
built-in or
created class. This is a way to extend the functionality of such
objects as
the Date(), String(), Image(), and other objects. Once you add the
prototype, all new objects of that type will support the prototyped
function.
Note: If you're writing a project that covers times during the Middle
Ages,
then you may want to bump the test condition from 1000 to 1600 or so.
AURAL CSS2
Level: Intermediate
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 3
* Netscape Navigator 4
The Cascading Style Sheets 2 specification was basically built around
the integration of media into the Web browser. Among these was the use
of sound, which up until now has been typically limited to bad MIDI
soundtracks and the occasional button special effect. However, the
ability to have your Web page read aurally can prove useful, from
automobile and cell-phone access to your Web sites, to sites that work
with the sight-impaired, to kiosks that use a Web page base and
listening to one site in the background while viewing another in the
foreground.
All the basic CSS2 properties that deal with sound require some form
of add-on to existing browsers to actually read the text. Most of
these properties should be placed after the visual CSS properties in
style rules, since older Netscape browsers will typically ignore
properties after ones that it can't decipher. These are the
properties:
* volume--Has possible values of {number}, {percentage}, silent,
x-soft, soft, medium, loud, and x-loud. This gives the average volume
of the aural presentation and can range between 0 and 100 (or 0% and
100%) of the possible aural comfort levels.
* speech-rate--Has possible values of {number}, x-slow, slow, medium,
fast, x-fast, faster, and slower. This provides the speed at which
text is read, from x-slow (80 words per minute) to x-fast (500 words
per minute).
* voice-family-- Has possible values of male, female, child, and
{custom}.
Roughly analogous to font-family, these provide specifications to
describe the voices used. A custom voice-family could conceivably be
an agent with a distinct voice signature--for example a "Spock" voice
or "Jean Luc Picard" (not that either one of these exists, but you get
the idea).
* pitch--Has possible values of {number}[Hz|kHz]. The pitch provides
the tone of the character speaking in his or her average vocal range.
A typical male voice has a pitch of about 120 Hz, while a female voice
is closer to 200 Hz.
* pitch-range--Has possible values of 0-100. The range of the voice:
from 0, for a flat "robotic" voice, to 100, for an extremely inflected
voice.
* azimuth--Has possible values of {angle}, left-side, far-left, left,
center-left, center, right, far-right, right-side, behind, leftwards,
and rightwards. The direction that the voice is projected from. Note
that you can specify multiple azimuth elements in the same line:
azimuth:left-side behind will make the sound appear as if it comes
both from your left and from behind you.
* pause--Has possible values of {time},{percentage}. This indicates
that a pause should exist before or after (or both) a given selection.
For example,
will pause before the
selection begins for one second, and afterwards, for half a second.
This is the aural equivalent of a margin.
* cue-before, cue-after, cue--Has a possible value of {url}. This
provides an aural icon before or after a selection begins, roughly the
equivalent of a bullet in a bullet point. The cue property can take a
URL both before and after a selection. For example,
An important point
will cause a
"bink" sound to play before the reader says "An important point."
* play-during--Has possible values of {url} mix, repeat, auto, none,
and inherit. Plays the selection indicated in the url() in the
background as the text contained in the corresponding selection is
read.
* speak--Has possible values of normal, none, and spell-out. This
global property determines whether speech is enabled (normal) or
disabled (none) or the contents are spelled out.
BEHAVIOR CODE
Here's another article for the Visual Basic crowd. By now probably
many VB
developers are leveraging their skills to do Web development. DHTML
Behaviors is a new feature of Internet Explorer 5 that can be used in
a
Visual Basic DHTML application, browser control, or HTML pages. (Just
remember that it's IE5-specific.) Find out what this is and how to use
it at
http://www.inquiry.com/techtips/thevbpro/10_minute_solutions/10min1199.asp
INFO FOR THE TRULY NEEDY
Everybody needs help sometimes, and here's a site that offers
tutorials, a FAQ, labs, and links to solve many problems. Related
links will shoot you over to links for HTML, JavaScript, ASP, and
Java. The articles are a roundup from various sites, so the
possibilities are endless. Go to
http://www.katungroup.com/dhtml.htm
NEED A REFERENCE--CHECK OUT THIS ONE
Danny Goodman wrote "Dynamic HTML: The Definitive Reference" because
he thought the documentation on DHTML had too many contradictions. His
practical guidance--tested on multiple versions of Netscape and
Internet Explorer--offers a solid foundation for those who have some
experience in HTML. This book continues to be a best seller, although
it was published more than a year ago. Check it out at
http://www.amazon.com/exec/obidos/ASIN/1565924940/tipworld
RETRIEVING RESPONSES AS XML
Level: Advanced
Categories:
* VBScript
* ASP
* XML
Browsers targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 3
* Netscape Navigator 4
The ASP Request object can be confusing to beginning Web programmers.
One common problem is to get all of the terms sent up in a form or
query string without knowing precisely what to expect. The problem is
that the Request object appears to be a collection of name/value
pairs, but in fact it's much more complex. It's actually an interface
that exposes four distinct subcollections:
* QueryString--This retrieves all of the name/value pairs that were
sent on the command string or were sent as part of a form with its
method sent to GET.
* Form--This retrieves all of the name/value pairs that were sent
through a form via a POST method.
* Cookies--This retrieves all of the cookies that have been defined
for this page.
* ServerVariables--This retrieves the server variables that were sent
as part of the HTTP header or are maintained by the server.
One problem that I frequently encounter is a need to load a Response
object into an XML file that I can then pass into an XSL filter.
Knowing that the Response object supports all four collections, I
wrote a small routine that queries each collection in turn and turns
the resulting query into an XML document:
<%@LANGUAGE="VBScript"%>
<%
'GetRequestKeys.asp
function getRequestXML()
dim xmlDoc
set xmlDoc=server.createObject("Microsoft.XMLDOM")
xmlDoc.loadXML ""
setKeysCollection xmlDoc,"querystring"
setKeysCollection xmlDoc,"form"
setKeysCollection xmlDoc,"cookies"
setKeysCollection xmlDoc,"servervariables"
set getRequestXML=xmlDoc
end function
function setKeysCollection(xmlDoc,collectionName)
set collectionNode=xmlDoc.createElement("collection")
collectionNode.setAttribute "id",collectionName
for each key in eval("request."+collectionName)
set keyNode=xmlDoc.createElement("key")
keyNode.setAttribute "id",key
keyNode.setAttribute "value",request(key)
collectionNode.appendChild keyNode
next
xmlDoc.documentElement.appendChild collectionNode
set setKeysCollection=collectionNode
end function
function main()
set requestDoc=getRequestXML
response.ContentType="text/xml"
response.write requestDoc.xml
end function
main
%>
SIMPLIFY XML WITH VBSCRIPT CLASS
Level: Advanced
Categories:
* VBScript
* XML
* ASP
Browsers targeted:
* Internet Explorer 5
* Internet Explorer 4
VBScript has long been considered a fairly rudimentary language,
lacking the robustness that the full-featured Visual Basic product
demonstrates and lacking any real tools for handling even basic
object-oriented capabilities (something that JavaScript does handle).
However, with the release of VBScript 5.0 (part of the general
Internet Explorer 5 upgrade, although the scripting engine can be
loaded separately for IE4), at least some of these basic objections
are being answered.
One of the most common problems with ASP scripts (which is where most
VBScript code is written) is that the combination ASP and HTML tends
to make for difficult-to-manage, highly coupled code. Changing such
code is difficult, which is why ASP files tend to be fairly difficult
to write and manage. Yet, VBScript 5.0 released the ability to build
classes. Specifically, the Class and End Class keywords let you define
encapsulated entities that can expose properties and methods (and
events in a limited fashion). You can use such classes to simplify
your Web page generation radically.
For example, the following VBScript class CWebPage exposes two
methods: GetPageData, which retrieves the name of an XML file, an XSL
transform file, and a mime type (all optional); and ShowOutput, which
performs the XML transform and outputs it to response stream.
<%@LANGUAGE="VBScript" %>
<%
Class CwebPage
Dim xmlSource
Dim xslTransform
Dim mimeType
Dim resultText
Public Sub GetPageData()
dim sourceFileName
dim transformFileName
sourceFileName=request("source")
transformFileName=request("transform")
mimeType=request("mimetype")
if mimeType="" then
mimeType="text/html"
end if
if sourceFileName<>"" then
set xmlSource=createObject("Microsoft.XMLDOM")
xmlSource.load server.mapPath(sourceFileName+".xml")
end if
if transformFileName<>"" then
set xslTransform=createObject("Microsoft.XMLDOM")
xslTransform.load server.mapPath(transformFileName+".xsl")
resultText=xmlSource.transformNode(xslTransform)
else
resultText=xmlSource.xml
mimeType="text/xml"
end if
response.ContentType=mimeType
End Sub
Public Sub ShowOutput()
response.write resultText
End Sub
End Class
%>
<%
Function Main()
set WebPage=new CWebPage
WebPage.GetPageData
WebPage.ShowOutput
End Function
Main
%>
The advantage to using classes in this page can be seen in the Main()
function. Classes can be loaded in through the use of directives so
that the entire body of the code consists of the includes and the Main
function call (which should be in the calling page simply for testing
purposes).
You can then make calls to your server to download XML formatted with
the given XSL stylesheet, and the output is sent to your browser as
formatted HTML. This makes it ideal for using with browsers that don't
support XML natively (everything but IE5) or those that support it but
can't handle printing XML documents properly (IE5).
THE DHTML PIT STOP
PageResource.com has articles on Cascading Style Sheets, JavaScripts,
Netscape layers, graphics, and more, with related links to ASP,
cgi/Perl, HTML, Java, and JavaScript. To put a little pep in your
pages, go to
http://www.pageresource.com/dhtml/index.html
UPLOADING FILES
Level: Intermediate
Category: File Transfers
Browsers targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 3
* Netscape Navigator 4
While you can upload a file to your server with the element (make sure your form's enctype attribute is set
to "multipart/form-data" and the method is set to POST), IIS doesn't
provide any direct means of working with the data beyond BinaryRead().
Microsoft does provide an ISAPI filter to handle uploads, but it is
primitive (about four years old) and awkward to use in ASP. Check out
SA-Fileup, which provides a cleaner interface for transforming the
resulting data. It is a commercial product, but generally worth the
expense. Go to
http://www.softartisans.com
USING HIDDEN FIELDS
Level: Intermediate
Category: Forms
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 4
* Netscape Navigator 3
When you work with forms, you may occasionally need to pass
information up to the server that you don't necessarily want to
display as part of the visible Web page. This is the kind of situation
that the hidden element was designed for. The syntax is simple:
The advantage to using hidden attributes is that it lets you create
name/value pairs that you can extract from the server without having
to notify the user about this information. This also makes them ideal
as persistent text-based variables; indeed, you can use hidden
variables to hold XML structures created on the client for those
browsers that don't support XML parsers:
XML Creator
In this case, the hidden field would end up holding the XML structure
built up from the visible fields. Note that using this approach, you
can still retrieve the items individually on the server <%
address=request.form("address") %>, but you can also retrieve the XML
object as a separate entity and pass it into XML processing code:
<%
set addressDoc=createObject("Microsoft.XMLDOM")
if isObject(request("addressXML")) then
addressDoc.load request("addressXML")
else
addressDoc.loadxml request("addressXML")
end if
%>
The ASP code block can thus accept input from both a Netscape page
holding an XML block as text and a Microsoft page sending XML through
HTTP.
VOICE-SENSITIVE HTML
Level: Beginner
Category: Design
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 3
* Netscape Navigator 4
Vox readers--devices that translate written text into vocal
representations--are becoming common, especially with the rise in
phone systems that connect to the Internet, automobile Internet
browsers, and similar systems, as well as systems that are targeted
toward blind users.
You can prepare your Web site for use by such browsers in several
ways. Perhaps the simplest way is to turn off your image and
multimedia views in your browser. In Internet Explorer you can do this
by choosing the Advanced tab in the Tools, Internet Options dialog box
and deselecting options such as Show Pictures. In Netscape Navigator,
open up the View menu, and if the option Show Images is checked,
uncheck it.
Now, take a look at your Web pages. This is what the view looks like
to audio-only readers, and if it's unintelligible to you, it will be
unintelligible to them too. Remember that most such readers work based
on the source HTML document, not the visual appearance on the page.
Make sure that the flow that you use reflects this--design critical
information such as document summaries so that they appear early, and
keep your interface items either on the top or left-hand side of the
screen, contained within their own DIV elements or LAYER elements.
Similarly, if you make extensive use of external components such as
ActiveX controls or Java applets, be sure that your site includes a
fall-through for such elements (by including the fall-through text
within the
CHANGE STYLES IN INTERNET EXPLORER
Using Internet Explorer, you can use JavaScript to change just about
any style property. What you need to know is the style property you
wish to change. For instance, if you wish to change the font-size
property in a DIV named "div1"...
document.all.div1.style.fontSize="20pt";
...look at how to access it. You will see that what we do is remove
the dash from the property name and capitalize the next letter. This
allows us to access that style property with Internet Explorer.
Here is an inline example--we'll change the border-color property:
Text
NO MARGIN FOR ERROR
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Netscape Navigator 4
You can use CSS to control the margins of your document. In DHTML, the
margin is the space between the bounding rectangle of the current
element (conceivably a body element) and the previous or container
element. For the element itself, the margin is the amount of
space between the corner of the browser display window and the
location where the Web page begins. You can set your documents to be
flush to the edges of the browser by setting the margin to 0px, as in
NUMBERING OUTLINES
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Netscape Navigator 4
Whenever you have hierarchical lists or outlines, you can use
list-style-type on the element used to contain each list. This
can give you the ability to designate different levels of a document
with different types of characters. For example:
Chapter 1
Section 1
Sub-section 1
Paragraph 1
Paragraph 2
Paragraph 3
Sub-section 2
Paragraph 1
Paragraph 2
Paragraph 3
Sub-section 3
Paragraph 1
Paragraph 2
Paragraph 3
Section 2
Sub-section 1
Paragraph 1
Paragraph 2
Paragraph 3
Sub-section 2
Paragraph 1
Paragraph 2
Paragraph 3
Sub-section 3
Paragraph 1
Paragraph 2
Paragraph 3
Chapter 2
Section 1
Sub-section 1
Paragraph 1
Paragraph 2
Paragraph 3
Sub-section 2
Paragraph 1
Paragraph 2
Paragraph 3
Sub-section 3
Paragraph 1
Paragraph 2
Paragraph 3
Section 2
Sub-section 1
Paragraph 1
Paragraph 2
Paragraph 3
Sub-section 2
Paragraph 1
Paragraph 2
Paragraph 3
Sub-section 3
Paragraph 1
Paragraph 2
Paragraph 3
Chapter 1
A. Section 1
i. Sub-section 1
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
ii. Sub-section 2
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
iii. Sub-section 3
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
B. Section 2
i. Sub-section 1
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
ii. Sub-section 2
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
iii. Sub-section 3
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
Chapter 2
C. Section 1
i. Sub-section 1
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
ii. Sub-section 2
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
iii. Sub-section 3
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
D. Section 2
i. Sub-section 1
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
ii. Sub-section 2
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
iii. Sub-section 3
a. Paragraph 1
b. Paragraph 2
c. Paragraph 3
OVERFLOWING YOUR BOUNDARIES
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
Normally, when you create a DIV element, that element will attempt to
display everything within it by expanding until it either reaches the
boundary of the browser or until it reaches the right or bottom edges
of any images it contains, whichever is larger. However, you can
modify this behavior so that the contents of the DIV element fit
within a specific boundary, with scroll bars appearing if the contents
are larger than the specified size. To control this, you can use the
CSS Overflow property:
Overflow can take a number of values, and the resulting action depends
on these values:
* visible--The full rendered contents will appear in the DIV element,
expanding the DIV out in the process. This is the default.
* scroll--Scroll bars are automatically placed around the DIV
regardless of whether the contents fit.
* hidden--The image is cropped to the specified size given by the
width and height CSS properties.
* auto--If the contents can fit within the DIV, scroll bars are
hidden; otherwise, they are displayed.
ROMAN NUMBER YOUR LISTS
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Netscape Navigator 4
Bullets form an integral part of most Web pages--although most Web
developers don't take advantage of the more advanced CSS features
available for modifying the way that both bulleting and numbering
takes place. The list-style CSS property determines characteristics of
bullets, although the supported functionality differs widely between
Netscape and Internet Explorer.
Consider the problem of numbering. Straight numeric bullets are easy
to achieve, but they are not terribly exciting. You can, however,
enhance them with the list-style-type subproperty, which handles the
specific form of the standard output from the list. For example, if
you wanted to list your bullets using Roman script, use a
list-style-type property value of either "upper-roman" or
"lower-roman":
This little piggy went to market,
This little piggy stayed home,
This little piggy had tofu (in deference to the vegetarians
out there),
This little piggy had none,
This little piggy went whee, whee, whee all the way
home.
I. This little piggy went to market,
II. This little piggy stayed home,
III. This little piggy had tofu (in deference to the vegetarians out
there),
IV. This little piggy had none,
V. This little piggy went whee, whee, whee all the way home.
while changing the attribute to "lower-roman results in":
i. This little piggy went to market,
ii. This little piggy stayed home,
iii. This little piggy had tofu
iv. This little piggy had none,
v. This little piggy went whee, whee, whee all the way home.
The values of "upper-alpha" and "lower-alpha" output the items
enumerated by letter:
A. This little piggy went to market,
B. This little piggy stayed home,
C. This little piggy had tofu
D. This little piggy had none,
E. This little piggy went whee, whee, whee all the way home.
a. This little piggy went to market,
b. This little piggy stayed home,
c. This little piggy had tofu
d. This little piggy had none,
e. This little piggy went whee, whee, whee all the way home.
Finally, "decimal" sets it to the default:
1. This little piggy went to market,
2. This little piggy stayed home,
3. This little piggy had tofu
4. This little piggy had none,
5. This little piggy went whee, whee, whee all the way home.
SIMPLE ROLLOVER BUTTONS
Level: Advanced
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 4
* Netscape Navigator 3
There are probably more scripts out there for rollover buttons in
JavaScript than there are buttons, but I wanted to bring up the point
to show how you can use JavaScript's object-like nature to simplify
the code. The onload event attached to the image objects creates a new
CButton object, into which the internal object reference is passed as
a parameter. As this loads, it extracts the base name of the image and
the image extension (.jpg, .gif, etc.--note that the routine looks for
the ending "." and uses that to determine the extension). The Hi and
Pressed strings indicate that the alternate buttons should have the
syntax buttonName_Hi.ext and buttonName_Pressed.ext respectively; you
can change it to reflect your own naming convention.
The heart of the routine is the Function() function. This entity
creates a function out of the strings, attaching them specifically to
the image object (which will be the object receiving the events in the
first place). This requires an ID to forward-reference the image, but
if one isn't explicitly provided, the routine creates one. Finally,
the image's onload event is set to null, which ensures that any new
images instantiated in the button (i.e., the other states) don't
inadvertently trip the onload event again.
<script language="Javascript">
function CButton(me){
this.image=me;
this.id=me.id;
if (this.id==null){
this.id=uniqueID;
}
pos=me.src.lastIndexOf(".")
this.imageExtension=me.src.substring
(pos,me.src.length);
this.imageName=me.src.substring(0,pos);
this.imageHiName="_Hi"
this.imagePressedName="_Pressed"
me.onmouseover=Function(this.id+".src='"+this.imageName+this.
imageHiName+this.imageExtension+"'")
me.onmouseout=Function(this.id+".src='"+this.imageName+this.
imageExtension+"'")
me.onmousedown=Function(this.id+".src='"+this.imageName+this.
imagePressedName+this.imageExtension+"'")
me.onmouseup=Function(this.id+".src='"+this.imageName+this.
imageHiName+this.imageExtension+"'");
me.onload=null;
}
</script>
STYLISH BODIES
Level: Intermediate
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
In Internet Explorer, you can set the document body style dynamically
by using the stylesheet object and rules. For every stylesheet that is
defined (there happen to be two in this document), there is an
associated stylesheet object kept internally. A given stylesheet is
made up of rules, one rule for each selector (such as BODY). Adding a
rule to a stylesheet will rewrite those properties that are different
between the old and the new rule (if one existed).
THE BROWSER WARS--PART 1 OF 3
While discussing DHTML, we want to take note of the differences
between the two major browsers. Here let's take a quick look at the
two document object models so that when we get to cross-browser coding
later, we'll know what we are up against.
In Microsoft Internet Explorer 4+, all (or close to all) the objects
on a page are accessible through the use of
document.all
After that, you insert the name of the object and then the property
you want to change. For instance:
document.all.object_name.style.left
This would access the left property of the object defined inline in a
style tag or through a style class. In the next tip, we'll look at how
to get to this same object and property in Netscape Navigator.
THE BROWSER WARS--PART 2 OF 3
In the previous tip, we showed you how to access an object and one of
its style properties in Internet Explorer. To get the left property,
we used:
document.all.object_name.style.left
In Netscape Navigator 4+, however, we have to go a different (though
shorter) route. The drawback is that not all objects are accessible in
Netscape as in Internet Explorer (I will be waiting to check version
5). In Netscape, the same property is accessed like this:
document.object_name.left
As you can see, you have to do a little extra coding to make certain
scripts work in both browsers.
THE BROWSER WARS--PART 3 OF 3
Another browser difference that can give us fits is the way each
browser supports layers. Both browsers support style sheet layers, but
Netscape doesn't support them as well as Internet Explorer yet. This
means that to do the same thing in Netscape, we often have to add some
extra code--or simply decide that the property isn't supported at all.
For instance, a
tag can take an onMouseover event in Internet
Explorer, but not in Netscape. In Netscape, The tag is the
closest tag for the same effect and will take the onMouseover command.
Since it is ignored by Internet Explorer, we can normally add the
tag with no side effects. The and tags will
be handy additions in some of our cross-browser scripts.
THE TEXT LINK HOVER--PART 1 OF 2
Here is something that is often thought to be a JavaScript or DHTML
trick but is done only with style sheets. The drawback: Netscape
doesn't seem to support it in any way (other than using images
instead), even through scripting. I could be wrong, though--send me a
note if you know the solution.
The text link hover is done easily if you want it to work for all the
links on the page. When the mouse moves over a link, the changes you
define will occur. Just add the code below between your
tags:
Of course, you can change other properties as well, such as the
text-decoration, by adding them in:
THE TEXT LINK HOVER--PART 2 OF 2
To perform the text link hover only on a certain set of links, we can
define a class:
Now, anything inside a set of tags with a class of "links1" will have
the change on a hover, but the rest of the links will be normal (or
you could define more classes).
Level: Beginner
Category: CSS
Browsers Targeted:
* Internet Explorer 5
* Internet Explorer 4
* Internet Explorer 3
* Netscape Navigator 4
* Netscape Navigator 3
A useful but frequently overlooked tag is , which lets you
specify the location that is used by any href or src tags contained in
the document. In essence, it specifies the default folder that other
resources use. If you break your resources into separate folders such
as IMAGES or CODE and your page makes references to that folder
compared to references in the current folder, you may want to think
about using BASE. Note that the BASE must be contained in the
element and must point to an absolute, rather than local, URL.
For example, the following gallery document is located in the root
folder but points to images on a different server (in this case, my
Sea Tails site):
Indirection
Indirection
LAYER BACKGROUND COLOR CHANGES
This one will work in the latest version of both major browsers, but
we have to use the and tags to make it work in
Netscape, while we use style sheets and the for Internet
Explorer.
The is used so that the will be inline rather than
needing absolute positioning. The tag inside lets us use the
onMouseover command in Netscape:
Text
TABLE BACKGROUND COLOR CHANGES
If you prefer to use tables over layers for layout, you can implement
the background color change in a table cell. Notice that in Internet
Explorer the <TD> tag can take the onMouseover command. We have to
use the <ILAYER> and <LAYER> tags to make it cross-browser:
<TABLE width="200" border="1" cellspacing="0"
cellpadding="0">
<TR>
<TD style="width:100%; background-color:lightblue"
onMouseover="this.style.backgroundColor='yellow';"
onMouseout="this.style.backgroundColor='lightblue';">
<ILAYER>
<LAYER ID="la2" bgColor="lightblue" width="100%"
onMouseover="this.bgColor='yellow';"
onMouseout="this.bgColor='lightblue';">
This is Text.
</LAYER>
</ILAYER>
</TD>
</TR>
</TABLE>
USING LAYER TAGS
One of the reasons for the layer tags is to make onMouseover commands
cross-browser, as we did in previous tips.
Another reason is for layout consistency. If you use a style sheet
layer and use a background color, the two browsers will display them
differently. Netscape tends to cut off the background color at the end
of the text by default, while Internet Explorer will allow it to span
the width of the page.
This can be controlled to some degree by adding the width property to
the style sheet, but the browsers still seem to disagree on how to
fill the background area.
The layer tag allows the color to span the entire width we desire, so
we place it inside a regular division tag and give it the same width:
<SPAN ID="sp1" style="width:80;
background-color:lightblue">
<ILAYER>
<LAYER ID="la1"
bgColor="lightblue" width="80">
Text
</LAYER>
</ILAYER>
</SPAN>
BACKGROUND IMAGE CHANGE
Now that we have done color changes, how about a background image
change? The good news is we can do it with Internet Explorer:
The downside is that it is not cross-browser yet, so you may want to
add a browser check to avoid an object properties error in Netscape.
LAYER BACKGROUND IMAGE CHANGE
You can change the background image of a table cell or layer in
Internet Explorer as we did with the background image of the body tag.
Here is one for an onMouseover command in a table cell:
<TABLE width="200" border="3"
cellspacing="0" cellpadding="0">
<TD ID="td1" style="background-
image:url(image1.jpg)"
onMouseover="this.style.
backgroundImage='url(image2.jpg)';"
onMouseout="this.style.
backgroundImage='url(image1.jpg)';">
Text
</TD>
</TABLE>
INTERNET EXPLORER: CHANGING BORDER COLOR
You can change the border color of a layer by accessing the style
property of border-color. To get to the border color in JavaScript,
you use
this.style.borderColor
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This has a border!
INTERNET EXPLORER: CHANGING BORDER PROPERTIES
You can change more than one border property at a time by adding an
extra command to change another property. The code below will change
the border color and the border width when the mouse moves over the
layer:
This has a border!
INTERNET EXPLORER: CHANGING BORDER STYLE
You can change the border style of a layer by accessing the style
property of border. To get to the border style in JavaScript, you use
this.style.border
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
<P>
<DIV style="border:solid; border-width:2;
border-color:black;
background-color:lightblue; width:200"
onMouseover="this.style.border='double';"
onMouseout="this.style.border='solid';
this.style.borderWidth=2;">
This has a border!
</DIV>
You'll notice we had to add a second JavaScript command to change the
border width back to 2. It seems that when the border is changed to
double and then back to solid, it keeps the width of the double border
unless you change it back.
INTERNET EXPLORER: CHANGING BORDER WIDTH
You can change the border width of a layer by accessing the style
property of border-width. To get to the border width in JavaScript,
you use
this.style.borderWidth
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This has a border!
INTERNET EXPLORER: CHANGING BORDER WIDTH, ONE SIDE ONLY
You can change the border width of the top part of the border in a
layer by accessing the style property of border-top and getting to the
width of it. To get to the border width of the top part in JavaScript,
you use
this.style.borderTopWidth
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This has a border!
You can do the same for the bottom, left, or right sides by using
borderBottomWidth
borderLeftWidth
borderRightWidth
INTERNET EXPLORER: CHANGING BORDERS COLOR, ONE SIDE ONLY
You can change the border color of the top part of the border in a
layer by accessing the style property of border-top and getting to the
color of it. To get to the color in JavaScript, you use
this.style.borderTopColor
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
<P>
<DIV style="border:solid;
border-width:2; border-color:black;
background-color:lightblue; width:200"
onMouseover="this.style.borderTopColor='red';"
onMouseout="this.style.borderTopColor='black';">
This has a border!
</DIV>
You can do the same for the bottom, left, or right sides by using
borderBottomColor
borderLeftColor
borderRightColor
INTERNET EXPLORER: CHANGING STYLES
An earlier tip mentioned how you can change all kinds of style
properties in Internet Explorer with JavaScript by removing the dash
and capitalizing the second word to access the property. We will use
this in the next several tips to change numerous styles in Internet
Explorer.
You get to the background color of a layer by taking the style
property
background-color
and then changing it with JavaScript:
this.style.backgroundColor="yellow";
The code for the whole layer would be this:
<P>
<DIV style="border:solid; border-width:2;
border-color:black;
background-color:lightblue; width:200"
onMouseover="this.style.backgroundColor='yellow';"
onMouseout="this.style.backgroundColor=
'lightblue';">
Text
</DIV>
MOVING AN IMAGE--PART 1 OF 4
To move an image, we need to work with style sheets and absolute
positioning. For the first part, we'll make a class that will position
a layer on the page:
The position declaration is absolute, meaning we are to define how
many pixels from the left and top of the browser we want the image
layer to be on the page. Here the layer will be 200 pixels from the
left and 10 pixels from the top.
MOVING AN IMAGE--PART 2 OF 4
The second part of moving an image is to write a short script for the
move. For this example, we'll move the layer from its current position
to a position 400 pixels from the left of the browser window. The
layer will be named "image1", which will be what we use to access the
layer's style properties:
Notice that we had to deal with the differing document object models
here. I used an object check, but a browser check will work as well.
After that, we only need to change the left property of the image,
which is the last command.
MOVING AN IMAGE--PART 3 OF 4
Now we'll show you how to put the style sheet and script together with
the HTML tags. In your HEAD section, use the style sheet we created
and the script we produced for the move:
<STYLE type="text/css">
<!--
.moveimage { position:absolute; left:200; top:10; }
-->
</STYLE>
<SCRIPT language="JavaScript">
<!--
function moveit()
{
if (document.layers || document.all)
{
if (document.layers)
var picture=document.image1;
if (document.all)
var picture=document.all.image1.style;
picture.left=400;
}
}
//-->
</SCRIPT>
Now, in your BODY, you need a style sheet layer named "image1" using
our class "moveimage". You'll also need to call the function somehow
to move the image layer. Here, we'll use a link that will move the
layer when it is clicked:
<A HREF="javascript:moveit
()">Click to move image</A>
<DIV ID="image1" class="moveimage">
<IMG SRC="scare.jpg">
</DIV>
MOVING AN IMAGE--PART 4 OF 4
If you also want to move the image vertically, you can do this by
changing the top property. In your HEAD section, use the style sheet
we created and the script we produced, but with an extra line for the
vertical movement:
Now, in your BODY, we can use the same code as we did before:
Click to move image
MOVING ANY STYLE SHEET LAYER--PART 1 OF 3
The image layer movement works for any style sheet layer that has
absolute positioning. For instance, we can move a layer that is a list
of links rather than an image. We start with a new style sheet:
<STYLE type="text/css">
<!--
.movediv { position:absolute; left:200; top:10; }
-->
</STYLE>
Now, we can make the script more universal by taking the name of the
layer in as a parameter:
<SCRIPT language="JavaScript">
<!--
function moveit(d_name)
{
if (document.layers || document.all)
{
if (document.layers)
var div_to=eval('document.'+d_name);
if (document.all)
var div_to=eval('document.all.'+d_name+'.style');
div_to.left=400;
div_to.top=150;
}
}
//-->
</SCRIPT>
Finally, we can call the script in the page. Be sure to send the name
(ID) of the layer along as a parameter:
<A HREF="javascript:moveit('div2')
">Click to move DIV</A>
<DIV ID="div2" class="movediv">
<A HREF="url">Link 1</A><BR>
<A HREF="url">Link 2</A>
</DIV>
MOVING ANY STYLE SHEET LAYER--PART 2 OF 3
Now I'll explain the script we used in the previous tip more
thoroughly. Here it is again:
By taking in the parameter, it made the script a little more complex.
When I first saw the +variable+ syntax, I was curious about what it
did.
The + signs are used to "escape" the variable from the quote marks
that define a string. What we do is temporarily end the string but add
the value of the variable to it. Then we can restart the string if we
need something after the variable. Since this doesn't work normally,
we use the eval function to add the values together as they are both
strings here. So:
eval('document.all.'+d_name+'.style');
Say the parameter sent for d_name (the name of our layer) was "div2".
The eval function places this in the line so we can access this layer.
It comes out as
document.all.div2.style
MOVING ANY STYLE SHEET LAYER--PART 3 OF 3
One more note on this idea. If you plan to use a background color,
you'll notice that the display is not the same in Netscape as it is in
Internet Explorer. Netscape cuts off the background color at the end
of the text and not your width. You can fix it with a table and a
background color defined in it, or you can add an ILAYER that defines
the width and color for Netscape in the HTML code we used:
<A HREF="javascript:moveit
('div2')">Click to move DIV</A>
<DIV ID="div2" class="movediv">
<ILAYER width="80" bgColor="lightblue">
<A HREF="#">Link 1</A><BR>
<A HREF="#">Link 2</A>
</ILAYER>
</DIV>
This way, your moveable layer will have the same look and feel in
either browser.
NOTES ON LAYER POSITIONING
You'll notice that most of the previous tips used absolute positioning
for layers. You can also use relative positioning, which will put the
layer on the page depending on the element before it. If you use
position:relative with no top or left properties, the layer will
display like you placed it in the code.
You can also place it in relation to the element that is directly
before it (provided it is not positioned as absolute). So, you can
place the layer in from the left 10 pixels and down 10 pixels from the
last element using relative positioning with left:10 and top:10. So,
if you want to do this for a layer that follows a link:
Link Text
Text!
Your layer will now be indented 10 pixels from the link and start 10
pixels below the link. It can be useful but is often not as stable as
absolute positioning when coding a script.
Also, you have static positioning. This one just puts the layer right
where it would be on the page normally.
INTERNET EXPLORER: CHANGING FONT COLOR
You can change the font color of a layer by accessing the style
property of color. To get to the font color in JavaScript, you use
this.style.color
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This is Text!
INTERNET EXPLORER: CHANGING FONT FACE
You can change the font face of a layer by accessing the style
property of font-family. To get to the font face in JavaScript, you
use
this.style.fontFamily
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This is Text!
INTERNET EXPLORER: CHANGING FONT SIZE
You can change the font size of a layer by accessing the style
property of font-size. To get to the font size in JavaScript, you use
this.style.fontSize
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This is Text!
INTERNET EXPLORER: CHANGING FONT WEIGHT
You can change the font weight of a layer by accessing the style
property of font-weight. To get to the font weight in JavaScript, you
use
this.style.fontWeight
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This has a border!
INTERNET EXPLORER: CHANGING FONT VARIANTS
You can change the font variant of a layer by accessing the style
property of font-weight. To get to the font variant in JavaScript, you
use
this.style.fontVariant
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This has a border!
INTERNET EXPLORER: CHANGING FONTS, LETTER SPACING
You can change the spacing between letters of a layer by accessing the
style property of letter-spacing. To get to the spacing in JavaScript,
you use
this.style.letterSpacing
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This has a border!
INTERNET EXPLORER: CHANGING A TABLE BORDER COLOR
You can change the border color of a table by accessing the table
property of borderColor. To get to the border color in JavaScript, you
use
this.borderColor
Here is an example of this change occurring when the viewer moves the
mouse over the table:
This is Text
INTERNET EXPLORER: CHANGING A TABLE BORDER SIZE
You can change the border size of a table by accessing the table
property of border. To get to the border size in JavaScript, you use
this.border
Here is an example of this change occurring when the viewer moves the
mouse over the table:
This is Text
INTERNET EXPLORER: CHANGING MARGINS
You can change the left margin (for the entire layer, including the
background and borders) of a layer by accessing the style property of
margin-left. To get to the left margin in JavaScript, you use
this.style.marginLeft
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This has a border!
You can do the same for the bottom, top, or right sides by using
marginBottom
marginTop
marginRight
INTERNET EXPLORER: CHANGING PADDING
You can change the left padding (for the text within the layer) of a
layer by accessing the style property of padding-left. To get to the
left padding in JavaScript, you use
this.style.paddingLeft
Here is an example of this change occurring when the viewer moves the
mouse over the layer:
This has a border!
You can do the same for the bottom, top, or right sides by using
paddingBottom
paddingTop
paddingRight
INTERNET EXPLORER: CHANGING TABLE PADDING
You can change the cell padding of a table by accessing the table
property of cellpadding. To get to the cell padding in JavaScript, you
use
this.cellPadding
Here is an example of this change occurring when the viewer moves the
mouse over the table:
This is Text
INTERNET EXPLORER: CHANGING TABLE SPACING
You can change the cell spacing of a table by accessing the table
property of cellspacing. To get to the cell spacing in JavaScript, you
use
this.cellSpacing
Here is an example of this change occurring when the viewer moves the
mouse over the table:
This is Text
LAYER ANIMATION--PART 1 OF 4
We've discussed moving a layer from one point to another when it just
jumped to the second spot. A layer can move more smoothly using some
script to create an animation effect. In this tip, we'll set up the
style sheet we'll use for this trick. Next, we'll get to the script.
Here's the style sheet:
The moveimage class will be used on an image that we will animate. The
hiddentext class will be used for some text that will be uncovered
when the image moves away.
LAYER ANIMATION--PART 2 OF 4
Now that we have the style sheet, we can look at the script that will
be used for the animation effect:
The procedure for Netscape and Internet Explorer is a little
different, which we have discussed before, but the main theme is the
same. We grab the "left" property of the object from its style sheet
properties and add a set number to it. It repeats until it hits 400
pixels from the left. Also, this takes a parameter called spot, which
will be the same as the initial left position of the image. This will
show up in the HTML, which we'll cover next time.
LAYER ANIMATION--PART 3 OF 4
Now, we get to the HTML portion of the animation. Here, we create a
link that will set the animation in motion by calling the moveit()
function from the script. The parameter 200 is sent, which is the same
as the left positioning of the image layer from its style sheet
properties. The two DIV sections place the image and the hidden text
on the page, along with which style sheet classes they will use.
Click to move image
Hello There!
LINKS: THE DHTML ZONE
The DHTML Zone includes a nice downloadable tutorial, plus articles,
resources, and other information on DHTML.
DHTML Zone
http://www.dhtmlzone.com/index.html
LINKS: THE DYNAMIC DUO
The Dynamic Duo contains a DHTML tutorial with numerous sections and
tips. The site also includes demos, games, and a downloadable version
of the tutorial.
The Dynamic Duo http://www.dansteinman.com/dynduo/
LINKS: WEBREFERENCE
I'd like to highlight a few useful DHTML links that you may find
valuable as you work. Feel free to send me suggestions on future links
or tips you'd like to see here.
The first link is to an excellent area of Webreference.com on the
topic of DHTML. They get into such subjects as hierarchical menus,
dynamic headlines, jigsaw puzzles, and more.
DHTML Lab http://www.webreference.com/dhtml/
Most tips are from TipWorld - http://www.tipworld.com :The Internet's #1 Source for Computer Tips, News, and Gossip; John Pollock is a software developer working in DHTML, JavaScript, and related technologies. You can see more examples of his work and reach him at: http://www.pageresource.com and http://www.javascriptcity.com