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!
{googlead}
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!
This site runs on the Thesis WordPress Theme
If you're someone who doesn't understand a lot of PHP, HTML, or CSS, Thesis will give you a ton of functionality without having to alter any code. For the advanced, Thesis has incredible customization possibilities via extensive hooks and filters. And with so many design options, you can use the template over and over and never have it look like the same site.
If you're more familiar with how websites work, you can use the fantastic Thesis User's Guide and world-class support forums to make more professional customizations than you ever thought possible. The theme is not only highly customizable, but it allows me to build sites with a much more targeted focus on monetization than ever before. You can find out more about Thesis below:











{ 1 comment… read it below or add one }
I’m not familiar with prototype but I’m working with a site that uses this library, and I was looking for a solution like this. So thank you! Is it possible to modify this code to target a specific div? For instance, if I had a div “#othersites” and I only wanted the code to search that div and modify the links, how would I do that?