How dangerous is e.preventDefault();, and can it be replaced by keydown/mousedown tracking?
Posted
by
yc
on Stack Overflow
See other posts from Stack Overflow
or by yc
Published on 2010-12-29T03:15:24Z
Indexed on
2011/01/03
15:55 UTC
Read the original article
Hit count: 160
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?
© Stack Overflow or respective owner