The reuasable Open in New Window javascript snippet

 As modern web development moves towards a more streamlined, dependency-free approach, it's important to revisit some of the common functionalities implemented in the earlier days with libraries like jQuery. One such functionality is opening links in a new window when they lead to external sites. Today, I want to share a reusable snippet written in plain JavaScript, inspired by the transition away from jQuery for simple tasks.

Why Move Away from jQuery?

For a long time, jQuery was the go-to solution for cross-browser compatibility issues and simplified DOM manipulation. However, as browsers have evolved, many of the utilities provided by jQuery have become native features of modern JavaScript, making jQuery less necessary and, in some cases, an unnecessary overhead.

A Vanilla JavaScript Approach

The snippet below replaces a common jQuery pattern used to open external links in a new tab. This approach uses native JavaScript methods and ensures that your site is a little faster by reducing reliance on external libraries.

document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.region-content a').forEach(function(link) {
    var href = link.getAttribute('href');
    // Check if href is defined, is a string, and is an absolute URL
    if (typeof href === 'string' && href.length > 0 && (href.startsWith('http://') || href.startsWith('https://'))) {
      var linkHost = new URL(href).host;
      var isExternal = linkHost !== window.location.host;

      if (isExternal) {
        link.setAttribute('target', '_blank');
      }
    }
  });
});

Benefits of This Approach

  • Performance: Eliminates the overhead of loading jQuery just for handling external links.
  • Maintainability: Uses clear and concise modern JavaScript, which is easier to read and maintain.
  • Compatibility: Fully compatible with all modern browsers.

As Drupal and other CMS'es are moving away from JQuery, it is the right move to prepare your snippets to be vanilla js!

 

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!