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

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.


I use a different approach, and generate the event tracking script in the page resulting from the submit. You could call it deferred event tracking.

I wrote a blog post with all details about my approach to event tracking in backend actions. It is biased towards Java-Struts, but you can get the general idea.

The rationale is that I want to track some things after they happened at the server side. In this kind of case, after the form was submitted and processed by the server.

What I do (very summarized):

  • Store events in an object tied to the session (a list/queue)
  • Flush these events upon the next page render (generate the javascript and empty the queue)

If you must have forms always work but tracking can be sacrificed if absolutely necessary, you could just try/catch it.

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