Skip to content

Instantly share code, notes, and snippets.

@bcj19
Created April 13, 2012 12:01
Show Gist options
  • Save bcj19/2376387 to your computer and use it in GitHub Desktop.
Save bcj19/2376387 to your computer and use it in GitHub Desktop.
Dynamic form analysis plug-in for use with Google Analytics implementations.
if("undefined"==typeof($tG)){$tG={};}
/*
$tG.formAnalysis()
- pv_formId = "id" property for html form element being monitored
- pv_event = status of form event: abandon, success, error
*/
$tG.formAnalysis = function(pv_formId,pv_event) {
var subDetail="";
var formId=pv_formId;
pv_event=pv_event.toLowerCase();
switch(pv_event) { //set success events based on form status
case "start":
subDetail="";
jQuery("#"+formId+" :input").live("change",function(e){
$tG.formLastFieldChanged=this.id;
});
if(jQuery("#"+formId).attr("ignoreFormAbandon")!="true") { //capture form abandon, where applicable
jQuery(window).unload(function() { //capture form abandon
if(!$tG.isNotAbandon) { $tG.formAnalysis(formId,'abandon',true); }
});
}
break;
case "abandon":
($tG.formLastFieldChanged) ? subDetail=$tG.formLastFieldChanged : subDetail="No Data Entered";
break;
case "complete":
$tG.isNotAbandon=true; //prevent abandon call after form complete
subDetail="";
break;
case "error":
($tG.formErrorMessage) ? subDetail=$tG.formErrorMessage : subDetail="";
break;
default: subDetail="";break;
}
if(subDetail) {
//category,action,label,value
_gaq.push(['_trackEvent',formId,$tG.upperCase('form '+pv_event),subDetail]);
} else {
_gaq.push(['_trackEvent',formId,$tG.upperCase('form '+pv_event)]);
}
}
/*
$tG.upperCase() - converts first letter of each word to upper case
- pv_string = string to convert
*/
$tG.upperCase = function(pv_string) {
pv_string = pv_string.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
return(pv_string);
}
//Dyanmically apply form analysis logic - REQUIRES JQUERY//
jQuery(document).ready(function() {
if(jQuery("form[formAnalysis='true']")) {
jQuery("form[formAnalysis='true']").each(function() {
$tG.formAnalysis(this.id,"start");
})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment