I have two video id that I played alternatively in single iFrame. I used onStateChange to detect the status if the video is playing, loading or etc. In the first video, the onStateChange is working properly but if I click another video, the onStateChange not working again.
Here's my code,
HTML:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Page title</title><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><div class="Centerized"><p>STATUS: <span id="checkVid"></span></p><div class="iFrame"><iframe id="YT_Video" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div><div class="VideoList"><button id="FirstVideo">NCS SONGS PART 1</button><button id="SecondVideo">NCS SONGS PART 2</button></div></div></body></html>CSS:
<style>*{margin: 0;padding: 0;outline: none;box-sizing: border-box}body{ display: flex; justify-content: center; align-items: center; width: 100%; height: 100vh; background: #2bd5ff;}.centerized{ width: 90%;}.iFrame{ width: 100%; height: 300px;}iframe{ width: 100%; height: 100%;}.VideoList{ margin-top: 12px; display: flex; width: 100%; justify-content: center; gap: 5px;}button{ width: 100%; background: blue; border: none; border-radius: 7px; color: white; padding: 10px; font-size: 20px;}</style>JS:
<script>var VidURL = ["pk1BYU7SBWY", "dU6ARX-KdZg"];let YT_URL = "https://www.youtube.com/embed/";let YTAPI = "?enablejsapi=1&html5=1";YT_Video.src = YT_URL + VidURL[0] + YTAPI;FirstVideo.addEventListener("click", function(){YT_Video.src = YT_URL + VidURL[0] + YTAPI;checkVid.innerHTML = "Checking..."; });SecondVideo.addEventListener("click", function(){YT_Video.src = YT_URL + VidURL[1] + YTAPI; checkVid.innerHTML = "Checking..."; });var player;function onYouTubePlayerAPIReady() { player = new YT.Player('YT_Video', { events: {'onStateChange': onPlayerStateChange } });}function onPlayerStateChange(event) {//console.log(event.data);if(event.data == 3){ checkVid.innerHTML = "LOADING, Please Wait";}if(event.data == 1){ checkVid.innerHTML = "The Video is Playing";}if(event.data == 2){ checkVid.innerHTML = "You Paused the Video";}}var tag = document.createElement('script');tag.src = "https://www.youtube.com/player_api";var firstScriptTag = document.getElementsByTagName('script')[0];firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);</script>If the iFrame is Loaded you can test like playing it then the Status print "The Video is Playing" but if you click the title "NCS SONGS PART 2", the status didn't update or in other words the onStateChange cannot triggered again.
EDIT: I coded this on my mobile phone, if you used laptop/desktop, please minimize the screen until 500px.