LoginSignup
3
10

More than 5 years have passed since last update.

Colorboxで開いたYouTube動画を再生終了後に自動で閉じる方法

Last updated at Posted at 2016-12-28

やりたいこと

  • ページを表示したときにyoutubeをモーダルで開く
  • モーダルはcolorboxを使用
  • youtubeの再生が終わったら自動で閉じる
  • 2度目以降に再生したら自動で閉じないようにする

実装

jQueryとColorboxを読み込みます。

モーダルの表示にはColorboxを使用します。
下記よりダウンロードしたファイル群を読み込みます。
https://github.com/jackmoore/colorbox

Colorboxの使い方は割愛します。

index.html、modal.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/jquery.colorbox.js"></script>

<link rel="stylesheet" type="text/css" href="css/colorbox.css" />

親側のhtmlには下記を記述します。

index.html
<script>
$(function(){
    $(".iframe").colorbox({iframe:true, open:true,innerWidth:"980", innerHeight:"620", scrolling:false});
});
</script>

<a href="modal.html" class="iframe">Movie Open</a>

モーダル側のhtmlには下記を記述します。

modal.html
<script>

    // IFrame Player API の読み込み
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    // YouTubeの埋め込み
    function onYouTubeIframeAPIReady() {
        ytPlayer = new YT.Player(
            'player', // 埋め込む場所の指定
            {
                width: 976, // プレーヤーの幅
                height: 549, // プレーヤーの高さ
                videoId: 'bHQqvYy5KYo', // YouTubeのID
                playerVars: {
                    rel: 0, // 再生終了後に関連動画を表示するかどうか設定
                    autoplay: 1 // 自動再生するかどうか設定
                },
                // イベントの設定
                events: {
                    'onStateChange': onPlayerStateChange // プレーヤーの状態が変更されたときに実行
                }
            }
        );
    }

    // プレーヤーの状態が変更されたとき
    function onPlayerStateChange(event) {
        // 現在のプレーヤーの状態を取得
        var ytStatus = event.data;
        // 再生終了したとき
        if (ytStatus == YT.PlayerState.ENDED) {
            parent.$.colorbox.close();
        }
    }
</script>

<div id="player"></div>

2度目以降は自動で閉じないようにする

cookieを使って処理します。
プラグイン「jquery.cookie.js」の読み込みを追加。

プラグインは下記よりダウンロードします。
https://github.com/carhartl/jquery-cookie

jQueryの読み込みよりも後に追加する。

index.html、modal.html
<script src="js/jquery.cookie.js"></script>

onPlayerStateChangeの内容を書き換え。

modal.html
    var loadMovieKey = $.cookie("loadMovieKey");

    // プレーヤーの状態が変更されたとき
    function onPlayerStateChange(event) {
        // 現在のプレーヤーの状態を取得
        var ytStatus = event.data;
        // 再生終了したとき
        if (ytStatus == YT.PlayerState.ENDED) {
            if(loadMovieKey != "played"){
                $.cookie("loadMovieKey", "played", { path: "/" });
                parent.$.colorbox.close();
            }
        }
    }

参考

3
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
10