LoginSignup
15
12

More than 5 years have passed since last update.

【初心者向け】複数モーダルの設置方法

Posted at

モーダルを複数設置する場合、「modal01」「modal02」...とIDやClassを付与して設置するとコード量が増えてしまいますよね。
複数設置する場合はこのように書いてみましょう。

jQuery

// モーダルが複数ある場合
$(function () {
  // モーダルのボタンをクリックした時
  $('.modal_trigger .modal_btn').on('click', function() {
    var btnIndex = $(this).index(); // 何番目のモーダルボタンかを取得
    $('.modal_area .modal_box').eq(btnIndex).fadeIn(); // クリックしたモーダルボタンと同じ番目のモーダルを表示する
  });

  // ×やモーダルの背景をクリックした時
  $('.modal_close , .modal_bg').click(function(){
    $('.modal_box').fadeOut(); // モーダルを非表示にする
  });
});

Demo

モーダル複数設置

まとめ

同じページ内に複数のブロックで使用する可能性もありますので、Classで運用してあげると楽かなと思います。(遭遇する頻度は少ないと思いますが。。。)
モーダルだけではなく、複数あるものはまとめて書いてしまうと何かと楽です。
正しく怠けましょう。

15
12
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
15
12