Reputation: 420
I am using the YouTube JavaScript API to control the YouTube Players on my page. The Goal is to stop all currently playing Videos, when i start a new one.
Already going through the struggle of different kinds of YouTube Embed options, like single videos, playlist etc. i came to a question, which would make my life much more easier.
Initializing the players like this:
// Array to store YTplayers
var YTplayers = [];
// Select all YouTube iframes
var YTembeds = $('iframe[src*="youtube.com"], iframe[src*="youtube-nocookie.com"]');
YTEmbeds.each(function(i) {
iframe = $(this);
// Generate and add the unique identifier for the current iframe
var iframe_id = "iframe-youtube-" + i;
iframe .attr("id", iframe_id);
// Check if src already has a "?" and add "?" or "&" accordingly
// then add the necessary "enablejsapi=1" option and update the src.
var url = iframe .attr("src");
url += url.indexOf("?") == -1 ? "?" : "&";
iframe.attr("src", url + "enablejsapi=1");
// Create YouTube Player Object with custom eventListener
player = new YT.Player( iframe_id, {
events: {
'onStateChange': onYouTubePlayerStateChange
}
});
// Store the new player element and the iframe_id together
YTplayers.push({
"id" : iframe_id,
"player" : player
});
});
Now inside the function "onYouTubePlayerStateChange", there i have access to the "event"-object, but there is only information about the embedded youTube-Player and nothing ... i can find ... about the surrounding iframe-object.
So the question is: How can i get access to the iframe-id, which got used to initialize the YT-Player, INSIDE the function "onYouTubePlayerStateChange"?
PS: For now i have used the video_id, or playlist_id, which are stored in the event-object to identify the iframe. But then when i have two players with the same YT-video_id, although this case is unlikely, they will both keep running.
Thanks for any effort to help me with this problem.
Kindly,
Max K
Upvotes: 2
Views: 4512
Reputation: 3651
as @Dmitro mentioned you can use getIframe()
method, solution without jQuery:
event.target.getIframe().id
Upvotes: 3
Reputation: 1549
Another way to get id of iframe:
jQuery(event.target.getIframe()).attr('id')
Upvotes: 3
Reputation: 420
So finally i found a pretty simple solution, to pass an argument to the eventListener function by wrapping it in with another function, and passing the default "event" object PLUS the customly defined iframe_id, like so:
player = new YT.Player( iframe_id, {
events: {
'onStateChange': function(event){
onYouTubePlayerStateChange(event, iframe_id);
}
}
});
Now, in the "onYouTubePlayerStateChange" function you have access to both the youtube-event-object with the current state of the player and the iframe_id that defines which player it actually is.
Cheers!
Upvotes: 8