Download Script Live Demo
HTML & JavaScript Code
<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 for your website. Here just modify UA-YOUR-GA-ID value.
(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.
$(“#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 function, using this you will find out how many people actually finished the video.
$(“#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>
$(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>