jQuery Error in Google Code

I have the following Google Code in my script:
<script>
   (function() {
    var eventAction, i;
 
    var checkSubmit = function() {
      i = window.dataLayer.length - 1;
      while (i > -1) {
        if (window.dataLayer[i]['event'] === 'gtm.formSubmit') {
          return true;
        }
        i--;
      }
    };
    
    var formSelector = 'mail_form'; // Modify this CSS selector to match your form. Default is first form on the page.
    var attribute = 'name';
    var history = [];
    window.addEventListener('beforeunload', function() {
      if (history.length && !checkSubmit()) {
        window.dataLayer.push({
          'event' : 'formAbandonment',
          'eventCategory' : 'Form Abandonment',
          'eventAction' : history.join(' > ')
        });
      }
    });
   
    document.querySelector(formSelector).addEventListener('change', function(e) {
      history.push(e['target'].getAttribute(attribute));
    });
  })();
</script>

Open in new window

On line 28 I get an error in Chrome:
Uncaught TypeError: Cannot read property 'addEventListener' of null

Also does line 15 need to be the name of the class for the form?  I am using the tutorial on this page:
http://www.simoahava.com/analytics/track-form-abandonment-with-google-tag-manager/#2
LVL 7
rgranlundAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ioannis ParaskevopoulosCommented:
Hi,

Your formSelector variable should be '#mail_form' if mail_form is an id or '.mail_form' if it is  a class.

Giannisx
0
hieloCommented:
You have:
>> var formSelector = 'mail_form';

So this:
>> document.querySelector(formSelector)

is equivalent to:
document.querySelector('mail_form')

On the article you posted, under the section "Track simple interaction" after the block of code it states:
In the beginning, you define a formSelector. This is a basic CSS selector that you use to target a single form, e.g. ‘#formId‘ or ‘.formClass‘.

In other words, you should actually be using:
var formSelector = '#mail_form';
with <form id="mail_form"...>...</form>

Since you did not included the '#', then document.querySelector(formSelector) is returning null and you can't attach an event listener on null.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rgranlundAuthor Commented:
I still get the error:
document.querySelector(...) is null

	<script>
    $( window ).load(function() {
		$(function(){
  $('#mail_form').blur(function( e ){
    var me = $(this), form = me.parents('form');
    ga.push(['_trackEvent', (me.attr('name') || me.attr('id')), (me.val().length > 0 ? 'filled' : 'empty'), $(this).attr('name')]);
  });
});
  

  (function() {
    var eventAction;
    var formSelector = '#mail_form'; // Modify this CSS selector to match your form. Default is first form on the page.
    var attribute = 'name';
    window.addEventListener('beforeunload', function() {
      if (eventAction) {
        window.dataLayer.push({
          'event' : 'formAbandonment',
          'eventCategory' : 'Form Abandonment',
          'eventAction' : eventAction
        });
      }
    });
   
    document.querySelector(formSelector).addEventListener('change', function(e) {
      eventAction = e['target'].getAttribute(attribute);
    });
  })();
  });

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.