Automatically Add Google Analytics Event Tracking With jQuery

Automatically add basic Google Analytics event tracking using jQuery. I wrote it for use on this site, but the script can be used as is or modified to suite your needs.

You can either:

Add the code to an existing theme JavaScript file that is called on every page (or the pages you want to track events)

Add the code to the footer of the every page before the closing body tag () (or the pages you want to track events)

Download the script and include it on every page (..and again – or the pages you want to track events)

That’s it!

Then clicks will be automatically trigger a Google Analytics event on:

Other Outbound Links – Any other link that leaves your domain, but is not caught by the social media or affiliate match.

Outbound Affiliate Links – set as any link within your domain that includes “/go/”. You can alter to your liking by adjusting the match in the affilateLink variable. [code type=”js”]var affiliateLink = new RegExp(‘/go/+’);[/code]

Outbound Social Media Links – set as any outbound link that includes “Facebook, Twitter, Google+, Linkedin and Twitter”. You can change or adding or removing the names in the socialMedia variable. Make sure you seperate the values you want to match with a pipe “|” sign, and add them before the plus “+”. Case matters. [code type=”js”]var socialMedia = new RegExp(‘plus|linkedin|pinterest|facebook|twitter+’);[/code]

PDF Download Links – Any link that end in .pdf.ZIP Download Links – Any link that ends in .zipAnchor Text Links A link within your domain that includes a “#” sign, or a relative anchor link.

Any thoughts, feedback, or fixes would be appreciated.

Disclaimer: No guarantee! but it does work, I actively use both variations on sites