Although best practice is to define where a hyperlink opens per link, you can use javascript to determine how external links work per page or even sitewide.
For instance, on my Tumblr-based portfolio site, I do not have specific control in my navigation to decide if links open in the same tab or a new tab. So, I added a javascript function to force all external links on my site to open in a new tab.
Code
<script>
document.addEventListener('DOMContentLoaded', () => {
const links = document.querySelectorAll('a');
links.forEach(link => {
const isExternal = !link.href.startsWith(window.location.origin);
if (isExternal) {
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
}
});
});
</script>
What to know about this script
DOMContentLoaded Event: The script runs once the DOM is fully loaded, which means it doesn’t block the rendering of the page.
Query Selector: It uses document.querySelectorAll('a')
, which is efficient for selecting anchor tags.
Simple Logic: The logic inside the loop is straightforward—checking if a link is external and then setting attributes. This is a lightweight operation.
How this Javascript’s function works
Here’s a breakdown of how it works:
- Event Listener: The
document.addEventListener('DOMContentLoaded', () => {...});
line sets up a function to be called when the DOM is ready. - Selecting Links:
const links = document.querySelectorAll('a');
selects all anchor (<a>
) elements in the document. - Looping Through Links: The
links.forEach(link => {...});
loop goes through each link. - Checking External Links: It checks if each link’s
href
does not start with the current site’s origin, identifying it as an external link. - Setting Attributes: If a link is external, it sets the
target
attribute to_blank
and therel
attribute tonoopener noreferrer
for security and performance reasons.