Datalayer not getting push on click event? - google-tag-manager

I m having trouble pushing datalayer to gtm on click event. But datalayer gets properly pushed on a load of the page but not on click. below is my code
$('.load-test-div').on("click", function () {
//console.log('Called properly');
dataLayer.push({
'event': 'display more',
});
});
I have manipulated code in a different way still it's not pushed. For testing, I m using the "Tag Manager" addon of chrome. Is there are any setting to capture click event in google tag manager. Please help!

Without seeing more I can only guess.
For example, this works: https://jsfiddle.net/emo38rbv/
dataLayer = window.dataLayer || [];
document.querySelector('.load-test-div').addEventListener('click', function(){
dataLayer.push({
'event': 'display more',
});
alert('this has pushed to the dataLayer: '+JSON.stringify(dataLayer[dataLayer.length -1]));
});
The issue could be:
Your function is being called before jquery is loaded.
The dataLayer hasn't been declared
The DOM is not ready (the query selector can't find the element)
The element does not exist at the time you run your function

Related

GTM Callback firing multiple times

I've followed the Google docs to add GTM tags to my site. For some reason the call back is firing 3 times, however, I only have this tag on the page.
window.dataLayer.push({
'event': 'add_expense',
'eventCallback': function () {
alert('wtf');
}
});
Anyone have any clues on why this may be?
It could be you have multiple GTM containers on the page, including plugins. You can check to see if the callback is being passed different containers ids:
'eventCallback': function (id) {
alert(id);
}
This happened to me after enabling GA4 in the page. Seems like it is using same container and rules as GTM and caused callbacks to fire twice. My solution:
const buildGtmCallback = (callback) => {
//GA4 is also a container, so need to fire callbacks only once, for GTM container
//GA4 containerId starts with G-
return (containerId) => {
if (containerId.startsWith("GTM-") && typeof callback === "function") {
callback();
}
}
}
And then whatever you wish to be fired only once:
window.dataLayer.push({
'event': 'add_expense',
'eventCallback': buildGtmCallback(function () {
alert('wtf');
})
});
This solution will also work if you have multiple GTM containers by modifying containerId.startsWith("GTM-") and replace “GTM-“ with the container ID you wish the event to fire for. However in that case you won’t be sure event was fired for both containers, just that one

wpcf7 and GTM event listener issue

I have a Tag set up in GTM, custom html like this;
<script>
document.addEventListener( 'wpcf7submit', function( event ) {
dataLayer.push({
'event' : 'wpcf7successfulsubmit',
'CF7formID' : event.detail.contactFormId
});
}, false );
</script>
Doesn't work. Not at all. So I put a script on the page.
var wpcf7Elm = document.querySelector( '.wpcf7' );
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
dataLayer.push({
'event' : 'wpcf7successfulsubmit',
'CF7formID' : event.detail.contactFormId
});
}, false );
from a basic example on contactform7.com. This, in GTM preview, triggers fine. The first time it triggers the tag once, the 2nd and subsequent times it triggers twice (implying that both my script and the GTM tag are firing). Guessing at a problem with the event bubbling up. I put the specific selector wpcf7Elm into the tag's custom html but this doesn't work - like the first example.
I have no problem with running from a script but the problem is firing the tag twice so that the analytics shows two events. I would like to use GTM but at the moment the only solution I can see is to go back to on page scripts.
Can anyone suggest what I might be doing wrong? Just to note that I have disabled all plugins and that I am using, on a different page, a wpcf7 event listener successfully (from a script on the page) to perform a presentation function.

Social shares tracking in GA

This is pretty much covered topic for original FB/Twitter buttons. But what if I have my own "share on fb" button? Like this:
<div id="fb_share"><a target="_blank" href="http://www.facebook.com/share.php?u=blah-blah">Share on FB</a></div>
so I've come up with the folloing solution:
var FBbtn = document.getElementById("fb_share");
FBbtn.addEventListener('click', function() {
ga('send', 'social', {
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': window.location
});
//console.log('tracked');
});
That is placed AFTER the Google Analytics code.
Despite the fact it wont catch FB callback - it is supposed to do the trick but for some reason I still cannot see any results in Analytics so the question is this: will the solution actually work? In fact it could be even like this I believe:
FB
Your 'share on Facebook' links causes the page to navigate (and not open a new window/tab). When this navigation happens, most mainstream browsers cancel all pending HTTP requests for the current page and then navigates to the new page (fb.com)
In this scenario, one of the pending HTTP requests will be the GA event tracking call which will therefore never complete and never be received by the GA servers.
What you need to use is the GA hit callback functionality, this essentially cancels the native navigation (to FB), sends the tracking call and waits enough time for it to complete and then does a JavaScript redirection to the next page.
You should read the google docs here
In your case your event tracking function should be similar to this:
var FBbtn = document.getElementById("fb_share");
FBbtn.addEventListener('click', function() {
ga('send', 'social', {
'socialNetwork': 'facebook',
'socialAction': 'share',
'socialTarget': window.location,
'hitCallback': function(){
window.location = this.href;
}
});
//console.log('tracked');
return false;
});
So I've made the following changes:
Added the hitCallback property to the event tracking call. this is an anonymous function that is called once the GA servers have sent their response to the event tracking.
added a 'return false' statement which cancels the native functionality and then relies on the hitCallback function to do the navigating.

Trigger event using dataLayer does not work

I have problems with trigger my event. In my code:
<script>
dataLayer.push({
'event' : 'GAEvent',
'eventCategory' : 'overlayer',
'eventAction' : 'popup [overlayer]',
'eventLabel' : undefined,
'eventValue' : undefined
});
</script>
In the preview mode my custom event isn`t trigger because of _event rule
which I didnt create in GTM. My trigger from GTM:
Any ideas what I did wrong?
You are passing in "GAEvent" as a dataLayer event, but had the incorrect field in your GTM trigger looking for it. (Screenshot shows "GaEvent").
You also don't need the filter field, which is where you originally put in the uppercase verion.
Change that to the same as the event you are passing in, "GAEvent".
There is always confusion on which events we are talking of, GA, GTM or JavaScript :)

React + Router + Google Tag Manager

I've been spending a bit of time developing an MVP at quickcypher.com. I wanted to start putting in some analytics, and it worked great for just tracking total visits, but things went south when I tried to track different URLs on my site that uses React Router.
My approach was this: Setup a GA tag that fires on some pages, using a trigger for a custom "pageview" event. When things did fire, I would set the field page to "/rap" for example. I was firing the event in the "componentDidMount" method of the top level component for each of my views. Using the debugger, I saw the event fire as expected, but for the life of me I can't get GA to acknowledge the event. GA works as expected when I simplify the tag to fire on "all pages", so I'm assuming it has something to do with React.
Has anyone successfully implemented this or run into similar problems? Is my approach all wrong? Hoping for some guidance...cheers!
A bit late to the party here, but react router should need no special code to integrate with GTM. Just drop the GTM script on your page (immediately after the opening <body> tag as recommended) and let your app run as normal.
In GTM create a custom trigger for history change.
You can fire it on all history changes.
Or only on some of them. Only on your production hostname, for example.
Then add a tag for your google analytics (or whatever) and configure it to fire on your history change event by clicking "More" under "Fire On" and selecting the trigger created above.
It's also important to change the Advanced Settings of our tag to fire once per event instead of once per page. Without this, the tag will only fire on the initial page load.
This could be due to misconfiguration of your google analytics account, but assuming that you can fire the initial pageview event back to GA, here is a recipe that taps into react-router's willTransitionTo hook. It also uses react-google-analytics. First npm install react-google-analytics.
Then configure your app like so:
var React = require('react');
var Router = require('react-router');
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var RouteHandler = Router.RouteHandler;
var ga = require('react-google-analytics');
var GAInitiailizer = ga.Initializer;
// some components mapped to routes
var Home = require('./Home');
var Cypher = require('./Cypher');
var App = React.createClass({
mixins: [Router.State],
statics: {
willTransitionTo: function(transition, params, query, props) {
// log the route transition to google analytics
ga('send', 'pageview', {'page': transition.path});
}
},
componentDidMount: function() {
var GA_TRACKING_CODE = 'UA-xxxxx';
ga('create', GA_TRACKING_CODE);
ga('send', 'pageview');
},
render: function() {
return (
<div>
<RouteHandler />
<GAInitiailizer />
</div>
);
}
});
var routes = (
<Route path="/" handler={App} >
<DefaultRoute handler={Home} />
<Route name="cypher" path="/cypher" handler={Cypher} />
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler />, document.body);
});
module.exports = App;

Resources