4
votes

I am using Google Tag Manager to register events with Google Analytic. At one plance I am changing url on the changeof a dropdown. I want to track the same event on Google Analytics. I am worried what would happen if page is changed before event is registered with GA. Could you please let me know if there is a feature in GTM that can ensure that page is not changed before event is registered with GA.

Here is the code that will execute on the change of the dropdown

var targetCityChangedEventName = "TargetCityChanged";

$("#location", topHeader).bind({
        "change": function(ev, obj) {
            dataLayer.push({event : targetCityChangedEventName });
            var url = "http://" + window.location.host + "/" + $(this).val();
            window.location = url;
     }
});
2
If you use built-in event listeners in GTM, they all have hit callback functionality. - Petr Havlik
@PetrHavlĂ­k, but there is no onchange handler, is there ? - Eike Pierstorff
Eike, I think you are correct :-) - Petr Havlik

2 Answers

5
votes

If you are using ga.js (asynchronous Analytics) you can set an hit callback (a macro that returns a function) in the tag template under "advanced configuration and do the redirect there (possibly you'd need a separate analytics tag just the change event).

If you use Universal Analytics there was a discussion at the Tag Manager Google Group a while ago where Googles Brian Kuhn suggested the following way ( I have not tested this):

In the meantime, have you tried this?

dataLayer.push({callback:
 function() {
     alert(123);   
});

Then, create a dataLayer macro that reads the "callback" key. Then, use that macro as the value of a "fields to set" pair on your UA tag, under the field name "hitCallback".

Instead of the alert you'd do the redirect.

In case that's not clear, a hit callback is a function that can be passed to the tracking calls and is executed after the tracking call has executed.

0
votes

I was able to resolve the same issue by simply inserting a delay. The dataLayer.push doesn't need to return anything, so a 100 millisecond delay is sufficient in 99% of the cases for the dataLayer.push to be executed.

dataLayer.push({ ... });
setTimeout( function(){ window.location = ...; }, 100 );

Note that the GTM preview/debug mode gives false positives - you must make sure that your tags are actually being fired, in my case my event was for a virtual pageview and I could see the results in RealTime Analytics. Without the delay, I could see that the tag was not being fired.