I have a WordPress website where I'm embedding a YouTube video in a popup on a product page. The goal is to pause the video when the popup is closed. Here's the relevant code:
The JavaScript code uses the YouTube IFrame Player API to create and control the video. It's supposed to stop the video when the popup is closed:
<!-- WordPress template code --><a href="#0" class="cd-popup-trigger">Watch how to generate the correct link</a><div class="cd-popup" role="alert"><div class="cd-popup-container"><p>To learn how to generate the correct link, watch the video below:</p><div class="youtube-content"><div id="player"></div><!-- JavaScript code for YouTube API and controlling the video --></div><a href="#0" class="cd-popup-close img-replace"></a></div></div>
// JavaScript code for YouTube API and controlling the videovar tag = document.createElement("script");tag.src = "https://www.youtube.com/iframe_api";var firstScriptTag = document.getElementsByTagName("script")[0];firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);var player;function createPlayer() { if (typeof player !== "undefined") { player.destroy(); } player = new YT.Player("player", { videoId: "' . esc_js($youtube_link) . '", // Using the value from ACF field playerVars: { autoplay: 1, controls: 1, modestbranding: 1, rel: 0 }, events: { onReady: onPlayerReady } });}function onPlayerReady(event) { event.target.playVideo();}function stopVideo() { player.stopVideo();}
This code works on most devices, but there are some cases where the video doesn't pause or stop when the popup is closed. I've tested it on different browsers and devices, and the behavior is inconsistent.
I would appreciate any insights or suggestions on how to ensure that the video reliably pauses or stops when closing the popup on all devices and browsers. Thank you!