How Dangerous Is E.preventdefault();, And Can It Be Replaced By Keydown/mousedown Tracking?
Solution 1:
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.
Solution 2:
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)
Solution 3:
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();
}
});
Solution 4:
e.preventDefault()
doesn't have to be right at the beginning of the function call. Why not just have an if
statement to verify if everything is working correctly, and only call e.preventDefault()
if it does. If any function in the chain doesn't return the expected result, set a submitted
variable to false
, and don't prevent the default.
This might be a little more difficult to handle when it comes to anything asynchronous (such as your setTimeout
, but there will be ways to make fairly sure, depending on what your code looks like. So you can check if methods exist with if (_gaq.push)
(for example). You can't make 100% sure without testing every single combination in every browser, but I reckon you can get a pretty satisfactory result with this.
Solution 5:
Another approach:
var pageTracker;
_gaq.push(function() {
pageTracker = _gat._getTrackerByName();
});
$('form').submit(function(e){
pageTracker._trackEvent('Form', 'Submit', $(this).attr('action'));
};
I would guess this way _trackEvent would be synchronous but I haven't tested it.
Post a Comment for "How Dangerous Is E.preventdefault();, And Can It Be Replaced By Keydown/mousedown Tracking?"