Scott Blair
Scott Blair

Reputation: 3

Google Analytics - OnClick Event Tracking with Javascript & CSS Class

Due to a theme limitation in WordPress where I can't inline the onclick event, I'm passing attributes into the link and attempting to pick this backup in Javascript to send the Event tracking to Google Analytics. It's not firing and I can't figure out why.

The script was posted on another website and I'm working to adapt it for my use. I've tried escaping the variables /' and \x27 on the ga(send line but nothing is working so far. I've also included jQuery as a include to see if that was the issue as well.

<a href="#" class="ga-track" data-category='Schedule Appointment' data-action='click' data-label='Website'>Link</a>

<script type="text/javascript">
  var trackEl = document.querySelectorAll('.ga-track');
  Array.prototype.forEach.call(trackEl, function(el) {
      el.onclick = function() {
          var elCategory = this.getAttribute('data-category');
          var elAction   = this.getAttribute('data-action');
          var elLabel    = this.getAttribute('data-label');
          ga('send', 'event', elCategory, elAction, elLabel);
      };
  });
</script>

No errors are being triggered. My hope is that this will pass an Event into Google Analytics for conversion tracking.

Upvotes: 0

Views: 1705

Answers (1)

Scott Blair
Scott Blair

Reputation: 3

I was able to get it working with the following code:

<a href="#" class="ga-track" data-category='Schedule Appointment' data-action='click' data-label='Website'>Link</a>

<script>
jQuery(document).ready(function() {
 jQuery(‘.ga-track’).on(‘click’,  function(e) {
     e.preventDefault();
      var elCategory = this.getAttribute(‘data-category’);
      var elAction   = this.getAttribute(‘data-action’);
      var elLabel    = this.getAttribute(‘data-label’);
      gtag(‘event’, elAction, { ‘event_category’: elCategory, ‘event_label’: elLabel });
 });
});
</script>

Upvotes: 0

Related Questions