Created
March 22, 2018 16:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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