Skip to content

Instantly share code, notes, and snippets.

@bmodena
Last active February 22, 2017 18:34
Show Gist options
  • Save bmodena/bcba5c95a2671f63743f4c914a7308c3 to your computer and use it in GitHub Desktop.
Save bmodena/bcba5c95a2671f63743f4c914a7308c3 to your computer and use it in GitHub Desktop.
Simple analytics event tracking
/*
Add a data attr of event to a tag and push to analytics
@req : jquery
*/
<a href="http://google.com" class="btn" data-event="footer-action">Download Now</a>
<script type="text/javascript">
$('a').on('click', function(event){
event.preventDefault();
var href = $(this).attr("href"),
target = $(this).attr("target"),
eventData = $(this).attr('data-event');
// if we want to track event push the data
if(eventData){
ga('send', 'event', {
eventCategory: eventData,
eventAction: 'click',
eventLabel: href
});
}
// wait for data to push and then open link
setTimeout(function() { // now wait 150 milliseconds...
window.open(href,(!target?"_self":target)); // ...and open the link as usual
},150);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment