Skip to content

Instantly share code, notes, and snippets.

@ktopolski ktopolski/tracker.coffee

Last active Sep 25, 2017
Embed
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'
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
You can’t perform that action at this time.