Skip to content

Instantly share code, notes, and snippets.

@engarifulislam
Last active December 22, 2023 18:01
Show Gist options
  • Save engarifulislam/baef199dcb999efdcbbff7d1a67014eb to your computer and use it in GitHub Desktop.
Save engarifulislam/baef199dcb999efdcbbff7d1a67014eb to your computer and use it in GitHub Desktop.
jQuery Click Listener for Google Tag Manager replicating the "Click Element" and "Link Click" functionality within Google Tag Manager.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
/* jQuery is required for this script.
*/
/// load jQuery in no-conflict mode
jQuery.noConflict();
(function($) {
/// dom ready
$(function() {
$('body').on('click', function(e){
dataLayer.push({
"gtm.element": e.target,
"gtm.elementClasses": $(e.target).attr('class'),
"gtm.elementId": $(e.target).attr('id'),
"gtm.elementTarget": e.target,
"gtm.elementUrl": $(e.target).attr('href'),
"event": "gtm.click"
});
});
/// add gtm.linkClick handlers
$(document).on('click', 'a', function(e){
dataLayer.push({
"gtm.element": e.currentTarget,
"gtm.elementClasses": $(e.currentTarget).attr('class'),
"gtm.elementId": $(e.currentTarget).attr('id'),
"gtm.elementTarget": e.target,
"gtm.elementUrl": $(e.currentTarget).attr('href'),
"event": "gtm.linkClick"
});
});
});
})(jQuery);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment