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

File Size: 33.8 KB
Views Total: 1175
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
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="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/local/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);

4. The plugin will ignore href links with the target="_self" attribute. 

<a href="https://www.cssscript.com" target="_self">CSSSCRIPT</a>

5. The plugin will ignore href links with the target="_self" attribute. 

<a href="https://www.cssscript.com" target="_self">CSSSCRIPT</a>

6. Determine whether or not to ignore www from the host name. Default: false.

$('a').joldExternalHrefs({
  'ignore_www': true
});

7. Determine whether or not to ignore www from the host name. Default: false.

$('a').joldExternalHrefs({
  'ignore_www': true
});

8. Determine whether or not to set target & rel attributes. Default: false.

$('a').joldExternalHrefs({
  'set_target': true,
  'set_rel': true
});

Changelog:

v1.2.1 (2019-11-29)

  • Update the package

v1.2.0 (2019-11-28)

  • Add settings: set_target, set_rel and ignore_www
  • Add attributes rel and target to if settings allow it
  • Ignore all links with target="_self" attribute

v1.1.0 (2019-01-15)

  • Check and skip all non http and https links from opening in new tabs

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