Answer the question
In order to leave comments, you need to log in
How to bind a button to each video in youtube API?
Hello.
I upload a video to the site through YouTube api, there is more than one video, I try to implement dynamic initialization.
Each video has its own "Play" and "Pause" buttons.
The problem is that when you click on any of the "Play" buttons, all videos start playing, but only the one that is in the same parent with the button should start playing.
Please tell me where the error is in the code and how to fix it, thanks!
code on codepen
Answer the question
In order to leave comments, you need to log in
function onYouTubeIframeAPIReady(){
$('.player').each(function(){
var playerId = $(this).attr('id');
var videoId = $(this).data('video');
var player;
var parent = $(this).parent();
player = new YT.Player(playerId, {
height: '360',
width: '640',
videoId: videoId,
events: {
'onReady': onPlayerReady.bind(parent),
'onStateChange': onPlayerStateChange
},
playerVars: {
showinfo:0,
// iv_load_policy:3,
rel:0
// controls:0
}
});
});
}
function onPlayerReady(event){
var target = event.target;
$('.play',this).click(function(){
target.playVideo();
$('body').addClass('v-play');
})
$('.pause', this).click(function(){
target.pauseVideo();
$('.v-play').removeClass('v-play');
})
//event.target.stopVideo();
}
function onPlayerStateChange(event){
var status = event.target.getPlayerState();
if(status == 0){
$('.v-play').removeClass('v-play');
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question