Created
August 9, 2018 07:11
-
-
Save blogjunkie/f24176d516d1fff4d6811ef600409943 to your computer and use it in GitHub Desktop.
Track clicks as GA events on all links with 'ga_event_click' CSS class
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($) { | |
/* | |
Track clicks as GA events on all links with 'ga_event_click' CSS class | |
Use data attributes to identify event fields. Example use: | |
<a href="http://example.com" class="ga_event_click" data-category="Button" data-action="play video" data-label="Play Button" data-value="0">Click me</a> | |
data-category will default to 'click' if no value is provided | |
data-action will default to the URL if no value is provided | |
data-label will default to the link text if no value is provided | |
*/ | |
$('.ga_event_click').on('click',function(e) { | |
// Check for Google Analytics | |
// if(typeof(ga) !== 'undefined'){ | |
// Check for MonsterInsights instead | |
if ( mi_track_user ) { | |
e.preventDefault(); | |
var url = $(this).attr("href"); | |
var linkText = $(this).text(); | |
var category = ($(this).data('category') !== undefined) ? $(this).data('category') : "click"; | |
// var action = ($(this).data('action') !== undefined) ? $(this).data('action') : ""; | |
var label = ($(this).data('label') !== undefined) ? $(this).data('label') : linkText; | |
var value = ($(this).data('value') !== undefined) ? $(this).data('value') : 0; //SHOULD BE NUMERIC | |
// Send event | |
// ga('send', 'event', { | |
// Use MonsterInsight's alias instead | |
__gaTracker('send', 'event', { | |
'eventCategory' : category, | |
'eventAction' : url, | |
'eventLabel' : label, | |
'eventValue' : value, | |
'transport': 'beacon', | |
'hitCallback': function(){ | |
document.location = url; | |
} | |
}); | |
} else { | |
//e.preventDefault(); | |
console.log("Event was not sent."); | |
} | |
}); | |
// End | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment