I try to make a video wall with multiple iframes, video should play when user hovers over the video iframe. Everything I set in the code works - I can call currentPlayer.seekTo(10) and it moves the slider but currentPlayer.playVideo() doesn't work.
And the weird part is than if I hover on a card - this creates or chooses a player from an array and set it to global vriable and I call this player manually from the console by
currentPlayer.playVideo()
All the code suddenly starts to work for that player, When I first manually call a function (does not matter which: playVideo, mute) on all the players my website starts to work as intended. I can hover between videos and only the one where the mouse is positioned is working.
html part of the code is here but in the bin it does not work at all, it's just for reference how it looks. https://jsbin.com/bavexujome/edit?html,js,output my js looks like this:
//yt api boilerplate
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// my helper variables
var players = {}
var player
var currentPlayerId = null
var currentPlayer = null
// I have cards with iframes inside - when user hovers on a card
// then I check if I have a player for that card in my players array
//and if not I create it and set it to global variable
// I also try to start that video first time I got the autoplay
// variable set - dont work and it there is a player I try to call
// .playvideo() on it - also does not work
// all variables are set proper - I can console.log them
$(document).ready(function(){
$('#hg-container').on("mouseenter", ".card", function(){
currentPlayerId = $(this).find('iframe').attr('id');
player = $(this).find('iframe')[0];
if (!players[currentPlayerId]){
players[currentPlayerId] = new YT.Player(player, {
playerVars: { 'autoplay': 1 },
events: {'onReady': onPlayerReady }
});
}
else{
currentPlayer = players[currentPlayerId]
currentPlayer.playVideo();
}
});
//when user leaves the card video should stop
$('#hg-container').on("mouseleave", ".card", function(){
currentPlayer.pauseVideo();
currentPlayer = null;
});
});
//this gets called when video loads - and seekTo(10) works
// but playVideo() don't
function onPlayerReady(event) {
currentPlayer = players[currentPlayerId]
currentPlayer.seekTo(10);
currentPlayer.playVideo();
}
function onYouTubeIframeAPIReady(){
console.log("ready")
}
Any hint's ? I think it might be a scope problem and when I call this from js console the scope somehow changes and then it works