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.
June 2nd, 2008 at 11:19 pm
Thanks for all this input.