Search code examples
javascriptclasshyperlinkrelnofollow

How do I make external links open in new window automatically with JS (with exception rule)?


For my question I was not able to find a solution so far. What I want is a js script that will convert all external links on my site (page), so that they open in a new window (add target=_blank to the a tag).

For this I have found a simple script that does this and it works like a charm (credits: gist.github.com/wpscholar). However, I have no control on the output at all. And I think it would make sense to have a little control on which links are changed and which not. Here is the basic script:

/** Open all external links in a new window */
jQuery(document).ready(function($) {
$('a')
    .filter('[href^="http"], [href^="//"]')
    .not('[href*="' + window.location.host + '"]')
    .attr('rel', 'nofollow noopener noreferrer')
    .attr('target', '_blank');
});

Can anyone give me an example script on how to add an exception, for when the a tag has class=trusted? Where only the target attribute is set and the rel attribute is left empty.

<a href="https://somedomain.com/" class="trusted">anchor</a>

Becomes:

<a href="https://somedomain.com/" class="trusted" target="_blank">anchor</a>

When class=trusted is not found, it should just execute the example script.

Many thanks and happy new year!


Solution

  • I think you should add your class "trusted" to your jQuery selector with not() (as you done with the href) :

    /** Open all external links in a new window */
    jQuery(document).ready(function($) {
    $('a')
        .filter('[href^="http"], [href^="//"]')
        .not('[href*="' + window.location.host + '"]')
        .attr('rel', 'nofollow noopener noreferrer')
        .not('.trusted')
        .attr('target', '_blank');
    });