Track youtube video event on google analytic using html and javascript

Now YouTube is the best media providing company in the world. Most of the website use youtube media for the video solution. like example : online seminar website, learning tutorial website, movies website etc. YouTube provides its own player which we can embed in our website. YouTube also provides the api for handling the player with external custom buttons of javascript.


Most of the websites use YouTube embed player or iframe code, but this is not enough for those websites who wants to provide best service to the visitor. I mean to say there must be a data gathering algorithm with the help of that we can get the data about how many visitors play the particular video, how much percentage watched, most watched videos, least watched videos etc. This will really helpful for business perspective and customer service.

So this article is totally about to use youtube api and google analytic events step by step.

Create youtube player using javascript and youtube api

  • You have to create div element in html. see below code

Filename :- youtube.html (you can create with your own name)

    [code type=html] <div id="player"></div> [/code] 

  • Now create a js file and include that js to your html file

Filename :- youtube.js (you can create with your own name)

[code type=javascript]

/*added script for youtube iframe apis */
var tag = document.createElement(‘script’);
tag.src = “”;
var firstScriptTag = document.getElementsByTagName(‘script’)[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

/* youtube player state tracking */
var player;


/* *

** youtube api ready function

** This will call at the time of start After the youtube script loaded


function onYouTubeIframeAPIReady() {
player = new YT.Player(‘player’, {
height: ‘360’,
width: ‘640’,
videoId: youtubeFilename,
playerVars: {‘rel’:0,’showinfo’:0,’modestbranding’:0},
events: {
‘onReady’: onPlayerReady,  // player ready state function call
‘onStateChange’: onPlayerStateChange, //player state change function call
‘onError’: onPlayerError //player error function


** This function is use if you want to play, pause video using custom html button

** You need to get play button Id and bind the click event



function onPlayerReady(event) {
// get button Id and bind events on html play button
var playButton = document.getElementById(“play-button”);
playButton.addEventListener(“click”, function() {
player.playVideo(); // player is a object of youtube player and playVideo() is a function which will play the video


** This function will call at the time of player state change


function onPlayerStateChange(event) {
// events for tracking video play state

// YT.PlayerState.PLAYING for video is in playing state
if ( == YT.PlayerState.PLAYING) {

//send play state data to google analytic using ga function and send event

// you can skip the dimension parameter otherwise you have to create dimension in google analytic for setting the field values like userId, pagetitle etc.

// you can create dimension using your own name but inthe function you have to use serialwise

ga(‘send’, ‘event’, ‘Video’, ‘played’, ‘Started Watching’,{
‘dimension1’: userId,    //you can pass userId by php to js or get from hidden field
‘dimension2’: userName, //you can pass userName by php to js or get from hidden field
‘dimension3’: pageTitle, //you can pass PageTitle by php to js or get from hidden field or get from url
‘dimension4’: ‘Started Watching’,


// YT.PlayerState.ENDED call when video end

// getPercentage() will return the value of how much percent user watch the video

// below I define the getPercentage function
if ( == YT.PlayerState.ENDED) {
ga(‘send’, ‘event’, ‘Video’, ‘Completed’, ‘watched completely’,getPercentage(),{
‘dimension1’: userId,
‘dimension2’: userName,
‘dimension3’: pageTitle,
‘dimension4’: ‘Progress Completes’,

// YT.PlayerState.PAUSED call when video pause
if ( == YT.PlayerState.PAUSED) {
ga(‘send’, ‘event’, ‘Video’, ‘Paused’, pageTitle,getPercentage(),{
‘dimension1’: userId,
‘dimension2’: userName,
‘dimension3’: pageTitle,
‘dimension4′: getPercentage()+’% completed’,

/*  This function will return how much percent user watch the video */

function getPercentage(){
var pecentage = 0;

var pecentage = ((player.getCurrentTime()/player.getDuration())*100).toFixed();

/*  This function will call when error occur in the player */

function onPlayerError(e) {
ga(‘send’, ‘event’, ‘Error’, ‘Error occured’, ‘youtube’+ e.message);



Hope this code will help you to track YouTube video events. If you have any doubt on that you can comment on this Article.