views:

55

answers:

2

Hi!

I'm using a form provided to me by PayPal in order to sell something on my website. Before the user hit "checkout" via the paypal form button, though, I want to track an event in google analytics. i have found this article via google analytics http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html that explains how to track the custom event, but i don't know how to add it before the form is submitted such that the form submission is also not interrupted.

i imagine it's some basic javascript?

thanks!

+2  A: 

You can either attach to button's click event or form's submit event. The latter is better, because submits may happen on hitting the ENTER key in a textbox as well. In which case a button click would not detect such a submit.

So button click:

$("buttonID").click(function(){...});

or form submit:

$("formID").submit(function(){...});

In your function you should do what's required by the analytics and submission will auto-continue afterwards (as long as there're no errors that would stop javascript execution).

Robert Koritnik
Great - anyone know how to delay the form submission for a second, too, so the GAnalytics have time to post?
Zachary Burt
A: 

You can add this to your form tag

<form onsubmit="return do_something()" >

Then write the *do_something* function and make it always return TRUE (as anything else will stop the form from submitting). You could also bind submit event to your form from the javascript using:

element.submit = do_something (note the fact that we're using a callback here
                               not the function itself)
lemiant
This is not the prefered way of attaching to DOM events, since only one event can be attached to an element this way. What if later on in his code someone else writes: `element.submit = do_something_else();`?
Robert Koritnik
Without Jquery, what is the preferred method?
lemiant