LoginSignup
6
5

More than 5 years have passed since last update.

[javascript]モーダルを作成してみた

Posted at

やったこと

フロントエンドエンジニアとして働いてはいるものの、あまりjsに触ってこなかった自分が
最近jsを触ってやったことを紹介したいと思います。
今回はモーダルを作成したのでこちらを紹介させて頂きます。

コード

class名など結構、適当に書いたので書くときはちゃんと考えて書いた方がいいかもしれません。

    <div class="main">
      <button type="button" id="main_button">ボタンです</button>
      <div class="content1">
        <p>テキストテキストテキストテキストテキストテキスト</p>
      </div>
      <div class="content2">
        <p>テキストテキストテキストテキストテキストテキスト</p>
      </div>
      <div class="content3">
        <p>テキストテキストテキストテキストテキストテキスト</p>
      </div>
      <div class="content4">
        <p>テキストテキストテキストテキストテキストテキスト</p>
      </div>
      <div class="content5">
        <p>テキストテキストテキストテキストテキストテキスト</p>
      </div>
    </div>

    <div class="modal">
      <div class="modal_wrapper"></div>
      <div class="modal_content">
        <p>テキスト</p>
      </div>
    </div>
      .main {
        height: 3000px;
        background-color: #ff0000;
        text-align: center;
      }
      .content1, .content2, .content3, .content4, .content5 {
        width: 600px;
        height: 400px;
        background-color: #0000ff;
        margin: 30px auto;
        color: #ffffff;
      }

      .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }
      .modal_wrapper {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
      }
      .modal_content {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          color: #ffffff;
          font-size: 30px;
          display: flex;
          justify-content: center;
          align-items: center;
      }
window.addEventListener('load', function() {
  const $button = document.getElementById('main_button');
  const $modal = document.getElementsByClassName('modal');

  $button.addEventListener('click', function() {
    $modal[0].style.display="block";
  });

  $modal[0].addEventListener('click', function() {
    $modal[0].style.display="none";
  });

  const windowHeight = window.innerHeight;
  $modal[0].style.height = windowHeight + 'px';

});

とりあえずこれだけでいけました。
これはhtmlの方に適当なボタンを設置して押したらモーダルで文言が出るような仕組みにしてます。

6
5
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
6
5