Citizen SP
Citizen SP

Reputation: 1411

Javascript: link href target

I'm using the standard Google Analytics Javascript code to track the outbound links on my website:

  function recordOutboundLink(link, category, action) {
    _gat._getTrackerByName()._trackEvent(category, action);
    setTimeout('document.location = "' + link.href + '"', 100);
  }

Even when I add "target='_blank' to my links, all links are still opened in the same window/tab. I tried add 'document.location.target', but the script isn't working yet.

Upvotes: 0

Views: 5535

Answers (1)

mike
mike

Reputation: 7177

document.location = newURL will open the URL in the existing window. You can use window.open(newURL) to open the URL in a new window.

A couple of other things:

  1. document.location has been deprecated -- use location.href instead.
  2. You can simplify your code by not passing in the action, and getting from the link href instead.

Try the following

<a href='http://example.com' onclick="return recordOutboundLink(this, 'Outbound Link');">

function recordOutboundLink(link, category) {
  var url = link.href;
  _gat._getTrackerByName()._trackEvent(category, url);
  if (link.target == '_blank') 
    window.open(url);
  else 
    setTimeout(function() {location.href = url;}, 150);
  return false;
}

FYI: Why use setTimeout only for opening the URL in the existing window? Starting to open a new URL in the existing window can halt the analytics tracking pixel request before it's completed. If you're opening the URL in a new window, there's no need for a delay.

Upvotes: 3

Related Questions