A Tech Blog

Unobtrusive Javascript Pop-up Links

One of the things I dislike the most about writing HTML is creating links that open in new windows. Since I try to make all my HTML standards-compliant, I can’t use the target="_blank" attribute in my links anymore, since it’s been deprecated in XHTML. Many have followed the new standard of making an inline onclick attribute of the link open the window, including myself. But what a pain it is to type it all out and remember the exact code to do it. Instead of this:
  <a href="http://www.example.com" onclick="window.open(this.href); return false;">External Link</a>

Wouldn’t it be easier to type this?

  <a href="http://www.example.com" rel="external">External Link</a>

I’m sure you’ll agree it’s much cleaner, easier to type, easier to remember, and to top it off, it’s (kind of) symantically correct. While the possible attribute values of rel do not include external, using it as a keyword to denote the relationship between an external page and your link makes sense. Best of all it validates with the W3C validator with flying colors.

How to Make it HappenSo how do we make the magic happen? The answer is with our good old friend Javascript. Basically we’re going to make a function that will crawl the document after the page loads and check for links that have rel="external" in it, then attach an Event.observe to each link that will cause it to open in a new window (note that you’ll need Prototype.js for this to work).

Here’s the code:

  function external_link(link) {
    var el = Event.element(link);
    if (el.tagName == 'IMG') {
      if (el.parentNode.tagName == 'A') {
        var el = el.parentNode;
      } else {
        return false;
      }
    }
    window.open(el.href);
    Event.stop(event);
    return false;
  }
  function init() {
    var links = $A(document.getElementsByTagName('a'));
    links.each(function(link) {
      if (link.getAttribute('rel') == 'external') {
        Event.observe(link,'click',function(e){ external_link(e); },false);
      }
    });
  }
  Event.observe(window,'load',init);

Note in the external_link function it checks if the item clicked was an image tag. If it is, then it will look up one node in the DOM tree to see if the image was enclosed in an anchor tag, and attach the event to that instead (since it contains the href it needs to open). If it doesn’t find anything, it will exit quietly.

Load this in your document header and off you go. You should be able to add rel="external" to any link on your page and it will open in a new window. Remember you need a copy of Prototype loaded as well. Leave a comment if have any questions or improvements.