Martin Martin - 9 months ago 49
Javascript Question

Using JavaScript to open links (absolute URLs only)

I'd like links within a website to open as normal when they take you within the website (navigation, internal page linking) but any links to an external source to open in a new window.

Putting target="_blank" in the HTML isn't an option any more as webkit browsers ignore this so I need to use JavaScript.

How would I use JS to open all absolute URLs on a page in a new window and leave all relative URLs as they are? (This is the method I'd use to distinguish the two.)

I guess it'll be an expanded version of:

onclick="''); return false;"

But the rest is beyond me…

I'd prefer to avoid using a class or id (in fact, an id wouldn't be possible due to CMS constraints) as I'd prefer to keep the markup as minimal and semantic as possible.

Answer Source

The selector filters the external link. By clicking a new window will be opened.

  <script src=""></script>
 <!-- Here is your site content -->
 $(document).ready(function() {
   $('a[href^="http://"]').on('click', function(e) {
     e.preventDefault();$(this).attr('href'), '_new');

Further you can use the following snippet:

$('a').on('click', function(e) {
    var domain = '',
        url = $(this).attr('href'),
        target = '_top';
    if (this.href.indexOf(domain) !== 0) {
        target = '_new';
    }, target);