Skip to content

Instantly share code, notes, and snippets.

@cyokodog
Last active October 12, 2015 12:57
Show Gist options
  • Select an option

  • Save cyokodog/4029701 to your computer and use it in GitHub Desktop.

Select an option

Save cyokodog/4029701 to your computer and use it in GitHub Desktop.
jQuery External

#jQuery External

外部リンク(location.hostに一致しないリンク)に対し、target="_blank" や特定のクラス名を設定する jQuery プラグイン。

以下のように実行。

JavaScript

$('a').external();

CSS

a:hover.external{
    padding-right:14px;
    background:url("external.png") no-repeat right 3px #ffffcc;
    color:#ff00ff;
}

HTML

<div id="nav">
    <a href="?home">Home</a>
    <a href="?products">Products</a>
    <a href="?contact">Contact</a>
</div>
<ul>
    <li><a href="http://www.google.com">Google</a></li>
    <li><a href="http://www.yahoo.com">Yahoo</a></li>
    <li><a href="http://jp.msn.com/">MSN</a></li>
</ul>
<a href="http://cyokodog.tumblr.com/">
    <img src="http://24.media.tumblr.com/avatar_35a592364924_64.png"/>
</a>
(function(){
$.fn.external = function(option){
var c = $.extend($.fn.external.defaults,option||{});
var reg = new RegExp('^' + location.host);
this.each(function(idx) {
var target = $(this);
if(!reg.test(target[0]['host']) && target.prop('href')){
target.prop('target','_blank');
if(c.className && !target.find('img').size()) target.addClass(c.className);
}
});
return this;
}
$.fn.external.defaults = {
className : 'external'
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment