1

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.

Community
  • 1
  • 1
CDub
  • 13,146
  • 4
  • 51
  • 68
  • can you please provide the full version of the 'anchor's html element? this should work without problems – Hakan Fıstık Mar 11 '17 at 08:09
  • Please try setting the `target` using `prop` instead of `attr`. Attributes are ment as the *initial* value of the corresponding HTML element instance. – Zoltán Tamási Mar 11 '17 at 08:22

1 Answers1

2

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'
  });
});
Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93
  • Just tried this - it did not work. Still simply opened the same window in Chrome and Safari. – CDub Mar 11 '17 at 08:29
  • Then please try to create a jsfiddle which reproduces your issue, so we can have a look at it. – Zoltán Tamási Mar 11 '17 at 08:31
  • Also note that there might be cases when the browsers override this setting in result of some local settings or circumstances. So to test it, try to create two static links (without `jQuery`) so you can see if it works at all. – Zoltán Tamási Mar 11 '17 at 08:33
  • https://jsfiddle.net/b8s4bLhm/1/ - and of course, the jsfiddle works. I'm wondering if it's Rails preventing this somehow? – CDub Mar 11 '17 at 08:36
  • I assume you mean create a "hard-coded" `target="_blank"` link in my app. When I do this, yes, it works as expected. – CDub Mar 11 '17 at 08:39
  • Yes I ment that. It sounds really interesting – Zoltán Tamási Mar 11 '17 at 09:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/137816/discussion-between-zoltan-tamasi-and-cdub). – Zoltán Tamási Mar 11 '17 at 09:03