Return to Snippet

Revision: 12696
at March 25, 2009 00:07 by Ashung


Initial Code
function openExternalLink(elementId) {
    if(!document.getElementById(elementId) && !document.getElementsByTagName) return;
    var links = document.getElementById(elementId).getElementsByTagName('a');
    var localURL = 'http://snipplr.com';
    for(i=0; i<links.length; i++){
        url = links[i].getAttribute('href');
        if(url.indexOf(localURL) == -1 && url.indexOf('http') == 0) {
            links[i].setAttribute('target','_blank');
        }
    }
}

Example:
<div id="links">
<a href="http://snipplr.com">snipplr</a>
<a href="http://www.flickr.com">flickr</a>
<a href="/new">New Snippet</a>
</div>

<script type="text/javascript">
    openExternalLink('links');
</script>

Initial URL

                                

Initial Description
Open external links in new window.

Initial Title
Open external links in new window JavaScript.

Initial Tags
javascript

Initial Language
JavaScript