yuheijotaki.com

YouTube APIで複数動画

ちょこっとやったやつのメモ

HTML

<button class="js-player-start" data-movie="0">再生</button>
<button class="js-player-stop" data-movie="0">停止</button>
<div id="player_0"></div>

<button class="js-player-start" data-movie="1">再生</button>
<button class="js-player-stop" data-movie="1">停止</button>
<div id="player_1"></div>

JavaScript(jQuery)

var tag = document.createElement('script')
tag.src = "//www.youtube.com/iframe_api"
var firstScriptTag = document.getElementsByTagName('script')[0]
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)

// make player array
var players = new Array()

function onYouTubeIframeAPIReady() {
  players[0] = new YT.Player('player_0', {
    height: '100%',
    width: '100%',
    videoId: 'IqKz0SfHaqI'
  })
  players[1] = new YT.Player('player_1', {
    height: '100%',
    width: '100%',
    videoId: '-bNMq1Nxn5o'
  })
}

$(function () {
  // 再生
  $('.js-player-start').on('click', function(){
    const target = $(this).attr('data-movie')
    players[target].playVideo()
  })
  // 停止
  $('.js-player-stop').on('click', function(){
    const target = $(this).attr('data-movie')
    players[target].stopVideo()
  })
})

横幅をレスポンシブにするには、

  ...
    height: '100%',
    width: '100%',
  ...

とすればよい

YouTube Data API の概要
https://developers.google.com/youtube/v3/getting-started?hl=ja