Gwellin.ca — Portfolio of Peter Fingler, Web Developer

Open External Links in a New Window with jQuery

Those who closely check their HTML 4.0 Strict pages for invalid code know that under that DOCTYPE it is improper to include the 'target' attribute in an <a> tag. The reasoning is Strict coding dictates that HTML should only be used for structure, CSS for styling, and Javascript for behaviour. So as a behaviour, the action of opening a link in a new window (or tab) falls to Javascript.

I found an article offering a rather simple method to do this, however I didn't like how it relied on a defined class name to work. What I have done with it is to check every link on the page for a beginning 'http://', accounting for other protocols, and use jQuery selectors to make things easier.

<script>
function linkBehaviour(link) { var href = $(link).attr('href'); if (href.match(/^(https?|ftp|file):\/\//i)) { $(link).click(function() { var newWindow = window.open($(this).attr('href'), '_blank'); newWindow.focus(); return false; }); } } $.each($('a'), function (key, value) { linkBehaviour(value); });
</script>

The key line of code is window.open(), where the second passed parameter accepts the same values as the <a> 'target' attribute. Nice and easy.