Last active
October 18, 2018 13:42
-
-
Save furzeface/8338247 to your computer and use it in GitHub Desktop.
A function to return the custom event tracker for Google Analytics, wrapped so if GA is not set up for local/demo environments JavaScript won't go mental!Plus, attaching it to a standard jQuery event listener.
This file contains hidden or 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
// Wrap it so if GA is not initialised it doesn't go 'undefined'! | |
function analytics_custom_event_tracker(name, event, label) | |
{ | |
if (typeof ga === 'function') | |
{ | |
return ga('send', 'event', name, event, label); | |
} | |
} | |
// Attach it to a standard JavaScript event listener | |
var clickMe = document.getElementById('click-me'); | |
clickMe.addEventListener('change', function () { | |
// your code goodness | |
analytics_custom_event_tracker('Dans Event Listener', 'click', clickMe.value); | |
// Sending the value of element to Google Analytics on a click event with the name 'Dans Event Listener' | |
}, false); | |
// Attach it to a standard jQuery event listener | |
$('#click-me').on({ | |
click: function () { | |
// the rest of your magic | |
analytics_custom_event_tracker('Dans Event Listener', 'click', $(this).val())); | |
// Sending the value of element to Google Analytics on a click event with the name 'Dans Event Listener' | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment