Shoora
2/12/2014 - 8:50 AM

jQuery form drop out tracking for Google Universal Analytics

jQuery form drop out tracking for Google Universal Analytics

var ft_startDate = 0,
    ft_startTime = 0,
    ft_pageTitle = document.title,
    ft_duration = false;

$(':input').focus(function() {
    /* Make a record of when the user focused on the input */
    ft_startDate = new Date();
    ft_startTime = ft_startDate.getTime();
});

$(':input').blur(function() {
    /* Use the start time and current time to calculate duration spent on the input */
    var ft_endDate = new Date(),
        ft_endTime = ft_endDate.getTime();

    /* Occasionally ft_startTime doesn't seem to get set */
    if(ft_startTime && ft_startTime > 0) {
        ft_duration = Math.round((ft_endTime - ft_startTime)/1000);
    } else {
        ft_duration = false;
    }

    /* Only record the event if the input has been filled out and not left blank */
    if($(this).val().length > 0) {
        /**
         * Here we follow the first two GA args with 4 custom variables.
         * 
         * @string {Page Title}
         * @string {Event Category}
         * @string {Input Name}
         * @string {Duration}
         */
        ga('send', 'event', 'Form: ' + ft_pageTitle, 'Field Filled', $(this).attr('name'), ft_duration);
    } 
});


/* Repeat with check boxes and radios */
$( "input[type=checkbox], [type=radio]" ).click(function() {
    if ($(this).attr("checked") == "checked") {
        ga('send', 'event', 'Form: ' + ft_pageTitle, 'Checked Checkbox', $(this).attr('name') + ': ' + $(this).attr('value'));
    } else {
        ga('send', 'event', 'Form: ' + ft_pageTitle, 'Unchecked Checkbox', $(this).attr('name') + ': ' + $(this).attr('value'));
    }
});