I'm using YouTube iframe to embed videos on my site developed using php laravel framework. I want to ensure autometic stop others videos when i play one video. I am using following code but not workng it. Can anyone please help me!
<iframe id="youtube_player" class="yt_player_iframe" width="100%" height="350"
src="https://www.youtube.com/embed/{{$post->video_link}}" title="YouTube video player"
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope;
picture-in-picture" allowfullscreen></iframe>
<script>
$('.yt_player_iframe').each(function(){
this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
});
</script>
To pause other videos and play the currently clicked one, You have to loop on each one and make sure it is not playing
I have created a sample function and you can workaround it:
// Function Argument takes the current player
function pauseOthersYoutubes( currentPlayer ) {
// Make Sure there is a current video working, if not don't proceed
if (!currentPlayer) return;
//Loop to make sure all players are stopped unless the current player
for (var i = ytplayerList.length; i-- ;){
if( ytplayerList[i] && (ytplayerList[i] != currentPlayer) ){
ytplayerList[i].pauseVideo();
}
}
}