views:

36

answers:

1

I am working on this site: http://www.vomero.co.uk/Torquay.aspx and would like to track views of the images (which open in a Fancybox gallery).

I know I could add an onClick event to each image, but since the gallery allows the user to view all the images using Next/Prev icons it is unlikely users will actually click each photo.

Any ideas?

Thanks, Matt

+1  A: 

You want the Google Analytics Event Tracking API.

This allows you to insert events into the JavaScript code of your web page that are registered in Google Analytics. Something like this:

<a href="#" onClick="_gaq.push(['_trackEvent', 'Images', 'View', 'Specific Image Name']);">Play</a>

or more realistically, something like this:

function openLightbox(id) {
  // your code to open the lightbox here
  _gaq.push(['_trackEvent', 'Images', 'View', 'Specific Image Name']);
}
<a href="#" onClick="openLightbox(7);">Play</a>

A little bit of Firebug spelunking reveals that the Fancybox left and right arrows are anchor tags like so:

<a id="fancybox-right">
  <span id="fancybox-right-ico" class="fancy-ico"></span>
</a>

So you can hook the click event like so:

$("#fancybox-right").click(function(){ alert("hi"); });

jQuery adds this click handler to a collection of click handlers, which will all fire when the button is clicked. Therefore the original behavior of the button will be preserved.

In this case, it would be more useful to climb around to the "#fancybox-inner" sibling and retrieve the image url.

$("#fancybox-right").click(function() {
  alert( $("#fancybox-inner > img").attr("src") );
});

Or, to hit the Google Analytics Event API

$("#fancybox-right").click(function() {
  var image_url = $("#fancybox-inner > img").attr("src");
  _gaq.push(['_trackEvent', 'Images', 'Click Right', image_url]);
});
$("#fancybox-left").click(function() {
  var image_url = $("#fancybox-inner > img").attr("src");
  _gaq.push(['_trackEvent', 'Images', 'Click Left', image_url]);
});
marshally
The code is a little messy, but it's a really valuable piece of information
alcuadrado
Thanks Marshally - I knew about the ability to add on click events, but it is likely that a user will click just one photo and then use the the next/prev navigation within Fancybox to see the other images (therefore any events I attach to the other links won't get fired).
Matt Bunce
I think what I am looking for is some way to hook into Fancybox itself, so it will run _gaq.push as the user views different images within the lightbox.
Matt Bunce