javascriptyoutube-apiyoutube-javascript-apiyoutube-iframe-api

How to detect if video has just begun to play using Youtube API?


I have a youtube player embed done with API as instructed in documentation. Player works fine, so far good. Next for analytics, I want to trigger an analytics event when the video has just started playing (like at clip 1 of video).

From documentation, I am able to read YT.PlayerState.PLAYING === event.data at onStateChange event. But this event is fired when user pauses and plays; skips to different clip and plays; video buffers and plays etc. I have to fire my analytics event ONLY when video just started to play at clip 1. Is there an event/way to check if video is playing from clip 1.

Note: I tried storing the previous states and then comparing. I dont feel it is a clean solution. Looking for a better way.


Solution

  • var videoBegan = false;
    if (!videoBegan){
        // Your code to fire after the video has began
    }
    
    if(YT.PlayerState.PLAYING === event.data){
        videoBegan = true;
    }