0

I'm using the new GA analytics.js to track my website, that triggers just fine. I'm trying to track a button for clicks (linking to an external website), making sure it opens in a new window so we have the time to track it.

<button class="knapp" id="b2" onclick="window.open('https://site.com');" 
target="_blank" type="button">Text</button>

According to googles guidelines, I can now use JS to track this.

Hence, I updated the code to match my button ID and events, then placed it in my header.

<script type="text/javascript">
var downloadLink = document.getElementById('b2');
addListener(downloadLink, 'click', function() {
ga('send', 'event', 'External_link', 'click', 'KL-FB');
});

function addListener(element, type, callback) {
 if (element.addEventListener) element.addEventListener(type, callback);
 else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
</script>

However, it doesn't trigger at all. I have a "normal" event tracker on a normal link that triggers just fine, but from what I can see in my console this doesn't even try.

user977101
  • 161
  • 2
  • 12

1 Answers1

1

There are a few issues with your code:

  1. Your addListener function in the <head> is running before the element b2 is rendered. There are a few options to solve this: Put scripts in bottom of page, call attach code on load, or wrap it in a jQuery document.ready. There is a good stackoverflow post on this.
  2. Your inline onclick event on the button is getting fired prior to the event sending. Use google analytics hitCallback function to send the user to the next page after ga has received the event.

That would look like this:

<script type="text/javascript">
    var downloadLink = document.getElementById('b2');
    addListener(downloadLink, 'click', function() {
        ga('send', 'event', 'External_link', 'click', 'KL-FB', {
            'hitCallback': function(){
                document.location = 'https://site.com';
            }
        });
    });

function addListener(element, type, callback) {
 if (element.addEventListener) element.addEventListener(type, callback);
 else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
</script>
Community
  • 1
  • 1
Blexy
  • 9,197
  • 5
  • 35
  • 51