×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Mikael Malmgren
Added: Aug 17, 2018 1:52 PM
Modified: Aug 20, 2018 12:13 PM
Views: 3323
Tags: no tags
  1. <script>
  2.   (function() {
  3.     var eventAction;
  4.     var formSelector = 'form'; // Modify this CSS selector to match your form. Default is first form on the page.
  5.     var attribute = 'name';
  6.     window.addEventListener('beforeunload', function() {
  7.       if (eventAction) {
  8.      
  9.         window.dataLayer.push({
  10.           'event' : 'formAbandonment',
  11.           'eventCategory' : 'Form Abandonment',
  12.           'eventAction' : eventAction
  13.         });
  14.       }
  15.     });
  16.  
  17.     document.querySelector(formSelector).addEventListener('change', function(e) {
  18.       eventAction = e['target'].getAttribute(attribute);
  19.     });
  20.   })();
  21. </script>