The inspiration for this code was New-Window Links in a Standards-Compliant World. They were using the “rel” attribute and checking it for “external” to update the anchor’s target attribute. I lean towards not opening new windows unless it’s an off-site link to improve the user’s experience. Furthermore, I try to avoid adding more code when I can simply use an element’s existing attributes to serve my needs.
The externalLinks function below sets the “target” attribute to “_blank” for all links that point off-site. It checks the existing anchor’s href attribute for “://” which matches both “http://” and “https://”.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) oldonload();
func();
}
}
}
function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
if (anchors[i].getAttribute('href') && anchors[i].getAttribute('href').indexOf('://') > -1) anchors[i].target = '_blank';
}
}
addLoadEvent(externalLinks);
This is written to be a drop-in-and-go function. No XHTML modifications are necessary 🙂
Note: Credit for the addLoadEvent function goes to Simon WIllison.