Change Rel External to Target Blank using Prototype

by Terri Ann on April 7, 2008

This entry is part 7 of 10 in the series Prototype Tutorial

When coding strict XHTML sites it’s important to not use the target attribute in your anchors. <a href="http://www.example.com">example</a> validates but <a href="http://www.example.com" target="_blank">example</a> will not. I know it’s better for my experience if windows don’t open in new windows but clients always want it.

There’s been a popular trend to use JavaScript to add target="_blank" to anchors with rel="external". So in the name of making everything in my site Prototype based I worked out a script to do just that.

JavaScript

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

It’s nice, quick and easy. By using Event.observe it will automatically apply the changes when the page is done loading, no matter if the script is in the header, in the body or in an external included JavaScript file.

Leave a Comment

Previous post:

Next post: