Matt Hammond Matt Hammond - 10 months ago 53
CSS Question

Youtube detect when video started playing


The aim is to be able to adapt YouTube JavaScript to be able to detect when a video has finished it initial buffer and has started to play. This should then trigger an event which will then remove

Display: none
from the class revealing the auto-playing video. The idea behind this is that mobile devices won't see the video as mobile don't allow auto-play therefore we want to hide it. Due to the platform I'm using I can't use media queries as the view port has to be set to 1280px.

Current Progress

I've tired using YouTube state change to remove the display none. However this removes the video when the buffer starts not when the video playing. Meaning on mobile devices the video still shows.

// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.

var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: 'UA-DEHHUjeM',
playerVars: {
'loop' :1,
'playlist' :'UA-DEHHUjeM'
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {;

// 5. The API calls this function when the player's state changes.
var done = false;
function onPlayerStateChange(event) {
document.getElementById("videoContainer").className = document.getElementById("videoContainer").className.replace( /(?:^|\s)video-hidden(?!\S)/g , '' );

All Suggestions are appreciated!!!

Answer Source

you can use the YT.PlayerState object and compare it to your, to find if the video is playing it would look like this:

  function onPlayerStateChange(event) {
      if ( == YT.PlayerState.PLAYING){
        //your code here