links, graceful degradation and javascript

Aug 18, 2006 · 0 comments

in general

I’ve been reading DOM Scripting: Web Design with JavaScript and the Document Object Model by Jeremy Keith, and have been impressed with the focus on gradeful degradation, unobtrusive javascript and backwards compatibility.

I am going to start adopting a new method of coding links that evoke js calls. In the past, I’ve done as follows:

<a href="javascript:void(0)" onclick="showPic('bigben.jpg');return false">view Big Ben<a>

I’ve long known that this isn’t accessible if the user does not have js enabled. I ignored this little fact. But Keith offers up such a simple alternative, there is no reason not to do it.

1. use the href attribute. Link to the image:
<a href="bigben.jpg">

2. separate the behavior from the content. Add the appropriate function externally using an event handler: (note this assumes this is a list of links within a ul or ol with an id of ‘gallery’) note: it also doesn’t add the event handler as generically as I’d like, shouldn’t it check for click as well as onclick? ah well…

....
var gallery = document.getElementById("gallery");
var links = gallery.getElementByTagName("a");
for (var i= 0; i < links.length; i++) {
   links[i].onclick = function() {
      return showPic(this);
     }
 }

Where showPic uses the getAttribute method to get the value of the href attribute.

function showPic(whichpic) {
 if (!document.getElementById("placeholder")) return true;
 var source = whichPic.getAttribute("href");
 var placeholder = document.getElementById("placeholder")
 placeholder.setAttribute("src", source);
 return false;
}

One trick is that it function also checks to see if the function executes properly to determine its return value; if it is able to properly execute, it returns false, and the link is not followed by the browser. But a check within the function returns true if the showPic function does not execute properly. As an alternative to the picture showing in an appropriate location on the page (its desired behaviour), clicking on the link will allow the user to still access the content, by navigating to it directly.

Good, robust code.

Leave a Comment

CommentLuv Enabled

Additional comments powered by BackType

Previous post:

Next post: