Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

How to Open Link in a New Window?

For general web development questions using HTML and CSS.
Post Reply
admin
Site Admin
Posts: 45

How to Open Link in a New Window?

Post by admin » Thu Aug 22, 2019 2:38 pm

HTML attribute (valid in HTML5 now):

Code: Select all

<a href="http://chriscoyier.net" target="_blank">This link will open in new window/tab</a>
#Inline JavaScript way:

Code: Select all

<a href="http://chriscoyier.net" onclick="window.open(this.href); return false;" onkeypress="window.open(this.href); return false;">This link will open in new window/tab</a>
#With jQuery:

Code: Select all

$('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');
       });
   }
});
Or, you can still avoid the validation problems and just append the class target=_blank thing to any links with href attributes starting with http://. The example below only targets links in a #content area. Scoping down like that might be a good idea in case your menus are dynamic and create full URLs.

Code: Select all

$("#content a[href^='http://']").attr("target","_blank");

Post Reply