LoginSignup
12
7

More than 5 years have passed since last update.

jQueryで超簡単モーダル表示

Posted at

実装したいこと

indexでeach文で表示させてる記事の➕ボタンを押すと
モーダル表示出来るようにしたいです。
具体的にいうと、
image.png

これの➕ボタンを押すと

image.png

このようにモーダルが出てくるようにしたいです。

まずはビューを編集

index.html.haml
<i class="fa-plus">
</i>
<div class="modal-background">
  <div class="modal">
    <div class="escape">
           &times;
    </div>
  </div>
</div>

fa-plusは➕ボタンのことです。
modal-backgroundはモーダル表示させた時の後ろの
modalは表示させたいモーダルのことです。
escapeは❌ボタンのことです。

次にcssです。

cssを編集

.modal-background{
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
  text-align: center;
  display: none;
}

.modal{
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%,-50%);
  -webkit-transform : translate(-50%,-50%);
  transform : translate(-50%,-50%);
  background-color: $whitecolor;
  border-radius: 4px;
  width: 360px;
  min-height: 450px;
}

modal-backgroundのdisplay: none;がキモですね。
これにより、通常の画面ではモーダルが表示させないようにしてます。
➕ボタンを押したらjQueryでモーダルを表示させてやるって感じですね。

また、モーダル表示させたら基本的に背景の灰色は画面いっぱいにしてあげたい&下にスクロールした時にはみ出ないようにしたいので
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
をしてあげてます。
z-indexで、ボックスの重ね位置を手前にしています。

modalは、これは位置を決めているだけです。

jQueryをいじる

modal.js

$(document).on('turbolinks:load', function(){
  $(function(){

    $('.fa-plus').on('click', function(e){
      e.preventDefault();
      $(this).siblings().fadeIn();
    });

    $('.escape').on('click', function(e){
      e.preventDefault();
      $('.modal').fadeOut();
    });

  });
});

こんな感じですね。
fa-plus(➕ボタン)をクリックすると発火するようにしてます。
$('.modal').fadeIn();
でやればいいのでは?と思われるかもしれませんが、
今回は、each文で記事を一つずつ表示させてます。

もし、$('.modal').fadeIn();と書いてしまうと記事の分だけモーダルが表示されてしまいます(記事がもし100個あったら、モーダルも100個表示される)

これを防止するために
$(this)で他のfa-plusとは違うということを認識させて
$siblings()で兄弟要素であるmodalを取得してます。
そして、fadeInでmodal-backgroundのdisplay:noneを解除してあげてます。

終了!ありがとうございました!

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