December 5, 2017
Track HTML5 Video Views with Google Analytic
Today we are talking about Track HTML5 Video Views with Google Analytic
HTML & JavaScript Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(document).ready(function(){ ...... ...... ...... }); </script> //HTML Code <video id="video" width="100%" controls> <source src="video.mp4" type="video/mp4"> </video> |
Google Analytics
Create a free Google Analytics account, add a property to your website. Here simply modify UA-YOUR-GA-ID worth.
<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-YOUR-GA-ID', 'auto'); ga('send', 'pageview'); </script> |
Jquery Bind Timeupdate
Contains jquery code. $(“#video”).bind(“timeupdate”, function(){} – here video is the ID name of the video tag, this will bind with video timeline. This will call Google Analytics function once it crossed 66%, you can modify percentage value.
var i=0; $("#video").bind("timeupdate", function() { var currentTime = this.currentTime; if(currentTime > 0.66*(this.duration)) { if(i<1) { /* Watched 66% */ ga('send', 'event', 'Videos', 'Watched','Video Title'); } i=i+1; //Reset for duplicates } }); |
Jquery Bind Ended
This works like previous perform, victimisation this you’ll establish what percentage folks really finished the video.
var j=0;
$("#video").bind("ended", function()
{
if(j<1)
{
/* Finished */
ga('send', 'event', 'Videos', 'Finished','Video Title');
}
j=j+1; //Reset for duplicates
}); |
Google Analytics Widget Filter

Result
Final Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(document).ready(function(){ var i=0; var j=0; /* Video Watched */ $("#video").bind("timeupdate", function() { var currentTime = this.currentTime; if(currentTime > 0.66*(this.duration)) { if(i<1) { /* Watched 66% */ ga('send', 'event', 'Videos', 'Watched','Video Title'); } i=i+1; //Reset for duplicates } }); /* Video Finished, Thanks */ $("#video").bind("ended", function() { if(j<1) { /* Finished */ ga('send', 'event', 'Videos', 'Finished','Video Title'); } j=j+1; //Reset for duplicates }); }); </script> //HTML Code <video id="video" width="100%" controls> <source src="video.mp4" type="video/mp4"> </video> //Google Analytics Code <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-YOUR-GA-ID', 'auto'); ga('send', 'pageview'); </script> |