I’m trying to display an image in the “player” div, and then after the visitor clicks the button, replace it with a video (replace the div with an iFrame). Here’s my code:
<!DOCTYPE html>
<head>
<style type="text/css">
html {
text-align: center;
}
#player {
display: inline-block;
width: 640px;
height: 360px;
background: url(http://placehold.it/640x360) no-repeat;
}
</style>
</head>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<p><button onclick="playMe()">Play</button></p>
<script>
function playMe() {
// 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', {
height: '360',
width: '640',
videoId: 'JW5meKfy3fY',
playerVars: { 'autoplay': 0, 'controls': 0, 'rel': 0, 'showinfo': 0 },
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
}
</script>
</body>
</html>
But it doesn’t work.
It works when the “playMe” function is removed, but I’d need the video start after a button/div/link is clicked. I’ve tried to put the picture and the video into separate divs, picture on top of the video and than after the click hide the top div and start the video, but that didn’t work either.
This is a variable scoping issue.
The function onYouTubeIframeAPIReady needs to be a global variable – as does the player variable.
I believe this example should work as a basis for what you want (there’s a race condition if you click the button before the api has downloaded, but a full implementation would probably be app-specific so I’ll leave that to the reader)