I have a JavaScript question regarding the YouTube API. I made some modifications to the YouTube iFrame API in order to display two videos simultaneously, with one playing automatically and the other not. However, I am facing an issue where only the second video is being shown.
Below is the code I have implemented:
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player1', {
height: '315',
width: '420',
videoId: 'bHQqvYy5KYo',
events: {
'onReady': onPlayerReady
}
});
}
var player2;
function onYouTubeIframeAPIReady() {
player2 = new YT.Player('player2', {
height: '315',
width: '420',
videoId: 'M3uWx-fhjUc',
events: {
'onReady': stopVideo
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function stopVideo() {
player.stopVideo();
}
</script>
<div id="player1"></div>
<br>
<div id="player2"></div>
After implementing the suggested fix, the updated code looks like this:
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player1;
var player2;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player1', {
height: '315',
width: '420',
videoId: 'bHQqvYy5KYo',
events: {
'onReady': onPlayerReady
}
});
player2 = new YT.Player('player2', {
height: '315',
width: '420',
videoId: 'M3uWx-fhjUc',
events: {
'onReady': stopVideo
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function stopVideo() {
player.stopVideo();
}
</script>
<div id="player1"></div>
<br>
<div id="player2"></div>