Last active
September 25, 2017 15:26
-
-
Save ktopolski/7501beb00d0d3bf196b83093eefd2d83 to your computer and use it in GitHub Desktop.
Google Analytics Rails form tracker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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