Search code examples
javascriptjquerygoogle-analyticsanalyticsjquery-events

How dangerous is e.preventDefault();, and can it be replaced by keydown/mousedown tracking?


I'm working on a tracking script for a fairly sophisticated CRM for tracking form actions in Google Analytics. I'm trying to balance the desire to track form actions accurately with the need to never prevent a form from not working.

Now, I know that doing something like this doesn't work.

$('form').submit(function(){
 _gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
});

The DOM unloads before this has a chance to process.

So, a lot of sample code recommends something like this:

$('form').submit(function(e){
e.preventDefault();
var form = this; 
 _gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
//...do some other tracking stuff...
setTimeout(function(){
form.submit();
}, 400);
});

This is reliable in most cases, but it makes me nervous. What if something happens between e.preventDefault();and when I get around to triggering the DOM based submit? I've totally broken the form.

I've been poking around some other analytics implementations, and I've noticed something like this:

$('form').mousedown(function(){
 _gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
});
$('form').keydown(function(e){
    if(e.which===13) //if the keydown is the enter key
    _gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
});

Basically, instead of interrupting the form submit, preempting it by assuming that if someone is mousing down or keying down on Enter, than that form is submitted. Obviously, this will result in a certain amount of false positives, but it completely eliminates use of e.preventDefault();, which in my mind eliminates the risk that I might ever prevent a form from successfully submitting.

So, my question:

  • Is it possible to take the standard form tracking snippet and prevent it from ever fully preventing the form from submitting?
  • Is the mousedown/keydown alternative viable?
  • Are there any submission cases it may miss? Specifically, are there other ways to end up submitting besides the mouse and the keyboard enter? And will the browser always have time to process javascript before beginning to unload the page?

Solution

  • Them fellers over at that there Googleplex are awful bright and they figgered some day somethin' like this was bound to happen and now, sure enough, it has. Why don't you give this a good try:

    $('form').submit(function(e){
      e.preventDefault();
      var form = this; 
      _gaq.push(['_trackEvent', 'Form', 'Submit', $(this).attr('action')]);
      //...do some other tracking stuff...
      _gaq.push(function(){
         form.submit();
        });
      });
    

    That _gaq.push thigamajigger executes its elements sequentially, so you should be jest fine.

    And no, I don't know why I suddenly started talking like this.