On some websites, the gtm.click and gtm.linkClick events are not workining. No matter where you click, those events are never added to the event list. If you want to do some more complex tagging, those events are indispensable.
The events can be blocked from firing due to a number of reasons. Most of the time it’s a conflicting JavaScript library or script. In JavaScript events “bubble” up from the deepest element that was clicked up to the document element. For example, when you click a link, first the click event is fired on the link element, after that the click event is fired on the parent element of that link, for example a paragraph the link element is nested in, and so on. Until it reaches the document element and fires the click event there. GTM is listening for click events on the document level. So whenever another script stops the click event from propagating before it has reached the document’s click listener, GTM will never know this click ever happened.
Luckily there is an easy solution for this: we create a custom HTML tag that creates a GTM event whenever an element or link is clicked on a page.
1. Create a new Custom HTML tag, name it GTM Click Helper.
2. Add the following code to the tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
jQuery.noConflict();
/// run the following script using our jQuery library
(function($) {
$(function() {
/// add gtm.click handlers
$('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"
});
});
});
</script>
That’s it! When you click elements and links in your page, the gtm.click and gtm.linkClick events should fire correctly.
Author: David Peeters