|
Shorten your code by detecting document objects rather than checking for the browser type.
Do you remember the browser detection script we worked on a while back? Then you probably remember
how much trouble it was to detect a specific browser type before we could run certain scripts. Here was how we had to do it:
browserName=navigator.appName;
browserVer=parseInt(navigator.appVersion);
if ((browserName=="Netscape" && browserVer>=3) ||
(browserName=="Microsoft Internet Explorer" &&
browserVer>=4))
version="n3";
else
version="n2";
That is a lot of code to run through, and it can be much worse when you create a script that has a lot of browser differences.
Well, instead of checking for the browser, we could have checked for the javascript object that we needed for the script to
work. Since we know that a hover button script needs the document.images object to work, we could shorten the above code
to say:
if (document.images)
{ ...code...}
In fact, this object just so happens to exist in the browsers we
checked for, and not in the browsers that were excluded. So, using this
object detection code, we are checking for Netscape 3 or higher, and MS
Internet Explorer 4 or higher! And as a bonus, if any other browser
happens to recognize the document.images object, the script will run
for them too! (Opera perhaps?)
You can also use a couple of the new objects to check for version 4 browsers. If you are looking only for NS4, check for the
document.layers object:
if (document.layers)
{ ...code...}
If you want only IE4, check for the document.all object:
if (document.all)
{ ...code...}
Of course, if you just want it to work for either version 4 browser, check to see if the browser has one object or the other:
if (document.all || document.layers)
{ ...code...}
For IE 5:
if (document.getElementByID && document.all)
{ ...code...}
For NS 6:
if (document.getElementByID && !document.all)
{ ...code...}
For both IE5 and NS6 (or better):
if (document.getElementByID)
{ ...code...}
You can find some more uses for this as you are coding, so that you can avoid those pesky javascript errors in older
browsers. While you are at it, it will probably keep away those errors with the newer browsers as well.
|