Last active
April 26, 2016 08:10
-
-
Save markhowellsmead/6d2023776339f1a98a90 to your computer and use it in GitHub Desktop.
jQuery function to set targets of external links to “_blank”
This file contains hidden or 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
/* | |
jQuery function to set targets of external links to “_blank” | |
*/ | |
(function($){ | |
$.extend($.fn, { | |
get_hostname: function(){ | |
var url = $(this).attr('href'); | |
if(url){ | |
url = url.toString(); | |
if(url.indexOf('http://')!==0 && url.indexOf('https://')!==0 && url.indexOf('//')!==0){ | |
return false; | |
}else{ | |
return url.replace('http://','').replace('https://','').replace('//','').split(/[/?#]/)[0] + ''; // plus nothing to force string | |
} | |
} | |
}, | |
setAsExternalLink: function(){ | |
$(this).each(function(){ | |
var $link = $(this), linkobject = this; | |
var hostname = $link.get_hostname() + ''; | |
if( | |
hostname && | |
(hostname.indexOf(window.location.hostname)<0) && | |
(hostname.indexOf(window.location.hostname.replace('www.',''))<0) && // same domain without www | |
(hostname!=='') && | |
(hostname!==null) && | |
(hostname!==undefined) && (hostname!=='undefined') && | |
(hostname!==false) && (hostname!=='false') && | |
((linkobject.hash==='')||(linkobject.hash===null)||(linkobject.hash===undefined)) && | |
(hostname.indexOf('javascript')!==0) && | |
(hostname.indexOf('mailto:')<0) && | |
(!$link.hasClass('anchor')) && | |
(!$link.hasClass('fancybox')) && | |
(!$link.hasClass('toggle')) | |
){ | |
this.target="_blank"; | |
if(this.className.indexOf("tooltip")<0){this.title=hostname;} | |
} | |
}); | |
return this; | |
} | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment