Grow your CSS skills. Land your dream job.

Last updated on:

Target Only External Links

Technique #1

$('a').filter(function() {
   return this.hostname && this.hostname !== location.hostname;
}).addClass("external");

Technique #2

$.expr[':'].external = function(obj) {
    return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$('a:external').addClass('external');

Technique #3

$('a:not([href^="http://your-website.com"]):not([href^="#"]):not([href^="/"])').addClass('external');

Technique #4

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
       // This is an external link
   }
});

Comments

  1. Permalink to comment#

    Reference URL no longer works.

  2. Permalink to comment#

    Any info on which of these is optimal for performance? (I’m guessing not #4 heheh)

    • I actually have no idea, that would be good to know.

    • Permalink to comment#

      Why does #4 create a new regular expression object on every iteration of the loop? That’d be pretty slow, as it’d have to parse the regexp on every iteration. I think it’d be significantly faster to create one RegExp, before the loop starts.

  3. Andy
    Permalink to comment#

    This is great, but I\m new to jquery – so how do you use this code? I assume it goes int he head somewhere, and then have a css style for ‘external’ – but does it need script tags etc?

  4. Permalink to comment#

    Do it with CSS:

    a[href^=”http://”]{ /*Style an external link here*/ }

    • Andy
      Permalink to comment#

      Nice – but this wouldn’t work if you have a CMS system that uses absolute urls (I think WordPress does this?)

    • Permalink to comment#

      Can you use this CSS technique to insert this:
      target=”_blank”
      into the href tag? I want to find all external links on a page and open them in a separate window, not style them.

    • Just in case any one comes across this like I did, and wants a CSS only alternative, this is what I used:

      a[href*="//"]:after {content: ">"}

      It is mainly for relative links only, or else your own links will get the content:">"

  5. why not use document.domain rather than manually typing in the domain?

  6. Jon Spencer
    Permalink to comment#

    @Rory – You can do it that way :)

    a[target=”_blank”] { yourstyle: style !important; }

  7. tushar lapani
    Permalink to comment#

    Hello frds!!
    I have two question here.
    first one is how i can prevent default selection of radio button.

    second one is that how i can open new window in parent window of the current. I have use code like
    window.open(‘mypage.html’ , ‘_parent’)

    what is prob with this code??????

    Help me plzzzzzzzz

  8. Permalink to comment#

    With pure CSS you can achieve this by setting all links to have the external treatment and using the cascade w/ attribute selectors to target and unset your exclusions. This technique probably won’t work on all browsers (*ahem* oldIE), but it’s handy when you don’t have complete control over how your markup is created—like in a CMS with inconsistant modules/plugins that write markup—where you have a mix of absolute and relative links and no way to apply an class="external", rel="external", target="_blank", etc. and you don’t want to rely on JavaScript.

    
    /* target all anchors with an href attribute */
    a[href] { 
    	display: inline-block; 
    }
    
    /* do something special to indicate an external link */
    a[href]:after { 
    	content: ">";
    }
    
    /* target what you consider to be "internal" links and undo styles */
    a[href*="your.domain.com"],
    a[href^="/"],
    a[href^="#"],
    a[href^="mailto:"],
    a[href^="javascript:"] {
    	display: inline;
    }
    
    /* undo */
    a[href*="your.domain.com"]:after,
    a[href^="/"]:after,
    a[href^="#"]:after,
    a[href^="mailto:"]:after,
    a[href^="javascript:"]:after {
    	content: none;
    }
    
    
    
  9. ravi

    I am trying to open rss feed on my website to open in new tab but its not working ,I have trying everything ,please help me.i think this script is preventing that to happen.i m new to this.can u please tell me what I need to change in this to external link to open in new tab.
    $(document).ready(function() {
    function filterPath(string) {
    return string
    .replace(/^\//,”)
    .replace(/(index|default).[a-zA-Z]{3,4}$…
    .replace(/\/$/,”);
    }
    var locationPath = filterPath(location.pathname);
    var scrollElem = scrollableElement(‘html’, ‘body’);

    $(‘a[href*=#]’).each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if ( locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,”) ) {
    var $target = $(this.hash), target = this.hash;
    if (target) {
    var targetOffset = $target.offset().top;
    $(this).click(function(event) {
    event.preventDefault();
    $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
    location.hash = target;
    });
    });
    }
    }
    });

    // use the first element that is “scrollable”
    function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
    var el = arguments[i],
    $scrollElement = $(el);
    if ($scrollElement.scrollTop()> 0) {
    return el;
    } else {
    $scrollElement.scrollTop(1);
    var isScrollable = $scrollElement.scrollTop()> 0;
    $scrollElement.scrollTop(0);
    if (isScrollable) {
    return el;
    }
    }
    }
    return [];
    }

    });

  10. Permalink to comment#

    hey there and thank you for your information – I have certainly
    picked up something new from right here. I did however
    expertise several technical issues using this web site, since I experienced to reload the website many times previous to I could get it to load properly.
    I had been wondering if your hosting is OK? Not that I am complaining, but slow loading instances
    times will often affect your placement in google
    and could damage your quality score if ads and marketing with Adwords.
    Anyway I’m adding this RSS to my email and can look out for a lot more of your respective intriguing content.
    Make sure you update this again soon.

  11. Bill Hinderman
    Permalink to comment#

    I’m handling it like this right now:

    
    a, .link
      &[rel^="external"],
      &[rel*=" external"],
      &[target^="blank"],
      &[target*="blank "],
      &:not([href*="website.com"]),
      &:not([href^="/"]),
      &:not([href^="#"]),
      &.external {
        //external styles
      }
    }
    
    

    Put it here, as well.

  12. OK this cool an all but… For a begginer like me where do I put this and how? I need it for a website i’m currently working on. Please if you can cater for beginners I need step by step.

    Thank you.

  13. Andrew
    Permalink to comment#

    BOO YAH – love it!
    Thanks Chris for putting together a external link targeting using either:
    CSS selectors or modular jQuery.

    Time saver!

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".