I am working on a page that plays YouTube videos in bootstrap modals. I have made this JS function to pause videos when the modal is closed, however only for 3 modals.
var player1;
var player2;
var player3;
function onYouTubePlayerAPIReady() {player1 = new YT.Player('ytplayer1'); player2 = new YT.Player('ytplayer2'); player3 = new YT.Player('ytplayer3');}
$('#Video1').on('hidden.bs.modal', function () {
player1.pauseVideo();
});
$('#Video2').on('hidden.bs.modal', function () {
player2.pauseVideo();
});
$('#Video3').on('hidden.bs.modal', function () {
player3.pauseVideo();
});
Currently I am adding videos from a database. These videos open in a modal with id="Video_#"
where # is the ID of the video in the database. (Same for ytplayer#)
How should I change the script to pause the video when I close the corresponding modal?
TIA
To make this work for any of the videos you have on the page, you can do the following.
var videoIds = [1, 2, 3, 4, 5, 6];
videoIds.map(function (id) {
var videoPlayer = new YT.Player('ytplayer' + id);
$('#Video' + id).on('hidden.bs.modal', function () {
videoPlayer.pauseVideo();
});
});