Open all external links in a new window using jQuery

In the following code we set the “target” attribute to “_blank” for every anchor that has an “href” attribute starting with “http(s)://”…

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" /></script>
<script type="text/javascript">
$(document).ready(function() {
 $('a[href^="http://"],a[href^="https://"]').attr('target','_blank');
});
</script>

Most examples of this type only check for links starting with “http”, this of course would cause internal relative links such as “httpd_info_page.html” to open in a new window. This is why I check specifically for the full strings.

One thought on “Open all external links in a new window using jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *