Skip to content

Instantly share code, notes, and snippets.

@ktopolski
Last active September 25, 2017 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktopolski/7501beb00d0d3bf196b83093eefd2d83 to your computer and use it in GitHub Desktop.
Save ktopolski/7501beb00d0d3bf196b83093eefd2d83 to your computer and use it in GitHub Desktop.
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'
else
@_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'
input.files[0].name
else
$input.val()
$ ->
tracker = new Tracker()
tracker.trackFormChoices()
tracker.trackSubmit()
tracker.trackExit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment