1

I need to add an event handler for GA event tracking to a button. I read the documentation thoroughly and spent an hour googling, but I didn't make it work. The session tracking works (I see myself in realtime analytics), but the event tracking doesn't work. This is my code:

<html>
<head>
<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-12345678-1', 'auto');
  ga('send', 'pageview');
</script>
</head>

<body>
<div>
<script>
var downloadLink = document.getElementById('submit_btn');
addListener(downloadLink, 'click', function() {
  ga('send', 'event', 'button', 'click', 'nav-buttons');
});
function addListener(element, type, callback) {
 if (element.addEventListener) element.addEventListener(type, callback);
 else if (element.attachEvent) element.attachEvent('on' + type, callback);
}
</script>
<button type="submit" id="submit_btn" name="submit_btn">submit</button></div>
</body>
</html>

What am I doing wrong here?

JAL
  • 39,073
  • 22
  • 153
  • 285

1 Answers1

2

I am not sure, but it may be the way the JavaScript code is invoke on the page.Can you try the following code:

<body>
  <div>
    <button type="submit" id="submit_btn" name="submit_btn">submit</button>
  </div>  
</body>
<script>
  var downloadLink = document.getElementById('submit_btn');

  addListener(downloadLink, 'click', function() {
    ga('send', 'event', 'button', 'click', 'nav-buttons');
  });

  function addListener(element, type, callback) {
    if (element.addEventListener) element.addEventListener(type, callback);
    else if (element.attachEvent) element.attachEvent('on' + type, callback);
  }
</script>
</html>
MaxZoom
  • 6,949
  • 5
  • 24
  • 41
  • this worked! do I get this right? you just placed the js part below the button? – youvebeennarddogged May 20 '15 at 23:20
  • 1
    You can attach event handlers only after the element you want to attach to has been created - so your code does not work when it's placed above the button, but works when it's below. If you still want to have your javascript in the head of the page you need to defer execution until the HTML content of your page has rendered. This answer should help with that: http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery – Eike Pierstorff May 21 '15 at 08:36
  • As Eike point out, you have to make sure that the element exists before attaching an eventListener to it, otherwise it won't work. – MaxZoom May 21 '15 at 16:16