Open links in a new window and still validate

Since the target attribute of links is no longer considered valid you have two choices to keep your pages valid and still have links open in a new window. Both involve a little javascript, which is fine – but the examples I have fond are horrible. You either have to write an onclick handler for each link or use javascript to reapply the _blank target after the page has loaded.

Looking (and failing) for an unobtusive way around what in reality is a minor issue I gave up and come up with

$(document).ready(function()
{
	$('a[rel~=external]').each(function(i)
	{
	    $(this).click(function(j)
            {
	        window.open($(this).attr('href'), 'child');
		return false;
	    });
	});
});

Add this and a reference to jQuery to your page header and and link with rel=”external” will open in a new window.

Clean, unobtrusive and valid – I love those words.

The Whole Code

<html>
 <head>
 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript">
 $(document).ready(function()
{
	$('a[rel~=external]').each(function(i)
	{
	    $(this).click(function(j)
            {
	        window.open($(this).attr('href'), 'child');
		return false;
	    });
	});
});

 </script>
 </head>
 <body>
   <a href="http://andrewbleakley.com" rel="external">This link will open in a new window</a>
<br /><br />
<a href="http://andrewbleakley.com">This link will <strong>NOT</strong> open in a new window</a>
 </body>
 </html>
VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)

No related posts.

Tags: ,

Leave a Reply