Last active
August 29, 2015 13:59
-
-
Save rhysburnie/10944948 to your computer and use it in GitHub Desktop.
Return filtered collection of external links
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* EXAMPLE: | |
* Find external links and add class to them | |
* Except for exclusions | |
* $('a[href^="http"]').externallinks({ | |
* excludeOrigin: true, // also exclude the host site | |
* exclusions: ['urltoexclude.com'] | |
* }).addClass('external-link'); | |
*/ | |
(function($){ | |
var defaults = { | |
exclusions: [], | |
excludeOrigin: true | |
}; | |
$.fn.externallinks = function(options) | |
{ | |
options = $.extend({},defaults,options||{}); | |
if(options.excludeOrigin) { | |
var loc = document.location; | |
// same as loc.origin but some browsers | |
// dont seeem to have that property | |
options.exclusions.push(loc.protocol + '//' + loc.hostname); | |
} | |
return $(this).not(function(){ | |
var truth = false, | |
src = $(this).tagName().toLowerCase() === 'srcipt' ? 'src' : 'href'; | |
for(var i=0,c=options.exclusions.length; i<c; i++) { | |
if(truth) break; | |
truth = this[src].indexOf(options.exclusions[i]) >= 0; | |
} | |
return !!truth; | |
}); | |
} | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Only looks on
href
orsrc
(if script tag)EXAMPLE:
var external_links = $('a').externallinks();
For styling purposes obviously these days it's better to style via attribute selectors.
This can be useful for other js requirements.