Javascript Tip: Use the rel Attribute

In HTML, <a> and <link> elements have a unique attribute, “rel.” Rel has practically no use in plain HTML these days, but with some creativity it can be an excellent hook for javascript events. This will provide you an unobtrusive way to change the behavior of these elements, without requiring “javascript:” links or onclick calls be written directly into the html.

Implementation:

var getElemsByRel = function(rel){
    aElements = document.getElementsByTagName("a");
    relElems = [];
    for (i = 0; i < aElements.length; i++) {
        if (aElements[i].hasAttribute("rel") && aElements[i].rel == rel) {
            relElems.append(aElements[i]);
        }
    }
	return relElems;
}

Case Study

Lightbox.js uses this to great effect: Any links with rel=”lightbox” activate the script, causing the image display to pop up with the target of the link as the image to display.

To accomplish this is very simple; for each element with the target rel attribute, one adds an onclick attribute that calls the function of one’s choosing, and - importantly - returns false, so that the link is not followed. As an added bonus, this technique fails extremely gracefully; if the javascript isn’t executed, the link is followed and the image is simply displayed in the browser.

Using rel in this case solves the problems of storing some relevant information in the link, forgoing the insertion of javascript into the markup, and providing some sort of semantic information in the markup as well.

Fuel another post

5 Responses to “Javascript Tip: Use the rel Attribute”

  1. graphic design Says:

    Thanks for all this input.

  2. Aaron Says:

    One thing to note is that hasAttribute() doesn’t work in IE, so you are better off using aElements[i].getAttribute(”rel”) != null

  3. Jean Dreesen Says:

    Slimbox, a lightbox clone, uses the rel attribute to, just like lightbox. It can be extended with the name of a group of photos between []. Example: rel=”lightbox[groupname]” What I want to know is, can I use the rel attribute to pass a parameter, like the heigth of a photo? Example: rel=”lightbox[groupname][500]“. 500 is the heigth of the photo. This way I could center every photo individual vertical.

  4. Charlie Says:

    I’m trying to use the rel attribute in a sothink dhtml menu to use the shadowbox iframe. Would this code be able to insert a rel attribute into the javascript that sothink compiles?

  5. Adam Says:

    The code is to access existing rel attributes, presumably hard-coded ones. You could certainly apply a rel attribute dynamically, that would involve getting a hold of the element and using a.rel = “whatever rel.” I can’t really tell you more, because I know nothing about sothink nor about shadowbox.

Leave a Reply

  • I promise I'll be nice to your email address