views:

46

answers:

2

On my website i have many outside links, as well as internal links. i'd like some kind of solution in javascript or w/e that detects outside links and opens them in a new tab, but leaves internal links to be opened in the same tab. thanks! =)

+1  A: 
function getXterlinks()
{
    var Xterlinks = document.getElementsByTagName('A');
    for (var i=0;i<Xterlinks.length;i++)
    { 
        var eachLink = Xterlinks[i];
        var regexp_isYourdomain="your-domain.com";
        var regexp_ishttp=/(http(.)*:\/\/)/;
        if( (eachLink.href != null) && (eachLink.href.match(regexp_isYourdomain) == null) && eachLink.href.match(regexp_ishttp)!=null )
        {
            eachLink.target ="_blank";
        }
    }
}

Source: http://www.mediawiki.org/wiki/Manual:Opening_external_links_in_a_new_window#How_to_make_external_links_open_in_a_new_window

Yuval A
Note that it is up to the browser to select if the link should be opened in a new window or in a new tab. You cannot force one behavior or the other using html or JavaScript.
Jan Aagaard
@Jan - true, but using `target="_blank"` is the standard way to do this. Your comment is in place, nonetheless.
Yuval A
that worked! thank you! :D
MKv4
A: 

Yeah, well, jQuery's still JavaScript. How about:

$('a[href^="http://your-domain.com"]').attr("target", "_self");

$('a').not('a[href^="http://your-domain.com"]').attr("target", "_blank");

Not sure about the second, though, but you get the idea.

nush