Skip to content

Instantly share code, notes, and snippets.

@douglaskarr
Created March 22, 2018 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save douglaskarr/cc275c8ff52f1a310ca97d1cf817aa0f to your computer and use it in GitHub Desktop.
Save douglaskarr/cc275c8ff52f1a310ca97d1cf817aa0f to your computer and use it in GitHub Desktop.
Google Analytics Event Tracking using jQuery and outbound link with a class of button
<script type="text/javascript">
jQuery(function($) {
$(document).ready(function() {
$("a.button").each(function() {
var href = $(this).attr("href");
var target = $(this).attr("target");
var text = $(this).text();
$(this).click(function(event) { // captures the clicked link event
event.preventDefault(); // interrupts sending to the next page
// ga('send', 'timing', 'timingCategory', 'timingVar', timingValue, 'timingLabel'); // for GA
gtag('event', 'Button', {
'send_to': 'UA-XXXXXXXX-1',
'event_category': 'Clicked',
'event_label': text,
'name': 'Button',
'value': href,
'fatal': false
}); // for Google Tag Manager
setTimeout(function() { // Wait 300 milliseconds to send the event to GA
window.open(href, (!target?"_self": target)); // Open the link as usual
}, 300);
});
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment