I have a section of a client site that has multiple Vimeo videos that can be launched in Bootstrap modals, so am working on the jQuery needed to automatically play a video when its modal is launched, and pause it when it's modal is closed.
The following code works, but I realize it's not very efficient and have not had any luck trying to get a for loop to work. If someone was able to "teach me how to fish" here, I'll be a heck of a lot more efficient in the future.
var idPlayer0 = new Vimeo.Player('player_0');
jQuery('#modal-0').on('shown.bs.modal', function (e) {
idPlayer0.play();
});
jQuery('#modal-0').on('hidden.bs.modal', function (e) {
idPlayer0.pause();
});
// And do it again...
var idPlayer1 = new Vimeo.Player('player_1');
jQuery('#modal-1').on('shown.bs.modal', function (e) {
idPlayer1.play();
});
jQuery('#modal-1').on('hidden.bs.modal', function (e) {
idPlayer1.pause();
});
// And so on...
I have tried the following to no avail...
// get total number of iframes on page
var iframes = document.getElementsByTagName('iframe');
var idPlayer = [];
for (var i = 0; i <= iframes; i++) {
idPlayer[i] = new Vimeo.Player('player_' + i);
jQuery('#modal-' + i).on('shown.bs.modal', function (e) {
idPlayer[i].play();
});
jQuery('#modal-' + i).on('hidden.bs.modal', function (e) {
idPlayer[i].pause();
});
}
Any help is very appreciated. Thanks!
EDIT
Got this working using the following with help from @ryan and JavaScript closure inside loops – simple practical example. It is not the most robust solution, but it's getting closer.
jQuery( document ).ready(function() {
// get total number of iframes on page
var iframes = document.getElementsByTagName('iframe').length;
var idPlayer = [];
for (let i = 0; i < iframes; i++) {
idPlayer[i] = new Vimeo.Player(document.getElementById("player_"+[i]));
jQuery('#modal-' + i).on('shown.bs.modal', function (e) {
idPlayer[i].play();
});
jQuery('#modal-' + i).on('hidden.bs.modal', function (e) {
idPlayer[i].pause();
});
}
});