2022.05.27(更新日: 2023.03.24)
YouTubeのポップアップモーダルを作成する方法

はじめに
現在取り組んでいるLPコーディングで、YouTubeをポップアップモーダルで表示するという仕様を実現したので、それについて書いていきます。
「modaal」というモーダルウインドウのプラグインを使用しました。
デモサイト
デモサイトはこちらです。
デモサイトにある画像をクリックすると、以下のような、YouTubeのポップアップモーダルが表示されます。

以下の手順で作成しました。
- 必要なファイルの読み込み
- HTMLを書く
- JSを書く

手順1: 必要なファイルの読み込み
- CSS
- JS
CSS
headタグ内で、modaal.min.cssを読み込みました。
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/Modaal/0.4.4/css/modaal.min.css">
</head>
JS
bodyの閉じタグの直前で、modaal.min.jsとyoutube-popup.js(自作JSファイル)を読み込みました。
<script src="https://cdnjs.cloudflare.com/ajax/libs/Modaal/0.4.4/js/modaal.min.js"></script>
<script src="youtube-popup.js"></script>
</body>
手順2: HTMLを書く
リンク先にはYouTubeの埋め込みURLを指定しました。
<a href="https://www.youtube.com/embed/eXE3ejJeJfQ" class="video-open">
<img src="movie.png" alt="動画" class="movie__img"/>
</a>
YouTubeの埋め込みURLを取得する方法
YouTubeの埋め込みURLは、
埋め込みたいYouTube動画の「共有 → 埋め込む → 動画の埋め込み」から取得しました。



手順3: JSを書く
youtube-popup.js(自作JSファイル)で、modaalの処理をまとめた「youtube_modal」という関数を作成し、リンクのクラス名である「.video-open」を引数として渡しました。
function youtube_modal(trigger) {
$(trigger).modaal({
type: "video",
});
}
youtube_modal(".video-open");
これでリンクをクリックしたときに、モーダルが表示されるようになりました。

書籍の紹介
主にjQueryを使用したWEBサイトの動きについて網羅的に学べます。
今回のYouTubeのポップアップモーダルは、
書籍連動サイトのこちらのページを参考にしました。
投稿ID : 3421
コメントを残す