Martin Martin - 4 days ago 5
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="window.open(''); 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

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

<html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 </head>
 <body>
 <!-- Here is your site content -->
 <script>
 $(document).ready(function() {
   $('a[href^="http://"]').on('click', function(e) {
     e.preventDefault();
     window.open($(this).attr('href'), '_new');
   });
 });
 </script>
</body>
</html>

Further you can use the following snippet:

$('a').on('click', function(e) {
    e.preventDefault();
    var domain = 'http://example.com',
        url = $(this).attr('href'),
        target = '_top';
    if (this.href.indexOf(domain) !== 0) {
        target = '_new';
    }
    window.open(url, target);
});
Comments