Open foreign domain links in a new window
Sep 14, 2012     16:59:45

Few weeks ago I saw a piece of code on my friend's website. Main task of this code - open foreign links in a new page.

$(document).ready(function(){
    $('a').each(function() {
        var a = new RegExp('/' + window.location.host + '/');
        if(!a.test(this.href)) {
            $(this).click(function(event) {
                event.preventDefault();
                event.stopPropagation();
                window.open(this.href, '_blank');
            });
        }
    });
})

Do you think this code is correct? As for me - I don't think so.

I can add few lines to this code to improove it:

  • "/*" before this code;
  • "*/" after this code;

The reason ot my decision - click event on a link. Technically this is correct. When we'll click on a link with foreign domain it will be opened on a _blank page. But I don't like nonusefull events. So I think it will be much better to use attribute target="_blank" for this issue.

$(document).ready(function(){
    var a = new RegExp('/' + window.location.host + '/');
    $('a').each(function() {
        if ( ! a.test(this.href)) {
            $(this).attr('target', '_blank');
        }
    });
})


Also this isea can be usefull for adding target="_blank" to links on different documents on a page - .pdf for example.

$(document).ready(function(){
    var pdf = /.pdf/;
    $('a').each(function() {
        if (pdf.test(this.href)) {
            $(this).attr('target', '_blank');
        }
    });
})

blog comments powered by Disqus