【jQuery】slickでYouTube動画を埋め込んだスライダーを実装する方法(iframeタグを使用)のデモページ

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

マイナビAGENT

スポンサーリンク

無料で登録するだけで、最高5,000万円の損害賠償が付く!

CSS

.wrap {
  width: 640px;
  margin: 50px auto 0;
}

.slick li div {
  position: relative;
  width: 100%;
  padding-top: 56.25%;
}

.slick li div iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

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

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 players = {};
function onYouTubeIframeAPIReady() {
  $(".slick iframe").each(function(id) {
      var $iframe = $(this).get(0);
      if ($iframe) {
        players = new YT.Player($iframe, {
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }
  });
}
function onPlayerReady() {
  $('.slick').slick('slickPlay');
}
function onPlayerStateChange(obj) {
  if (obj.data == 1) {
    $('.slick').slick('slickPause');
  } else if (obj.data == 2) {
    $('.slick').slick('slickPlay');
  }
}

$(function(){
  $(".slick").on("beforeChange", function(event, slick) {
    var currentSlide, player, command;
    currentSlide = $(slick.$slider).find(".slick-current");
    player = currentSlide.find("iframe").get(0);
    command = {
      "event": "command",
      "func": "pauseVideo"
    };
    if ( player != undefined ) {
      player.contentWindow.postMessage(JSON.stringify(command), "*");
    }
  });
  $(".slick").slick({
    autoplay: false,
    arrows: false,
    dots: true,
    pauseOnFocus: false,
    pauseOnHover: true,
    pauseOnDotsHover: false,
    fade: true
  });
});