How to add Google Analytics event logging to dynamic CMS page content
Wednesday 10 August 2011 at 21:46 I wanted to take to add Google Analytics events to links within content managed areas is to use jQuery to add the onclick events. For some of the links we can change the component code to add the onclick event, but for links created in rich text editors the only feasible way for us is to add them dynamically. As an example, the code we want to add
onclick="_gaq.push(['_trackEvent', 'File Download', 'Download', 'Document download: abc.pdf']);"
In order to achieve this, we can add an onLoad code block to add this event to the elements that need it. We will do this using jQuery selectors to match elements and to pull properties out of the elements to enhance the event submitted to GA. The first step is to make it log any PDF link clicks.
$("a[href*='.pdf']").live('click',function(){_gaq.push(['_trackEvent', 'File Download', 'Download', 'PDF download']);});
Once we have this working correctly we can move on to enhancing it by using the alt text or the body of the link to add to the message send to GA as this will make our analytics more useful if we can identify which document was clicked on. The advantage of doing it this way is that we don't need to train CMS authors to add these links, or even to modify the authoring environment to enable them to pick a goal for each hyperlink. We can control it at a developer level, which will reduce some of the flexibility of the analytics but with the benefit of centralised control and more reliable results. These things are just too technical to leave in the hands of the majority of authors purely because they are invisible. By automating the process of adding these events, it's clear that nothing will be missed.

Reader Comments