mysociety / caps

A simple, open database of local government climate action plan documents and emissions data.
https://cape.mysociety.org
Other
8 stars 2 forks source link

Track clicks on section page infographic / social graphic download buttons #688

Open zarino opened 2 weeks ago

zarino commented 2 weeks ago

We’d like some indication of whether people are using the infographics and social graphics, in the gallery on section pages.

zarino commented 1 week ago

@lucascumsille I’ve just realised we don’t currently track any custom events with Google Analytics in the scorecards site, and the way we do it in the caps site makes heavy use of jQuery (which we don’t use in scorecards) so this ticket won’t be quite as straightforward as I thought.

You’ll probably want to add something like our existing trackEvent function to scoring/…/main.js, just without all the jQuery-specific stuff. Something like this:

var trackEvent = function(eventName, params, callback){
  params = params || {};
  callback = callback || function(){};
  params['event_callback'] = callback;
  setTimeout(callback, 2000);
  gtag('event', eventName, params);
};

(We wrap the gtag('event') call like this to gracefully handle the situation where a user has blocked the Google Analytics JavaScript, or some other network error happens – in situations like that, the user will only have to wait a maximum of 2 seconds before the callback fires anyway.)

Then you can add some click handlers to the download buttons however you like (probably using addEventListener inside a forEachElement loop, which we use elsewhere in scoring/…/main.js), prevent the default page navigation, call your new trackEvent function, and do the page navigation in the callback eg:

forEachElement('.js-social-graphic-download', function(el){
  el.addEventListener('click', function(e){
    e.preventDefault();
    var eventName = "…" // TODO!
    var params = {} // TODO!
    trackEvent(eventName, params, function(){
      window.location.href = e.target.href;
    });
  });
});

You’ll need to work out what data to put into the eventName and params variables. Maybe we’ll want to track not just that a download has taken place, but which section it’s on, and which aspect ratio of image was downloaded (square, rectangular, or infographic PDF)…