YouTubeプレーヤーAPIを使ってYouTubeを複数設置してみます。
埋め込みはすぐできたのですが、onPlayerReadyで対象がどのプレーヤーなのか判別するのに手間取りました。
サンプルコード
HTML
<div id="sample01"></div> <div id="sample02"></div> <div id="sample03"></div> <div id="sample04"></div>
JavaScript
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 ytPlayer = [];
// プレーヤーのサイズ
var ytWidth = 640;
var ytHeight = 390;
// 各動画情報
var ytData = [
{
id: 'NcgBHHMbSGg',
area: 'sample01'
}, {
id: 'wbqOCoBkGvg',
area: 'sample02'
}, {
id: 'idIHKr4GvPY',
area: 'sample03'
}, {
id: 'ke8aMAvP7pk',
area: 'sample04'
}
];
// 各プレーヤーの埋め込み
function onYouTubeIframeAPIReady() {
for(var i = 0; i < ytData.length; i++) {
ytPlayer[i] = new YT.Player(ytData[i]['area'], {
width: ytWidth,
height: ytHeight,
videoId: ytData[i]['id'],
playerVars: {
rel: 0
},
events: {
'onReady': onPlayerReady
}
});
}
}
// 各プレーヤー準備完了後の処理
function onPlayerReady(e) {
for (var i = 0; i < ytData.length; i++) {
if(e.target.getIframe().id == ytData[i]['area']) {
console.log(ytData[i]['area'] + 'のプレーヤー準備完了しました。');
}
};
}
YouTubeプレーヤーAPIでYouTubeを複数設置するデモページ
onPlayerReady関数内で対象がどのプレーヤーなのか判別したかったので、getIframe()でDOMノードを取得して、さらにそこからidを取得するようにしています。
| player.getIframe() | 対象プレーヤーのDOMノードを返す。 |
|---|---|
| player.getVideoUrl() | 対象プレーヤーの YouTube.com URLを返す。 |
| player.getVideoEmbedCode() | 対象プレーヤーの埋め込みコードを返す。 |
【参考サイト】
コメントが承認されるまで時間がかかります。