Matt Hammond
Matt Hammond

Reputation: 785

Youtube detect when video started playing

Aim

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 = "https://www.youtube.com/iframe_api";
  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) {
    event.target.playVideo();
    player.mute();
  }


  // 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!!!

Upvotes: 0

Views: 1982

Answers (1)

StackOverMySoul
StackOverMySoul

Reputation: 2037

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

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

Upvotes: 2

Related Questions