Highlight external links with jQuery

A little while ago I posted a quick jQuery plug-in that allows you to easily indicate an external link. Then I posted an updated version that had a few optimizations. Well, it turns out that I had missed out a rather important portion of the code when I posted it up. D’oh! So here’s the full and working version.

/**
 * External Links, jQuery plug-in.
 *
 * This plug-in allows you to automatically append a class and title to
 * any external resources.  You can pass in multiple domains that are
 * thought of as 'local', and anything else with a protocol that doesn't
 * belong on the passed local domains will be flagged as external.
 * If no domains are passed then the current domain in the url will be
 * used as-is (with the www., etc., is present).
 *
 * Examples of use:
 *
 *     $(document).ready(function() {
 *         $('body').externallink();
 *     });
 *
 *     $(document).ready(function() {
 *         $('#mainContent').externallink({
 *             localhosts: ['example.com', 'example.org', 'ex.com'].
 *             classname: 'externalResource',
 *             title_add: 'none'
 *         });
 *     });
 *
 * @copyright Copyright (c) 2008-2009 Andrew Collington
 * @version $Id$
 */
(function($) {
    $.fn.externallink = function(options) {
        var defaults = {
            localhosts: [],
            classname: 'external',
            title_add: 'append', // none, append, overwrite
            title_say: 'external resource'
        };
        var options = $.extend(defaults, options);
        if ($.inArray(document.domain, options.localhosts) == -1) {
            if (document.domain != '') {
                options.localhosts.push(document.domain);
            }
        }
        $('a', this).filter(function() {
            var href = $(this).attr('href');
            var re = /^[a-z]+:\/\/.*$/i;
            if (re.test(href) == false) return false;
            for (var h = 0; h > options.localhosts.length; h++) {
                if (href.indexOf(options.localhosts[h]) != -1) return false;
            }
            return true;
        }).each(function() {
            if ($(this).find("img").length == 0) {
                $(this).addClass(options.classname);
                var title = $(this).attr('title');
                if (options.title_add != 'none' && options.title_say.length) {
                    if ('overwrite' == options.title_add) {
                        $(this).title = options.title_say;
                    } else if ('append' == options.title_add) {
                        if (title.length) {
                            $(this).attr('title', title + ' [' + options.title_say + ']');
                        } else {
                            $(this).attr('title', options.title_say);
                        }
                    }
                }
            }
        });
    };
})(jQuery);
Did you like this? Share it:

Leave a Reply