Change Rel External to Target Blank using Prototype


This entry is part 9 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.

Series Navigation«Zip Code, Phone Number and Replacing Empty Fields with Really Easy ValidationOpen Links to a Different Site in a New Window with Prototype»

Popularity: 38% [?]


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!