How do I stop youtube audio from playing in the middle?

I have a 2 minutes demo video on my site. You click a button to open it in a popup. When a user closes the popup (Display: None) the audio keeps playing. A user has to open the popup again and stop the video before hitting close, which is a terrible UX.
Any ideas?

Thank you,
Asaf Lupo

Here’s the site: https://www.insights.us/


Here is my public share link: LINK
(how to access public share link)

Hi,

You need to use Youtube API in order to cotrol the play/pause of videos from another element than the video player itself. It’s a bit of developer level. YouTube  |  Google Developers

1 Like

Hi @LupoAsaf

I’ve already had the joy to play around with the Youtube API.
It’s really cool. You can use this code to setup your player.
Basically all you need is assign your “closebutton” the ID of pausebutton.

<script>
// https://developers.google.com/youtube/iframe_api_reference

// global variable for the player
var player;

// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
  // create the global player from the specific iframe (#video)
  player = new YT.Player('video', {
    events: {
      // call this function when player is ready to use
      'onReady': onPlayerReady
    }
  });
}

function onPlayerReady(event) {
  

  var pauseButton = document.getElementById("pausebutton");
  pauseButton.addEventListener("click", function() {
    player.pauseVideo();
  });
  
}

// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>

Best,
Karl-Heinrich

P.S.: Don’t forget to add “?enablejsapi=1” at the end of your video URL, otherwise it won’t work.

2 Likes

Thank you, guys @Karl-Heinrich @vincent

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.