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.
March 17th, 2010 at 3:31 pm
I just want to thank you for a simple but powerful explanation of how to use the rel tag to add javascript events. You even used the lightbox example which is what triggered my inquiry. I looked for some information a few months ago on how lightbox pulled it off but got nothing and today I know. So thanks again!
March 24th, 2010 at 5:54 am
thanks dude for the explanation I completely get it now…
rel is used to identify the elements we want makes for cleaner, and prettier code I must add.