Skip to content

Instantly share code, notes, and snippets.

Last active September 25, 2017 15:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Google Analytics Rails form tracker
class Tracker
constructor: ->
@success = false
@pageLeftTracked = false
trackFormChoices: ->
$formInputs = $('form section input')
$formInputs.each (index, input) =>
$(input).change =>
inputName = $(input).prop('name')
eventName = @_labelFromFieldName(inputName)
choice = @_inputValue(input)
@_track eventName, choice
trackSubmit: ->
$('form').on 'ajax:success', =>
@success = true
@_track 'successful form submit'
$('form').on 'ajax:error', =>
@success = false
failedAttributeName = $('.estimate-error:first').parent().find('input:visible:first').prop('name')
eventName = @_labelFromFieldName failedAttributeName
@_track 'failed form submit', eventName
trackExit: ->
$(window).on 'page:before-change', @_trackPageLeave.bind(@)
$(window).on 'beforeunload', @_trackPageLeave.bind(@)
$(window).on 'unload', @_trackPageLeave.bind(@)
_track: (eventName, choice = '')->
ga('send', 'event', 'BestAppsForMarketing Form', eventName, choice)
undefined # this prevents page from displaying a prompt to user upon leave
_trackPageLeave: ->
return if @pageLeftTracked
@pageLeftTracked = true
if @success
@_track 'Page Leave', 'Successful'
@_track 'Page Leave', 'Fail'
# "estimate[project_scope][]" => "project scope"
_labelFromFieldName: (fieldName) ->
snakeCaseLabel = fieldName.match(/\[([a-zA-Z_]*)\]/)[1]
snakeCaseLabel.replace '_', ' '
_inputValue: (input) ->
$input = $(input)
if $input.prop('type') == 'file'
$ ->
tracker = new Tracker()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment