Question

1) My Google Analytics tracking code is placed in the HEAD, the Event tracking code is placed BEFORE BODY END TAG.

In this version, the clicks are tracked correctly, but the link leads to an /undefined page.

2) When I put both scripts in the HEAD, the links work, but no events are tracked.

QUESTION) What is the correct way to implement both codes?

INFO) This is my Google Analytics tracking code

<script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXX-X']); _gaq.push(['_setDomainName', 'xxxx.xx']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script>

This is my Google Event tracking code

<script>
$( '#lp-pom-image-xxx' ).click( function(event) {

event.preventDefault();
var buttonLink = $(this).attr("href");

var callbackFunction = function(){
window.location = buttonLink;
}

if(window._gat){
_gaq.push(['_set','hitCallback',callbackFunction]);
_gaq.push(['_trackEvent', 'x', 'y', 'z']);
} else {
callbackFunction(); 
}
});
</script>
Was it helpful?

Solution

Don't know why the first one is not working.

The second one is not working because your script is not inside a dom ready handler, so when your event registration code is executed the target elements are not loaded in the dom, this results in the handlers not getting added to the target elements.

So add the script in a dom ready handler

jQuery(function ($) {
    $('#lp-pom-image-xxx').click(function (event) {

        event.preventDefault();
        var buttonLink = $(this).attr("href");

        var callbackFunction = function () {
            window.location = buttonLink;
        }

        if (window._gat) {
            _gaq.push(['_set', 'hitCallback', callbackFunction]);
            _gaq.push(['_trackEvent', 'x', 'y', 'z']);
        } else {
            callbackFunction();
        }
    });
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top