jQuery Event Tracking Generator for Google Analytics

By /

July 2, 2013

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 is our Analytics Department Manager. He started building websites in the mid-90s, and has spent ten years in the agency world, focused on front and back-end development, SEO/SEM and web analytics. He also leads trainings in Google Analytics and Tag Manager around the country. Alex received his master's degree in Dublin, where he explored the Irish coast with a furry dog and lots of pints.

  • http://echoim.com Chris

    Hello,

    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!

  • http://www.lunametrics.com Alex Moore

    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.

  • http://roma.net.ua Roman Rybalchenko

    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
    },300);
    });
    });

    });

  • http://vreeman.com/ Simon Vreeman

    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.

  • http://www.lunametrics.com Alex Moore

    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.

  • http://roma.net.ua Roman Rybalchenko

    Thanks! Awesome.

  • Justine

    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?

  • http://www.lunametrics.com Alex Moore

    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

    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.

    Thanks

  • Pavel

    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

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

  • http://www.lunametrics.com Alex Moore

    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.

  • http://babegalleries.xxx John P.

    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

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

  • http://deltek.com Curtis

    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.

  • http://www.juoksufoorumi.fi/ Seppo

    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.

    • http://www.lunametrics.com Alex Moore

      Seppo,

      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!

  • http://www.pilda.cz/ Pilda

    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

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

  • http://CrescentInteractive.com John Ellis

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

    • http://www.lunametrics.com Alex Moore

      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!

  • http://kevingoldsmith.com Kevin

    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

    Hi,

    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?

    Thanks

  • http://www.aparthoteldelden.nl Jules

    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!

  • http://www.karelia.com/ Dan W.

    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() { …

  • http://www.nivault.com Carrelage Nivault

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

  • jestin

    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.

  • yisrael

    Hi Alex
    is there any way to do this if I am using Google Tag Manager to set the Google Analytics code (Universal)? I am not using a custom HTML tag rather the built in GA tag to fire the analytics code

  • http://Torpedo7/1-day Aaron

    Alex,

    Generator is awesome.
    I am using the following code to track users clicking an Large image which triggers a POP-UP zoomed image. In Safari this pop up loads, then disappears behind the current screen, any ideas?

    $(document).ready(function() {

    $(“.image_holder a”).each(function() {
    var href = $(this).attr(“href”);
    var target = $(this).attr(“target”);
    var text = $(this).text();
    var thisEvent = $(this).attr(“onclick”); // grab the original onclick event
    $(this).click(function(event) { // when someone clicks these links
    event.preventDefault(); // don’t open the link yet
    _gaq.push([“_trackPageview”, href]); // create a dynamic pageview
    setTimeout(function() { // now wait 300 milliseconds…
    eval(thisEvent); // … and continue with the onclick event
    window.open(href,(!target?”_self”:target)); // …and open the link as usual
    },300);
    });
    });

    });

  • Box

    How about this scenario: i have a small box with two options for booking. Book a table or Book a room. How to implement event tracking when somebody books a table and a room? The book button redirects to different external domains, DEPENDING on the choice (table or room). How do I know who booked a table and who booked a room?

Contact Us.

LunaMetrics

24 S. 18th Street, Suite 100,
Pittsburgh, PA 15203

Follow Us

1.877.220.LUNA

1.412.381.5500

getinfo@lunametrics.com

Questions?
We'll get back to you
in ONE business day.