Creating cross-browser DHTML
-Creating a "cross-browser" layer
Ok, so we've got NS that understands the <layer> tag, and IE that understands the <span> and <div>. If we wanted to create a simple DHTML effect such as a moving image, we would usually need to use two tags- A layer tag for NS 4, and either a div or span tag for IE 4. Not exactly pretty, uh? Well, I recently learned that there is actually a way to create a "cross-browser" layer that uses only one tag, although its a little buggy on the NS side. Apparently NS 4 treats an absolutely positioned div the same as a layer. So, without any further delay, here's an example of a cross browser layer:
<div id="crosslayer" style="position:absolute"></div>
NS 4 treates the above div exactly the same as it would with a layer. Like any other layer, to access it , we would first go go through the document object, then the layer's id:
In IE 4, we would simply use the div's id:
I found that in NS, specifying a layer this way, while convenient in terms of cross-browser compatibility, has one major draw back. Such a layer doesn't always behave the way a normal layer should, and can sometimes actually crash the browser. Just be prepared to expect the unexpected!
-Browser sniffing- object detection
Personally, I hate using the navigator object- its so complicated to use (just look at the above mess!). Well, I have good news to bring to you. There is actually a lot quicker way to sniff out various browsers, and its called object detection.
Let's do an example. We know that NS 3+ and IE 4+ support the document.images object. If we wanted to sniff out these browsers, we would do this:
Translating the above into English, it reads: "If the browser supports the images object (which only NS 3+ and IE 4+ do), alert a message.
Think of object detection as an indirect way of determining the browser type of the user. Instead of directly determining the name and version of the user's browser (through the navigator object), object detection is a more generic, less hassling browser sniffing technique.
So, how can we use object detection to sniff out NS 4 and IE 4? Well, only NS 4 supports the document.layers object, and only IE 4 supports document.all. We can use this knowledge to easily determine whether the user is using NS 4, IE 4, or both:
Now you never have to return to the messy navigator object to do your browser sniffings!
Obviously, this tutorial serves only as an introduction to DHTML. Here are some other resources to continue your DHTML endeavor:
This tutorial is written and contributed by Davud Gardner. David is an aspiring web designer, and hopes to one day quit his day time job and create websites for a living.