Created
April 9, 2015 10:56
-
-
Save hannesl/22523ac60a6a5f632115 to your computer and use it in GitHub Desktop.
Another take on opening external links in a new window.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
// Get the current domain name without any sub domains. | |
var internalDomain = (function () { | |
var domainParts = [], | |
hostnameParts = location.hostname.split("."), | |
i; | |
if (hostnameParts.length == 1) { | |
return location.hostname; | |
} | |
for (i = 0; i < 2; i++) { | |
domainParts.unshift(hostnameParts.pop()); | |
} | |
return domainParts.join("."); | |
})(); | |
// Regex for a full URL. | |
var fullUrl = /^([\w]+:)?\/\/.+/i; | |
// Regex for a full internal URL. (See this trick: | |
// http://stackoverflow.com/questions/185510/how-can-i-concatenate-regex-literals-in-javascript) | |
var internalUrl = new RegExp(/^([\w]+:)?\/\/[^\/]*/.source + internalDomain + /\//.source); | |
function urlIsExternal(url) { | |
return url.match(fullUrl) !== null && url.match(internalUrl) === null; | |
} | |
function checkLinkTarget(link) { | |
var href = link.getAttribute("href"); | |
if (href && urlIsExternal(href)) { | |
link.setAttribute("target", "_blank"); | |
} | |
} | |
// Process all links with a slight delay to minimize the performance impact. | |
(function() { | |
// All links without an existing target attribute. | |
var links = $("a:not([target])", context).toArray(); | |
var processLinks = function () { | |
checkLinkTarget(links.shift()); | |
if (links.length > 0) { | |
setTimeout(processLinks, 10); | |
} | |
}; | |
processLinks(); | |
})(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment