Open Links to a Different Site in a New Window with Prototype


While working on the Prototype script to change rel external to target blank I thought it would be kind-of neat to have another function that would detect external links and set them to rel="external" before all the rel="external" links get target="_blank" added to them.

So I made it.

One thing that was very important to me is that all the sub domains on my site do not open in a new window. If I have a link to another sub domain on my own site I probably won't want it to open in a new window. If I do, I'll have to implicitly set that which is a pretty reasonable requirement.

Just include prototype first, and in the sample code below you just need to replace ninedays.org with your own domain.

Once a page loads this will go through all your anchors with an href value (anchor points in a page that just have a name value set will be ignored) and it will use a regular expression to detect any link that starts with http:// and check that it's not to any page in your own domain (or it's sub domains) and it will add the rel="external" attribute/value pair then it will run through the process detailed in the change rel external to target blank post!

JavaScript

<script type="text/javascript">
Event.observe(window, 'load', function() {

    $$('a[href!=""]').each(function(link){
        var siteregex = /^(http:\/\/)([a-z]*\.)?(ninedays.org)/i;
        if(link.readAttribute('href').startsWith('http://') &&
          !link.readAttribute('href').match(siteregex)){
            link.writeAttribute('target','_blank');
            link.writeAttribute('rel','external');
        }
    });

    $$('a[rel="external"]').each(function(link){
        if(link.readAttribute('href') != '' && link.readAttribute('href') != '#'){
            link.writeAttribute('target','_blank');
        }
    });
});
</script>

Really easy to add and use to your pages, especially if you are already using Prototype!

Popularity: 29% [?]


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!