0

I have the following script added to my footer that is automatically adding target="_blank" to every external link:

<script type="text/javascript">
    function linkopener(a) {
    var b = a ? "_blank" : "_self";
    var c = document.links;
    for (var i = 0; i < c.length; i++) {
        if (c[i].href.search("www.mydomain.tld") == -1) {
            c[i].addEventListener("click", function () {
                    this.target = b;
            });
         }
    }
};
$(document).ready(function(){
    linkopener(true);
});
</script>

Now I would like to extend this to a small indicator at the end of every link so that a user is aware that it is an external link and for that I found this solution: https://stackoverflow.com/a/52058198 but I cannot make it work. How to integrate this into my working script?

Peleke
  • 891
  • 2
  • 10
  • 23
  • As the solution you linked to has several CSS based solutions, and the accepted answer does the very same, I closed this as a duplicate. – Asons Apr 28 '19 at 19:17

1 Answers1

1

I hope this code will help you

function linkopener(a) {
    var b = a ? "_blank" : "_self";
    var c = document.links;
    for (var i = 0; i < c.length; i++) {
        if (c[i].href.search("www.mydomain.tld") == -1) {
            /*
            c[i].addEventListener("click", function () {
                    this.target = b;
            });
            */
            c[i].target = b;
            c[i].className += ' external-link' 
         }
    }
};
$(document).ready(function(){
    linkopener(true);
});
a.external-link {
  position: relative;
  padding-right: 20px;
}
a.external-link:after {
  content: '\2197';
  position: absolute;
  right: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://www.google.com">Google</a>
<a href="https://www.facebook.com">Facebook</a>
<a href="https://www.stackoverflow.com">StackOverflow</a>
<a href="https://www.medium.com">Medium</a>
<a href="www.mydomain.tld">My domain</a>
Niraj Kaushal
  • 1,452
  • 2
  • 13
  • 20