Auto Open External Links In New Tabs - jold.external-hrefs.js

Auto Open External Links In New Tabs - jold.external-hrefs.js

jold.external-hrefs.js is a small jQuery plugin that has the ability to open external links in new browser tabs/windows.

How it works:

  1. Get the current hostname
  2. Check if the href attribute of the link has a different hostname than the current site
  3. Add the target="_blank" attribute to the external links.

How to use it:

1. Download and include the JavaScript file jquery.jold.external-hrefs.js after jQuery but before the </body> tag.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous">
</script>
<script src="jquery.jold.external-hrefs.js"></script>

2. Call the function on the <a> tag and done.

(function($){
  $('a').joldExternalHrefs();
  
})(jQuery);

3. The best practice to implement the jQuery jold.external-hrefs.js plugin.

<a href="https://www.google.com" rel="external">Google</a>
<a href="https://www.google.com" rel="nofollow">Google</a>
(function($){
  // Open all links with a 'rel="external"' attribute in a new window.
  $('a[rel="external"]').joldExternalHrefs();
})(jQuery);
// or
(function($){
  // Open all links with a 'rel="nofollow"' attribute in a new window.
  $('a[rel="nofollow"]').joldExternalHrefs();
})(jQuery);

This awesome jQuery plugin is developed by joldnl. For more Advanced Usages, please check the demo page or visit the official website.

  • Publication date: 30.10.2018
  • Source