iFrame Submit Button GA Event Tracker

[email protected]

by Ryan Brackett

HTML

Dynamically add options to JotForm<br/><br/>
<div class="form">
    <script type="text/javascript" src="https://form.jotform.com/jsform/53284842603961"></script>
</div>

<div class="locations">
	<ul>
		<li>Red</li>
		<li>Blue</li>
	</ul>
</div>

CSS

body {
    font-family: Arial;
    padding: 20px;
    line-height: 1.5em;
    font-size: 14px;
}

JavaScript

// Read the contents of the iframe.
   var iframe = $("iframe").contents();


   // Main function. Checks for errors. If none, event is sent to analytics.
   function fireEventga() {
       var errors = iframe.find(".form-button-error").length;
       // If errors do not exist
       if (!errors) {
           alert("Event pushed to analytics");
           // Send event to analytics
           ga('send', 'event', 'Category Here', 'OnMouseDown', 'Form Submit - Identifier here');
       }
       // If errors do exist
       else {
           alert("Please check the form for errors");
       }
   }


   // Submit button clicked. The delay waits for errors to render and then fires main function.
   $(function () {
       iframe.find(".form-submit-button").click(function () {
           setTimeout(fireEventga, 200);
       });
   });


// Location Bank Classes
var locBank = [];
$(".locations li").each(function() { locBank.push($.trim($(this).text().toLowerCase())) });
var locBank = locBank.join(',');
alert(locBank)


// Locations Option Classes
var locOptions = [];
iframe.find("label:contains('Favorite') + div").find(".form-checkbox-item label").each(function() { locOptions.push($.trim($(this).text().toLowerCase())) });
var locOptions = locOptions.join(',');

alert(locOptions)



var locToRemove = [];


$.each(locBank, function(indexA,valueA) {
    $.each(locOptions, function(indexB, valueB){
        if(valueA == valueB)
        {
            locBank[indexA]=null;
            locOptions[indexB]=null;
            return false; //break out of inner each loop                     
        }
    });
});

$.each(locBank.concat(locOptions),function(idx,val) {
    if(val!=null) locToRemove.push(val);
});

$.each(locToRemove, function( index, value ) {
  $("div").addClass(value)
});

alert(locToRemove)