Using HTML data attributes to elegantly create Mixpanel trackers

I've been using Mixpanel to track user behavior on one of my projects, and sought a more elegant way to track link clicks than the track_links method the standard API provides. Instead, I'd like to be able to specify the tracker's name and properties as HTML attributes.

Simply paste this snippet into your document ready block to get started: Using data attributes to elegantly create Mixpanel trackers

Then, on any links you'd like to track, simply provide the data-mixpanel-tracker attribute:

<a href="/moon" data-mixpanel-tracker="he chose to go to the moon">Go to the Moon!</a>

Specify custom properties in JSON using the data-mixpanel-properties attribute:

<a href="/moon" data-mixpanel-tracker="he chose to go to the moon" data-mixpanel-properties="{agency: 'nasa', mission: 'apollo 13'}">Go to the Moon!</a>

This snippet will automatically redirect the user to the link's href after 300ms, so no need to worry if the Mixpanel request failed. Happy tracking!