DollarChills
DollarChills

Reputation: 1086

Analytics and Tracking Downloads

I have the 'google-analytics-rails' gem which works great, but i'm also wanting to track downloads of pdf's. I have found this link which describes using an on click call, but i'm not sure how best to integrate with the rails link_to method.

<%= link_to 'Link Name', url_path(@url) %>

Upvotes: 2

Views: 450

Answers (2)

CrayonViolent
CrayonViolent

Reputation: 32517

When I do custom implementations for clients, I take the same approach as @Andre's answer, except I make it broader, to target all relevant links.

What the actual code looks like will depend on what your download links actually look like, and what you want to see in reports, but here is an example of targeting some download links and reporting on the file location (href attribute)

$(document).ready( function() {
  $('body').on('click','a',function(event) {
    /* download tracking */
      // add whatever download file extensions are relevant to you
      var exts = ['pdf','doc','xls','xlsx'];
      var p = new RegExp('\\.('+exts.join('|')+')$','i');
      var href = String(event.target.href)||'';
      if ( href.match(p) ) {
        _gaq.push(['_trackEvent', 'Link Clicks', 'Download', href])
      }    
  });
});

The great thing about this is that since this code targets all links, you can expand it to track other types of links as well. Some other link types you may want to track are clicks that:

  • lead to some other domain (exit link tracking)
  • lead to another site you own (cross domain tracking)
  • lead to social media sites (e.g. facebook, twitter)
  • invoke social media actions (e.g. facebook like/share)
  • links to promotions on your site (internal campaign tracking)
  • links that invoke a particular widget or interaction on your site (engagement tracking)

Upvotes: 1

andreofthecape
andreofthecape

Reputation: 1196

Ok, have not tested this but it should point you in the right direction... In rails you use unobtrusive javascript (unlike the inline javascript that is used in the link). So you add your js file (lets say my_ga.js) to the app\assets\javascripts directory. The application.js file will cause it to be automatically included. Inside the my_ga.js file you can use jquery to target the link. Something like: Your link: <%= link_to 'Link Name', url_path(@url), id: 'pdf1' %> Your my_ga.js file:

$(document).ready( function() { $('#pdf1').click(function() { ga('send', 'event', 'download', 'click', ‘Descriptive text here'); }); });

Upvotes: 1

Related Questions