externalize()

Snippets are small pieces of code that do not fit in the UvumiTools plugin category. Please note that each of these semi-useful functions requires Mootools 1.2.

Let's say you want some of the hyperlinks on your site to be opended in new windows, because you don't want your users navigating completely away from your site (you greedy jerk). "Easy" you're thinking, just use the old target="_blank" method in your anchors. Yes, that works... if you don't care about making your HTML standards-compliant.

That's right, the target attribute, while useful, is not valid in a strict doctype, which is what we recommand using. So what is a web developer to do in this situation while managing to keep the site compliant? UvumiTools Javascript Snippet to the rescue! Here are three different Javascript functions that will allow you to have external links on your site while maintaining the glory of standards-compliance. Just set the rel attribute of the links you want to open in a new window to external (actually recommended anyway, for Google's indexer) and run one of those three scripts in a 'domready' function.

Why three different functions? Well, depending on the type of site you run, you might prefer one over the others:


First method, good for small website like blogs, small business, portfolio...

var externalize = function(){
$$('a[rel="external"]').addEvent('click',function(e){
e.stop();
window.open(this.get('href'));
}).removeProperty('external');
};

Second method, good for pages with many links (like Digg)...

var externalize = function(){
$$('a[rel="external"]').set('target','_blank');
};

Third method, for ajax heavy sites, with links generated without refreshing the page.

var externalize = function(){
document.addEvent('click',function(e){
var target = $(e.target);
if($defined(target.getParent('a'))){
target = target.getParent('a');
}
if(target.get('tag') == 'a'){
var rel = target.get('rel');
if($defined(rel) && rel == 'external'){
e.stop();
window.open(target.get('href'));
}
}
});
};

Usage:

window.addEvent('domready',function(){
externialize();
});

Here are some links that were patched with the first function (but the others work, we promise). If you click them they will open a new window, but if you look at the code, there is no target attribute.
SXSW, Austin City Limits, Moonstone Guitars

Technically, besides executing the function, it does not take more work to generate a link with rel="external" instead of target="_blank". It's a nice and easy improvement.