Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a delay to link clicks for Google Analytics

I've been fiddling with various snippets of Javascript for the purposes of Google Analytics event tracking. I'm using Google Tag Manager. This question is also similar to some questions I posted recently so apologies to the smaller pool of users who follow the google analytics tag and are seeing the same thing.

Currently I'm working with this snippet:

    <script type="text/javascript"> 

$(document).ready(function(){ 

    $('.app-cta a').onClick=_gaq.push(['_trackEvent', 'App', 'Click', 'iOS']);

});
</script>

Within httpfox the event parameters (App, Click, iOS) are all showing. But not in Google Analytics.

I'm told that it is fairly common practice to add a delay to the link click of anywhere between 5 and 500 milliseconds. This is because, I'm told, that sometimes the browser hits the new site before it's had time to pass the analytics parameters.

There may be alternative means of correcting this but for my own curiosity of learning how to use Javascript for analytics, how would I integrate setTimeout to the above code?

I tried this:

<script type="text/javascript"> 

$(document).ready(function(){ 

 setTimeout(function(){

    $('.app-cta a').onClick=_gaq.push(['_trackEvent', 'App', 'Click', 'iOS']);

});
},500);
</script>

But surely this delays the Google Analytics tag from passing the data, rather than delaying the click? I checked and it did not solve my problem.

like image 992
Doug Fir Avatar asked Mar 23 '23 19:03

Doug Fir


1 Answers

Use Google Analytics' hitCallback

You can set a custom callback on the tracker by using the code documented here.

You might end up with something like:

$( ".app-cta a" ).click(function(e) {
        var location = $(this).attr('href'); //get the link location         
        e.preventDefault(); //disable the link action

        _gaq.push(['_set','hitCallback',function() {
            window.location = location; //action link after callback
        }]);

        _gaq.push(['_trackEvent', 'App', 'Click', 'iOS'); //trigger Track Event

        return !window._gat; //fallback in case Google Analytics hasn't loaded.
});
like image 158
Steve de Niese Avatar answered Apr 01 '23 16:04

Steve de Niese