How To Automatically Add target=“_blank” To External Links Only?
In website, from a page connect to another page, we need a link to join both pages.
HTML hyperlinks syntax begin with <a>, by default a hyperlinks setting is target_self (without or without added target_self), opens the linked in the same window or tab as it was clicked. To open links in new window or tab, we use target_blank. Try click the following links for comparison:
<a target=”_blank” href=”http://www.poxse.com/”>link to poxse.com</a> – open link in new window or tab
<a href=”http://www.poxse.com/”>link to poxse.com</a> – open link in same window or tab
note: click the result to refresh below frame
Both links are point to the same page, but the page is open differently. Generally we use target_blank to link external page and target_self for inter-page linking. Manually setting on each link target could be tiring, to simplify our task we can use jquery to automatically handle it.
Insert below code in between <head></head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js” type=”text/javascript”></script> (skip this line of code, if the page itself already have jquery library)
<script>
jQuery(document).ready(function($) {
$(‘a’).each(function() {
var a = new RegExp(‘/’ + window.location.host + ‘/’);
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, ‘_blank’);
});
}
});
});
</script>