Hack 55. Measuring Clicks the Old-Fashioned Way
If your particular web measurement application doesn't provide you the ability to measure which links your visitors are clicking, use this simple JavaScript hack to track them yourself. Before browser overlays, many vendors used JavaScript to track clicks on pages. Since the script is not very complicated and is used in other contexts in this book [Hack #13], it is also worth presenting as a standalone hack. 4.3.1. The CodeTo track clicks the old-fashioned way, you simply hijack JavaScript's onClick event handler, instructing it to fire off a message to a custom variable [Hack #31] in your measurement application right before the click is processed. The JavaScript for this is pretty straightforward; simply include this JavaScript in any page you want to track clicks on. <script language="JavaScript"> ' Use random numbers to ensure that the link doesn't get caught in ' the browser cache ' rnum = Math.random() * 1000000; rnum = Math.round(rnum); d=document.location; r=document.referrer; i.onload = SetClickTracking; ' ' After the click is processed, pass the click along as usual ' function ClickTrackRedirect(url){ window.location.href=url; } ' ' When a link is clicked, send a new image request to the measurement application ' NOTE: Your string in the "c.src="/books/4/263/1/html/2/ line will differ depending on your particular ' application. Consult your vendor for the specific string you'll need to use ' function ClickAlert(){ c=new Image(); c.src=(http://www.yourtrackingapplication.com/ tracking_code.cgi?link_href="+escape(this.href)+"&rn='+rnums;) c.onload=ClickTrackRedirect(this.href); } ' ' This function sets up the link array and calls ClickAlert when a link is clicked ' Use Language to Drive Action function SetClickTracking(){ for(i=0;(link=document.links[i]); i++){ link.onclick=ClickAlert; }; } </script> The most important things to note about this code are:
And perhaps most importantly, most modern web measurement applications are able to measure clicks with relatively little setup and will present the results in a more elegant fashion than this code. Ian Houston and Eric T. Peterson |