Mootools Automated External Links Class

A co-worker kept asking me for a Mootools class that automatically set links to external sites to open in a new window. So I spun up the following. It’s fairly self explanatory, just thought I would share (and have a centralized place to store it)

Basically, it just parses the DOM and checks if http and the document.location.host are in the href, any links that don’t match the current page it sets the target attribute. It also allows a CSS class to be added.

//<![CDATA[
/*
	name : com.aol.externallinks
	author : gregory tomlinson
	///////////////////////////
	///////////////////////////		
	dependencies : mootools 1.2
	///////////////////////////
	///////////////////////////
*/
 
if( typeof com === "undefined" ) var com = {};
if( typeof com.aol === "undefined" ) com.aol = {};
com.aol.externallinks = new Class({
 
	Implements: [Options, Events],
	options : {
		currentServer : '', // override use of document.location.host
		extLnkClass : '',
		autoRun : true,
		onComplete : $empty // Event
	},
	initialize : function (options)
	{
		this.setOptions(options);
		if(this.options.autoRun) { this.run(); }
	},
	run : function() {
		var b = $$('body')[0], lnks = b.getElements('a'), s = this.setServer();
		lnks.each( function(item) {
			this.setLink( item, s );
		}, this );
 
		this.fireEvent( 'complete', { "statusText" : "ok", options : this.options } );
		return true;
	},
	//Helpers
	setServer : function() {
		var s = ( this.options.currentServer !== '' ) ? this.options.currentServer : document.location.host;
		return {
			getServer : function() { return s; }
		}
	},
	setLink : function( el, server ) {
		var h = el.get('href');
		if( h.indexOf('http') >= 0 && h.indexOf( server.getServer() ) < 0 ) {
			el.set('target', '_blank');
			if( this.options.extLnkClass !== '' ) el.set('class', this.options.extLnkClass )
		}					
		return el;
	}
});
//]]>

Pretty simple stuff, an example of it’s use would be

var lnks = new com.aol.externallinks( {
    extLnkClass : 'aCSSClassForExtLnks',
    onComplete : function() {
         alert('I made all the links different if need be!');
    }
} );

In all likely hood, you would tie the instantiation of this class to the window DOM ready event, which you can learn more about here.

blog comments powered by Disqus