Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event tracking not working on Google Analytics

I've tried everything to try to get some simple event tracking to work to no avail. Here's the code. I'm using Universal Analytics.

 <script>
          (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

          ga('create', 'UA-xxxxxxx', 'thissite.net');
          ga('send', 'pageview');


            /*Testing with this link*/

              $('.home-logo').on('click', function() {
                alert('clicked');
                ga('send', 'event', 'homelogo', 'click', 'icons');

        });
         </script>

        <!--Sample Link -->
         <a href="/portal/" class="home-logo"><img src="/images/aeportal_logo_small.png" width="95" border="0" /></a>

It's using AJAX and services to render content on the application, so I am not sure if something else needs to be done. I know there's a 'hit callback' function as well, but that didn't work either. Thanks for any assistance you can provide.

like image 673
erics15 Avatar asked Mar 16 '26 09:03

erics15


1 Answers

You may need to delay the page from moving on so GA can send the event.

You can do that with the hitCallback function and put it in a reusable function so you can add events for outbound links all over the page:

function trackOutboundLinks(category, action, label, url){
    ga('send', 'event', category, action, label, {'hitCallback':
       function () {
           document.location = url;
        }
     });
}

$('.home-logo').on('click', function(e) {
     e.preventDefault();
     trackOutboundLinks("homelogo", "click", "icons", $(this).attr("href"));
});

Alternatively, you can add an onclick function to the link itself rather than use the .on function above:

<a href="/portal/" class="home-logo" onclick="trackOutboundLinks('homelogo', 'click', 'icons', '/portal/'); return false;"><img src="/images/aeportal_logo_small.png" width="95" border="0" /></a>

Also, you can use the Google Analytics Debugger extension for Chrome to check if the events are fired rather than staring at real-time.

Google Analytics Reference

like image 176
jk. Avatar answered Mar 18 '26 01:03

jk.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!