WEBデザインの勉強

初心者が1からWEBデザインを勉強するブログ。

YouTubeAPI サムネイルをクリックで動画を切り替える

デモ
http://efu.sakura.ne.jp/web/youtubeapi/index2.html

<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="UTF-8">
	<title>YouTube API サムネイルクリックで動画切替え</title>
	<link rel="stylesheet" href="css/style.css">
	<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
	<script src="js/script2.js"></script>
</head>
<body>
<div class="moviewrap"><div id="movie"></div></div>
<ul class="movielist">
		<li class="movielist__item" data-id="Aj1avSJ3Yhw"><img src="http://i.ytimg.com/vi/Aj1avSJ3Yhw/mqdefault.jpg" alt=""></li>
		<li class="movielist__item" data-id="lHuEGlAltVo"><img src="http://i.ytimg.com/vi/lHuEGlAltVo/mqdefault.jpg" alt=""></li>
		<li class="movielist__item" data-id="dX883Xkaw2E"><img src="http://i.ytimg.com/vi/dX883Xkaw2E/mqdefault.jpg" alt=""></li>
		<li class="movielist__item" data-id="lLhFPa_oBsc"><img src="http://i.ytimg.com/vi/lLhFPa_oBsc/mqdefault.jpg" alt=""></li>
		<li class="movielist__item" data-id="txTvLEQAw9w"><img src="http://i.ytimg.com/vi/txTvLEQAw9w/mqdefault.jpg" alt=""></li>
	</ul>
</body>
</html>
.moviewrap {
  width: 960px;
  margin: 50px auto 20px;
}

.movielist {
  font-size: 0;
  text-align: center;
}

.movielist .movielist__item {
  display: inline-block;
  width: 150px;
  margin-left: 10px;
}

.movielist .movielist__item img {
  width: 100%;
}

.movielist .movielist__item:first-child {
  margin-left: 0;
}
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

function onYouTubeIframeAPIReady() {
  Player = new YT.Player(
    'movie',
    {
      width: 960,
      height: 540,
      videoId: 'Aj1avSJ3Yhw',
      events: {
      },
      playerVars: {
        rel: 0,
        controls: 0,
        showinfo: 0,
      }
    }
    );
}

$(function(){
  $('.movielist__item').on('click', function(){
    var videoId = $(this).attr("data-id");
    Player.cueVideoById(videoId);
    //オート再生
    // Player.loadVideoById(videoId);
  });
});

関連記事
mmmmofu.hatenablog.com

mmmmofu.hatenablog.com