RE: to js or not to js?

> Although I'm not sure whether this tactic works for selectively disabled
> object model features, the best way of checking for support is not to
> sniff the browser type, but to use code that probes for the
> actual features,
> you want to use.  One way relies on the fact that the various methods
> are associated with objects and you write code that asks the type of
> any name subordinate to an object.

Agreed.

A bit of practical how-to for those who aren't sure what David means.

In javascript just about anything can be cast to a boolean. In particular
all objects will be cast to true, all functions will be cast to true, and
undefined will be cast to false.

Example 1. We want to do something with the document.all object:

if (document.all){
	/*if we got here then document.all is an object.
	Hence it got cast to true. Hence we can use it.*/
}
else{
	/*if we got here then document.all is undefined.
	Hence it got cast to false. Hence we can't use it.*/
}

It's important to note that we already know that all javascript browsers
have a document object. Otherwise we'd have to test if(document) first.

Example 2. We want to call self.print():

if (self.print){
	/*if we got here then self.print is a function.
	Hence it got cast to true. Hence we can use it.*/
	self.print()
}
else{
	/*if we got here then self.print is undefined*/
	alert('can't print from javascript').
}

The best way to use this varies from task to task.
In some cases we are best to just give up the task (e.g. for something we
want to do in response onload).
In some cases we might try another approach to the same thing:

function replacePage(URI){
	if (location.replace){
		/*location.replace doesn't break the back button if called when the page
loads, because it replaces the current page in the history list, so back
"goes back" correctly. However not all javascript browsers support it*.
		location.replace(URI);
	}
	else{
		/*we're going to have to break the back button, but presumably it's
important enough that we go ahead and do it*/
		location.href = URI;
	}
}

In some cases we might only offer the option if it's available:

if (self.print){
	/*we can print from javascript, so therefore there is no risk in offering
to do so*/
	document.write('<p><a href="#" onclick="self.print(); return false;">Print
this page</a></p>');
}

Finally we can fallback to a non javascript functionality:

function updatePage(){
	if (document.all){
		//some code that uses document.all to alter the page.
		return false;
	}
	else
		return true;
}
...
<a href="nonJavascriptBackUp.html" onclick="return(updatePage())">Do
stuff</a>

In the above case the onclick will over-ride the normal <a> behaviour only
if it returns false, and it will only return false if it was able to carry
out the task we want.

Of course the above techniques don't magic away all accessibility concerns
with javascript, they are techniques not panaceae.

Received on Monday, 20 January 2003 06:52:57 UTC