Wednesday, August 26, 2009

Avoid Those Ugly <a href="#"></a> Links

Usually when web developers want to use JavaScript to open a link in a new window with specific attributes (height, width etc.), they take recourse to this kind of ugly looking <a href> tags:

<a href="#" onclick="doSomething();">Do Something!</a>

There is much to dislike about this way of writing code:
  1. When you hover your mouse over the link, the result is both ugly and uninformative—all you see is a "#" in the status bar, rather than the URL to which the link will take you.
  2. When the link works, the location bar in the main window now shows a "#" appended to the parent page's link. Essentially, this has changed the apparent URL of the current (i.e., parent) page.
    • This may not seem like a big deal at first sight, but it fools the bookmarking feature (for example) into thinking that the current (i.e., the parent) page is not bookmarked (assuming it was bookmarked to begin with).
    • Similarly, the Read It Later Firefox extension gets fooled into showing that the current page is no longer marked for reading later (assuming it had been so marked to being with).
  3. If the user's browser has JavaScript disabled, the link simply won't work. There is no graceful failure of the code in such a case.
The following code solves all the aforementioned problems:
<a href="http://random-outpourings.blogspot.com/"
onclick="return doSomething(this);"
target="_blank">Do Something!</a>

In the doSomething() method, make sure you return a false as your last executed statement. For example:
function doSomething(link) {
  var newWin = window.open(link.href,'win1',
    'width=800,height=600,scrollbars=yes,resizable=yes');
  return false;
}

Take care that both the return false; at the end of the JavaScript function and the return in front of the call to doSomething(this) are present (highlighted above in red).

The benefits of opening new windows this way:
  1. When the user hovers his/her mouse over the link, the destination URL is visible in the status bar.
  2. When JavaScript is enabled in the user's browser and the user clicks on the link, it opens in a new window as desired.
  3. When JavaScript is disabled in the user's browser and the user clicks on the link, it will still work (the link will open in a new tab or window). The code fails gracefully!

Here, test this link: read something!

Hope this neat little trick helps other web developers!

No comments:

Post a Comment