Upcoming LunaMetrics Events
San Francisco, Apr 28-30 Los Angeles, May 12-16 New York City, May 19-23 Chicago, Jun 16-18

jQuery Event Tracking Generator for Google Analytics

jquery-coffeeEverybody these days knows about the awesome power of jQuery. Among its multitude of uses, it allows you to target elements on an HTML page in bulk. Let's say you have a page with a hundred different links on it. You might want to target twenty of the links inside a particular list element only, and apply some special click event to just those elements. jQuery is the tool for you, as it can save you from having to write twenty different onclick attributes on each a tag.

jQuery is also an invaluable tool for Google Analytics, as it allows us to reliably target clicks on links of a certain type and send some special event to Google Analytics. For example, you might want to fire off a virtual pageview every time someone clicks on a link with the .pdf extension. Or you might want to fire a custom event on every click of an external link. jQuery makes this task easy, so long as you know how to use it.

Enter the Google Analytics jQuery Tracking Generator. This wizard will auto-generate custom jQuery code to help you fire off custom events, virtual pageviews, or custom variables to Google Analytics, on the links or forms of your choosing!

Follow the steps below and copy the code into your web project. When prompted, you may also click on the big orange button to add multiple events, pageviews and variables, across new links and forms!

  Begin to Fill Out the Steps
Step 1
Step 2
Alex Moore

About Alex Moore

Alex Moore is our Analytics Department Lead. For over a decade he has built websites from the ground up, placing web analytics at the root of digital marketing strategy. Alex has spent eight years in the consultancy world and in client-facing roles, working on search engine marketing, development, web analytics and custom reporting. He also heads LunaMetrics training seminars across the country. The next seminar Alex will be leading will be a Google Analytics training in Houston. An avid independent backpacker and traveler, Alex also has his Masters in Religious Dialogue from Ireland, where he discovered that most sectarian conflict can be settled over a pint of plain.


30 Responses to “jQuery Event Tracking Generator for Google Analytics”

Chris says:


How would this be implemented in Google Tag Manager custom HTML tag? I’d love to be able to do the above without having to adjust the site’s code. Thanks!

Alex Moore Alex Moore says:

Hi Chris,

If you want to implement the code above using Google Tag Manager, you’ll need to make sure you’re including both jQuery and your Google Analytics tracking code on the page directly. If you already are, proceed to paragraph #3.

If not, you’ll need to load those libraries in their own tags inside GTM. Google Analytics has a special type of tag reserved for its implementation, along with several options you’ll need to fill out, and the jQuery library can be loaded inside a new tag with the tag type called “Custom HTML”. Just include the <script> tag and closing </script> tag which call jQuery, as generated by my tool above when clicking “Include jQuery library script tag”.

Then just copy and paste the rest of the code, the part inside-and-including the $(document).ready wrapper, into a new Custom HTML tag, or even the same Custom HTML tag as jQuery. You’ll need to wrap this new code in <script> tags to set it apart from regular HTML. Also, make sure that all of these tags have a macro defined that displays the tag on all pages! Save, create a new container, and publish!

Really it should be as simple as that, but please do let me know if you get it to work! Thanks.

I don’t see _trackEvent function in your code. Is it correct?

$(document).ready(function() {

$("a.class").each(function() {
var href = $(this).attr("href");
var target = $(this).attr("target");
var text = $(this).text();
$(this).click(function(event) { // when someone clicks these links
event.preventDefault(); // don't open the link yet
setTimeout(function() { // now wait 300 milliseconds...
window.open(href,(!target?"_self":target)); // ...and open the link as usual


This is really handy Alex! An analytics.js version would be cool too. However it is pretty easy to change it myself to universal analytics.

Alex Moore Alex Moore says:

Roman, keep filling out the steps. You want to click on “I want to fire a custom event” in Step 4 and then fill out the next options. You will then see the code for _trackEvent.

Justine says:

I’ve generated the coding, however I”m not sure where to implement it, since it is jquery. Do I just copy paste it to my site?

Alex Moore Alex Moore says:

Justine, just copy and paste this code into the of your webpage. If you are not already including the jQuery library on your site, you should be sure to check the boxes above for “Include jQuery library script tag” and “Load jQuery from Google”.

Alex says:

Hi Alex,

Thank you for this blog post. Unfortunately, I think that your code might have a bug, look at this line:
_gaq.push(["_trackEvent", "Links", "Clicked", "", href, false]); // create a custom event

You are “sending” href variable as one of the parameters of _trackEvent method. href is of string type, however, GA requires the 4th parameter to be an integer (https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide). It will not work with a string one. I think you might want tot fix it or correct me if I’m wrong.


Pavel says:

There is mistake in:
_gaq.push(["_trackEvent", "Links", "Clicked", "", href, false]);

According https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide#Values
GA expects in 5-th value of array (4-th parameter of _trackEvent) value of type integer. When you put string value (href) GA doesn’t process this event properly

Pavel says:

Sorry for the duplicate, Alex beat me to it :)

Alex Moore Alex Moore says:

Thanks so much, Alex and Pavel! You’re right: I realized I reversed the 4th and 5th parameters. I’ve updated the code now, so trackEvent now has the correct syntax.

John P. says:

Be forewarned! I’m not knowledgeable about coding and new to WordPress, JQuery etc. I have figured many things out already but getting GA to work with this WordPress theme has me stooped.

The challenge I’m facing is getting URL click calls from a WordPress Jquery/Ajax Image Gallery Page which have embedded relative URL paths to register as Events or Pageviews in GA. The outbound clicks from anywhere on the site register ok using an SEO GA plugin. However, the clicks on the Gallery images themselves which have embedded relative URLs for each won’t register with the plugin or by using this script method.

I use a WordPress plug-in called PrettyLinks which converts the relative url paths to the absolute URL external destination URL and that works fine. So my question is how to get event/pageview tracking working for these relative URL clicks such as; /Goto/SomeUrl. If the Pretty Links Plugin can recognize these clicks, surely Jquery could I would think!

Also, I tried to hunt down where the Ajax call is being actually made from in the theme’s files but can’t seem to locate it. Finding this call would allow trying other methods of implementation such as adding the JS Onclick events handler to the Ajax call for the URL string for the gallery images.

Lastly, where exactly and how should the GA code be inserted in this script when it has it’s own script bracketed; i.e. .GA Code.. I already had the code working on the top of the header page but when I put it in the script area where it is called for in this scripts comments it broke. Any help on these issues would be greatly appreciated!

Christian says:

I tried your code to track my links, but now the tracked links do not work, nothing happens. Can you helP?

Curtis says:

I am having the same issue. When I use your code for form submits, some of the forms function as expected but some of them no longer submit, and some of them submit without sending the event to GA. Do you have an idea why this might be? Anything to point me in the right direction would be great, thanks.

Seppo says:

Thanks! Finally i found working event tracker.

I would like to track all links going outside from my site, how i could track those? Now i managed to track only those link where i added class.

Pilda says:

Hi, nice application, thank you. However I noticed it generates for elements with ID a code containing EACH and it pointless because there cannot be two or more elements with the same id. The code is also longer because of it.

Laura says:

This is great, how would it work with Universal Analytics?

John Ellis says:

Can this code go anywhere on the site, like a common footer? Or does it have to go within the form?

Alex Moore Alex Moore says:

Hi John,

Yes, the code can go anywhere, like in a footer, as long as it’s bracketed with script tags. The beauty of jQuery is it doesn’t need to go in the form!

Alex Moore Alex Moore says:


I’m glad it’s helpful for you! In order to track all external links from your site, under the “Link Conditions (optional)” section, include “Only if the URL contains ‘http’”. That way only links beginning with http (which are external) will be targeted!

Kevin says:

I fixed the code for Universal Analytics by changing it to:
ga(‘send’, ‘event’, ‘link’, ‘click’, ‘href’, {‘link’: href});

however, I’m getting popup blocker warnings in chrome and the links aren’t being followed due to the window.open call since I target another tab. Is there any way around this without changing the target?

olaf says:


Thanks for the useful article. I have a couple of questions if thats ok. Say, I wanted to track affiliate links. Each of these has /go/ in the url, but I have lots of them on different pages, or I want to track a PDF download, again on different pages, how do I do that?


Jules says:

Very helpfull piece of code. However I have conflict with “PrettyPhoto” and AddThis scripts!
(and a commercial hotel-booking engine)
My web-builder keeps fixing one conflict after the other!

Dan W. says:

Nice generator. How about an option to match with the CSS selector, e.g. generating something like this:

$(‘a[href^="https://itunes.apple.com"]‘).each(function() { …

Nice Generator, but can you adapt it to use the new Universal Analytic instead of the old google analytic ?

jestin says:

Hey I am trying to track users based on the behavior of their scroll events. As in which part of the page they are reading.Can it be done?
I’m new to jquery.

I wanted too thank you for this wonderful
read!! I definitely enjoyed every little bit of it. I have you book marked
to check out new things you post…

This paragraph is actually a fastidious one it assists new web
users, who are wishing in favor of blogging.

Hi, I do believe this is an excellent website. I
stumbledupon it ;) I will come back yet again since i have book marked it.
Money and freedom is the best way to change, may you be rich and continue to guide other people.

Leave a Reply