The let player
is a bit of a hack, allowing code below it to update the player variable so that other code below it can get the player.
Let’s look at what the code does with player, and find out if other techniques might be more beneficial.
loadClickHandler
The player variable is used first in the loadClickHandler() function:
function loadClickHandler() {
loadPlayer();
player.playVideo();
}
That can never work. The loadPlayer function adds a script tag to load the youtube player library, and doesn’t have time to do anything before the player.playVIdeo line occurs.
Instead, the playVideo line needs to happen when the player is ready, which is why we have the onPlayerReady function. It needs to be moved down to there instead.
function loadClickHandler() {
loadPlayer();
// player.playVideo();
}
//...
function onPlayerReady(evt) {
//...
player.playVideo();
}
That attempts to play, but is stopped because the sandbox that jsFiddle runs the code in, doesn’t allow automatic presentations to occur.
As soon as the code is run outside of jQuery, the youtube video starts playing fine.
colorClickHandler
This code changes the of the lines and starts the player. It’s already started though by the onPlayerReady code too, so duplication is occurring here.
We can instead have the onPlayerReady code call the changeColor function, and there’s now no need for the colorClickHandler function.
// function colorClickHandler(evt) {
// changeColor();
// player.playVideo();
// }
//...
//wrapper.addEventListener("click", colorClickHandler);
//...
function onPlayerReady(evt) {
const player = evt.target;
changeColor();
player.setVolume(50); // percent
player.playVideo();
}
Remove let player
Nothing is left that accesses the player, so there’s no need for that let player statement.
// let player;
//...
window.onYouTubePlayerAPIReady = function() {
const video = document.querySelector(".video");
const videoId = video.getAttribute("data-id");
// player = new YT.Player(video, {
new YT.Player(video, {
Just remember that in jsfiddle when the youtube player shows the More videos panel, it has already started playing but was stopped because the jsfiddle sandbox doesn’t allow autoplay of videos. When you use the code outside of jsfiddle, it works well.