There is a quick, easy method to force web browsers to open external links (or any links you want) in a new window or browser tab.
First, Identify the links you wish to open in a new window. In jQuery, you can complete the previous two steps in one line of code:
$('a[href^="http://"]').attr('target','_blank');
The jQuery selector—$(‘a[href^=”http://”]’)—uses an attribute selector (page 133) to identify <a> tags that begin with http:// .
If you don’t want to open up a new window for every page of your site (your poor visitors), you need code like the following:
var myURL = location.protocol + '//' + location.hostname;
$('a[href^="http://"]').not('[href^="'+myURL+'"]').attr('target','_blank');
This code first specifies the URL for your site and assigns it to a variable myURL.
So the complete code to use on site page.
<script src="jquery-1.6.3.min.js"></script>
<script>
$(document).ready(function () {
var myURL = location.protocol + '//' + location.hostname;
$('a[href^="http://"]').not('[href^="' + myURL + '"]').attr('target', '_blank');
});
</script>
0 comments:
Post a Comment