Open Link in a New Window


HTML attribute (valid in HTML5 now):

<a href="" target="_blank">This link will open in new window/tab</a>

#Inline JavaScript way:

<a href="" onclick="; return false;" onkeypress="; return false;">This link will open in new window/tab</a>

#With jQuery:

$('a').each(function() {
   var a = new RegExp('/' + + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
 , '_blank');

You can do this straight with HTML, but that is invalid markup, this takes care of business without invalid code and unnecessary markup.

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.

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

Also note that there are a wide variety of different ways to only target external links.

  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.