Using jQuery to track GA Events (universal)

I am trying to track plays and pauses using jQuery on my Wordpress site that is using the mediaElement.js to handle audio players. I have researched this and found what I thought to be answers, but I can still not get the ga() function to fire!

My code is as follows:

jQuery(document).ready(function($) {
   //Tracking MediaElement Plays
   $('body').on('click', '.mejs-play', function() {
     ga('send', 'event', 'Audio', 'Play', 'Audio Played');
   });
});

I am not getting any response from the GA Realtime report when I click the elements with this class assigned to it.

Any idea what I am doing wrong?

Answers:

Answer

There is something wrong with your jQuery implementation. When I type in console something like $(window), I see an error:

TypeError: $ is not a function
Answer

Ok, I think I solved this for myself. Several factors were key to this particular situation:

  1. Due to the oddities of the Wordpress.org CMS, I have to use jQuery() instead of $() for every lookup on my site — not just at the beginning of the code, but every time I need to do a lookup within my code. Makes for kind of bloated code, but it works!

  2. My script was doing nothing with the MediaElement.js initially because it was being loaded before any of the MEJS elements were being created, and thus, they did not exist at the time of my JS code being fired. To resolve this, I found this defer trick that allowed me to queue up my <script> element at the end of the line. Simple, I had to call the script in my header using <script defer="defer">.

  3. Once I got the base script functioning and firing results into my console, I used a simple if () {} else {} statement combined with .hasClass() to distinguish between a play and a pause.

The end result inserted into my site's header works beautifully! Here it is:

<script defer="defer">
//Tracking MediaElement Plays and Pauses
jQuery(window).load(function() {
  jQuery('.mejs-playpause-button').click(function() {
    if (jQuery(this).hasClass('mejs-play')) {
      ga('send', 'event', 'audio', 'play audio', 'audio played');
    } else {
      ga('send', 'event', 'audio', 'pause audio', 'audio paused');
    }
  });
});
</script>

I hope this helps someone else track their plays and pauses.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.