Considering your code:
<div class="video_block">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/4LaUVEF9GTs?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="video_block">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/JYZ_oP7QVSY?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
Through this implementation, you will not need to define the identification of iframes or store many players in the memory. You just need to store the last iframe played.
Insert this script before using any function related to the Youtube iframe api.
<script src="https://www.youtube.com/iframe_api"></script>
If you're using an iframe directly on html, then append "enablejsapi=1" and your websites origin, in the iframe sources url parameters in all your iframe sources. Like this:
<iframe id="video_player" src="https://www.youtube.com/embed/VIDEO_ID?enablejsapi=1&origin=https://example.com"></iframe>
You can choose to "pauseVideo" or "stopVideo", in 'postMessage' method, of the following implementation:
var playedVideoIframe = false;
function onYouTubeIframeAPIReady() {
const IFRAMES = document.getElementsByTagName('iframe');
generatePlayers(IFRAMES);
}
function generatePlayers(IFRAMES) {
for (const IFRAME of IFRAMES) {
if (IFRAME.src.includes('youtube')) {
new YT.Player(IFRAME, {
events: {
'onStateChange': onPlayerStateChange
}
});
}
}
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
const PLAYING_VIDEO_IFRAME = event.target.h;
pauseLastPlayedVideo(PLAYING_VIDEO_IFRAME);
playedVideoIframe = PLAYING_VIDEO_IFRAME;
}
}
function pauseLastPlayedVideo(PLAYING_VIDEO_IFRAME) {
if (playedVideoIframe && playedVideoIframe.src != PLAYING_VIDEO_IFRAME.src) {
playedVideoIframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
}
Need more help? Read the documentation on https://developers.google.com/youtube/iframe_api_reference