Tuesday, 25 September 2018

Turn background video (ambient video) into a playable video on button click

I have created an iframe by taking advantage of YouTube's API.

On page load, the ambient video is set to autoplay with no sound. However, on top of the div which contains the iframe, I have a button.

On this button click, I want the video to load in a modal popup with the YouTube controls and sound on.

Wondering how I would go about this? Would it involve creating another iframe?

Code:

//  Load  IFrame Player API 
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Creating iframe
var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    videoId: 'jagIsKF8oVA',
    playerVars: {
      'autoplay': 1,
      'controls': 0,
      'mute': 1,
      'loop': 1,
      'rel': 0
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

//  Calls function
function onPlayerReady(event) {
  event.target.playVideo();
}

var done = false;

function onPlayerStateChange(event) {
  // if (event.data == YT.PlayerState.PLAYING && !done) {
  //   setTimeout(stopVideo, 6000);
  //   done = true;
  // }
}

function stopVideo() {
  // player.stopVideo();
}
<!-- THIS IS IN home.php-->

<button>Click me</button>


<!-- THIS IS IN hero.php -->
<section id="videoHero" class="hero hero--video">

  <div class="hero__container--teaser">
    
    <!-- Where the iframe is stored-->
    <div id="player"></div></div>

</section>


from Turn background video (ambient video) into a playable video on button click

No comments:

Post a Comment