jQuery adding target _blank not opening in new tab

In reference to this SO question, I'm trying to make my site work such that any external link opens in a new tab.

The jQuery for each of the answers on the aforementioned question works (meaning I see target="_blank" being added to external links when I use Chrome or Safari's inspector, but clicking on the links themselves do not open in a new tab or new window.

Have modern browsers changed such that this functionality no longer works? Or am I missing something else?

Update: Per @hakam-fostok's request, here is the relevant code:

JS:

$(function() {
  $('a').attr('target', function() {
    if(this.host == location.host) return '_self'
    else return '_blank'
  });
});

Link (as seen in Chrome inspector):

<a href="http://espn.com" target="_blank">ESPN</a>

Update 2: I'm not sure this matters, but the app is Rails 4.2.7.1, running jQuery 2.2.4.

Answers 1

  • Usually if you want to modify run-time properties of an existing HTML element, you have to use the prop function instead of attr. See the documentation here.

    The difference in simple words is that prop sets the corresponding property of the HTML element, whereas attr sets only the attribute value. Attribute values are ment to be initial values of run-time properties.

    $(function() {
      $('a').prop('target', function() {
        if(this.host == location.host) return '_self'
        else return '_blank'
      });
    });
    

Related Articles