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?
Ok, I think I solved this for myself. Several factors were key to this particular situation:
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!
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">
.
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.