I have modified my question following A.Cedano's comments.
I'm trying to implement the YouTube Player API , the implementation works correctly, if I click on any button the first time, it works and starts the video, now the problem comes if I do a second onclick to open another video, it doesn't change and the previous video continues to play and does not change, instead the alert does show me the new data-id obtained to play the new video.
How could I stop the video being played and reload the new video on every onclick?
To obtain the data-id I have used this example: Soes
<head>
<script>
/*
Con querySelectorAll haremos un alcance más específico
el selector usado aquí signfica simplemente:
"selecciona todos los elementos de tipo button
que tengan la clase btn-Editar"
Significa que otros botones quedarán aislados de esta escucha
así como otros elementos que tengan esa clase, pero no sean button
*/
var editButtons = document.querySelectorAll('button.btn-Play');
/*
A los elementos alcanzados por el criterio antes indicado
le asignamos un listener...
Significa que el click en cualquiera de esos elementos
ejecutará el código contenido en la función
en este caso recuperar el data-id
*/
editButtons.forEach(function(item, idx) {
item.addEventListener('click', function() {
/*
Usaremos la forma que existe para leer los atributos data
que es dataset
*/
//console.log(item.dataset.id);
Player(item.dataset.id);
});
});
</script>
</head>
<body>
<!-- Reproductor Youtube -->
<div id='player'></div>
<button class="btn-Play" data-id="n7l1oAYRThQ">Video 1</button>
<button class="btn-Play" data-id="G3P1IJaY6AA">Video 2</button>
<button class="btn-Play" data-id="353B-kOxWz4">Video 3</button>
//Etc..
<script>
function Player(id) {
// alert(id);
// Api Youtube Player
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
window.onYouTubeIframeAPIReady = function() {
// function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
}
</script>
</body>
/*
Con querySelectorAll haremos un alcance más específico
el selector usado aquí signfica simplemente:
"selecciona todos los elementos de tipo button
que tengan la clase btn-Editar"
Significa que otros botones quedarán aislados de esta escucha
así como otros elementos que tengan esa clase, pero no sean button
*/
var editButtons = document.querySelectorAll('button.btn-Play');
/*
A los elementos alcanzados por el criterio antes indicado
le asignamos un listener...
Significa que el click en cualquiera de esos elementos
ejecutará el código contenido en la función
en este caso recuperar el data-id
*/
editButtons.forEach(function(item, idx) {
item.addEventListener('click', function() {
/*
Usaremos la forma que existe para leer los atributos data
que es dataset
*/
//console.log(item.dataset.id);
Player(item.dataset.id);
});
});
<!-- Reproductor Youtube -->
<div id='player'></div>
<button class="btn-Play" data-id="n7l1oAYRThQ">Video 1</button>
<button class="btn-Play" data-id="G3P1IJaY6AA">Video 2</button>
<button class="btn-Play" data-id="353B-kOxWz4">Video 3</button>
<script>
function Player(id) {
alert(id);
// Api Youtube Player
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
window.onYouTubeIframeAPIReady = function() {
// function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
}
</script>
I would also like to redirect when each button is onclicked to go to the player since it is loaded above ( <div id='player'></div>
).
Then, when using onlick to play the videos, is there an option to start video number 1 on page load?
The API doc says that you can call a new video using Row functions . You therefore need to modify the code a bit, passing the video ID to a method
loadVideoById()
that will take care of stopping the video that may be playing and starting the new one.Edit 1
To set a default video, you could have its id loaded (in this case I use a
input
hidden one with which it will be the default id), retrieve it in the variablepreviewID
and pass that variable as a parameter when creating the player.JS
HTML
Edit 2: Change the buttons for images
Youtube allows you to access video images through a URL like this
http://i.ytimg.com/vi/VIDEO-ID/0.jpg
, you just have to change itVIDEO-ID
to the video ID. The code may be more elegant if you put something like this:The videos would be displayed when you click on each image and you don't have to change anything in the Javascript code.
For more details about this possibility of obtaining thumbnails of the videos, you can consult this question and its answers.
@deprecated
The only annoyance here is that from the outset it shows you a black screen with an error message (because a blank videoid is passed to it the first time it is created). I was looking in the API if there was a way to call the iframe in black or something but I didn't find anything about it. But surely there will be some way to solve this. An interesting option would be to start with a video by default, but I don't know if that would apply to your context.