Skip to content

Instantly share code, notes, and snippets.

@mreidsma
Created July 13, 2012 20:22
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mreidsma/3107202 to your computer and use it in GitHub Desktop.
Save mreidsma/3107202 to your computer and use it in GitHub Desktop.
Simple click tracking script
// .htaccess
//
// Add this to the directory where your write.php will be stored
// This is an easy way to do an HTTP request to the script with the data
<IfModule mod_rewrite.c>
RewriteEngine On
# Change the following to the base directory of this file
RewriteBase /clickstats/
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to write.php
RewriteRule . /clickstats/write.php [L]
</IfModule>
// clicks.js
//
// Load this script on the page where you want to collect stats
// Assign unique ids to all links on the page using a data element
// Set a click handler to fire every time a link is clicked
// It gathers the unique id of the clicked link and builds a URL to call
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].setAttribute("data-click", i);
anchors[i].onclick = function() {
confirm(i);
var hacky = document.createElement('iframe');
hacky.setAttribute('id', 'hacky-hack');
hacky.setAttribute('src', 'http://URL/clickstats/' + i);
hacky.setAttribute('style', 'visibility:hidden;');
document.body.appendChild(hacky);
};
}
// write.php
//
// This is the file that write to a database, or text file, or whatever.
<?php
header("Access-Control-Allow-Origin: *"); // Let's just be safe.
$navString = $_SERVER['REQUEST_URI']; // Returns "/clickstats/15/" or whatever. You want the "15"
$parts = explode('/', $navString); // Break into an array
// Change the number to reflect the piece of the array you want. You can scale this up to more fields.
$clicked = $parts[2]; // This is the position of the click
// Do something awesome with that number, like append it to a text file or write it to a database
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment