uaj__q
Last Updated: April 14, 2016
·
502
· ProGM
Avatar progm

Google analytics event tracking with pjax and jquery

Some random suggestions to setup google analytics in your projects. My current stack is Rails + pjax + coffeescript + jquery, but this suggestions are valid for everyone!

Tracking pageview events with pjax

Many people forget about google analytics when using pjax.
In fact, when an user navigates pages using pjax, it doesn't trigger pageview events.
You can solve this very easily:

$(document).on 'pjax:success', (e) ->
  if (window.ga)
    window.ga('send', 'pageview')

Track logged user informations

Google analytics has a great feature to track logged user informations. Instead of general demographic informations, you can pass an "userId" to google analytics at instantiation. For instance, I pass my current_user username from devise:

... your google analytics instantiation here...
ga('create', 'UA-XXXXX-Y', 'auto');
<% if current_user %>
ga('set', 'userId', '<%= current_user.username %>');
<% end %>

Track user actions on links and forms:

$(document).on 'ready', ->
  this.on 'click', 'a[data-analytics-click]', (e)->
    if (window.ga)
      window.ga('send', 'event', $(this).attr('data-analytics-click'), 'click', $(this).attr('href'))

  this.on 'submit', 'form[data-analytics-submit]', (e)->
    if (window.ga)
      window.ga('send', 'event', $(this).attr('data-analytics-submit'), 'submit')

Example usage with links:

<%= link_to "DOWNLOAD NOW!", my_file_download_link, target: '_blank', data: { analytics_click: 'DownloadFile' } %>

Or with forms:

<%= form_for :something, data: { remote: true, analytics_click: 'SubmitForm' } do |f| %>
...

Do you have more google analytics tricks?

Say Thanks
Respond