YouTube Player APIを使用してモーダルを閉じた時にモーダル内で再生中のYouTube動画を一時停止をさせる方法(iframeタグを使用)のデモページ

※デベロッパーツール等でソースコードをご確認ください(Please check using Developer tools)

マイナビAGENT

CLICK

スポンサーリンク

CSS

.wrap {
  margin: 50px auto 0;
  text-align: center;
}

.play {
  display: inline-block;
  cursor: pointer;
  font-size: 40px;
  font-weight: bold;
}

.movie-modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  background-color: rgba(000, 000, 000, 0.96);
  pointer-events: none;
  transition: all 0.5s;
  z-index: 10;
}
.movie-modal.active {
  opacity: 1;
  pointer-events: all;
}

.modal-box {
  position: relative;
  max-width: 600px;
  width: 100%;
  height: 100%;
  margin: 0 auto;
  z-index: 1;
}

.modal-inner {
  position: absolute;
  top: 50%;
  width: 100%;
  transform: translate(0, -50%);
}

.movie {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%;
}

.movie iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

#close {
  position: absolute;
  right: 0;
  top: -50px;
  font-size: 50px;
  cursor: pointer;
  z-index: 100;
  color: #fff;
}

#overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

@media screen and (max-width:640px){
  .wrap {
    width: 100%;
  }
}
  

JavaScript

$(function(){
  $(".play").on("click",function(){
    $(".movie-modal").addClass("active");
    $("html").css({"overflow-y":"hidden"});
    return false;
  });
  $("#close,#overlay").on("click",function(){
    $(".movie-modal").removeClass("active");
    $("html").css({"overflow-y":"auto"});
  });
});

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 player;
function onYouTubeIframeAPIReady() {
player = new YT.Player("player",{
});
}
var ovPause = document.getElementById('overlay');
ovPause.addEventListener('click', function() {
  player.pauseVideo();
});
var btnPause = document.getElementById('close');
btnPause.addEventListener('click', function() {
  player.pauseVideo();
});