In one of the projects, it was required to track the number of times an image (which linked to another page) was clicked using Google Analytics. We found a very informative article here. It talks about tracking external links and file downloads. This wasn’t exactly our purpose, but the javascript downloaded from there acted as a very good starting point.
What we did was to add a code block like this after line no. 13 of the javascript code from the link given above.
var imgs = document.getElementsByTagName("img"); for(var l=0; l <imgs.length; l++) { try { var path = imgs[l].getAttribute('src'); var isDoc = path.match(/\.(?:jpg|png|gif|svg)($|\&|\?)/); startListening(imgs[l],"click", trackImageClicks); } catch(e){ continue; } }
And a method before the Analytics script provided by Google for the site
function trackImageClicks(evnt) { var e = (evnt.srcElement) ? evnt.srcElement : this; var lnk = (e.getAttribute("src").charAt(0) == "/") ? e.getAttribute("src") : "/" + e.getAttribute("src"); if (typeof(pageTracker) == "object") pageTracker._trackPageview(lnk); while (e.tagName != "A") { e = e.parentNode; } lnk = (e.pathname.charAt(0) == "/") ? e.pathname : "/" + e.pathname; if (e.search && e.pathname.indexOf(e.search) == -1) lnk += e.search; if (e.hostname != location.host) lnk = e.hostname + lnk; if (typeof(pageTracker) == "object") pageTracker._trackPageview(lnk); }
Now, the clicks on each image were getting tracked.
