シンプルなモーダルボタンを自力で実装しよう!

スポンサーリンク

はじめに

Webサイト上にポップアップのように表示できるモーダル。Bootstrapなどのフレームワークを用いれば、素早くきれいなモーダルを簡単に表示できます。

今回は、そのようなフレームワークを使用するまでもない場合、環境により使用できない場合を想定してHTMLとCSS、JavaScriptを用いてシンプルなモーダルを作成します。

コード作成

表示部作成

表示部では、モーダルを表示するためのボタンとモーダル内に表示する内容を記載します。モーダルの表示・非表示のためにonClickにて関数を実行します。関数は後述します。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>モーダル表示テスト</title>
    <script type="text/javascript" src="modal.js"></script>
    <link rel="stylesheet" type="text/css" href="modal.css" />
  </head>
  <body>
    <input type="button" value="モーダルを表示する" onClick="showModal()" />
    <div id="modal" class="modal" onClick="hideModal()">
      <div class="modal-content" onClick="ignoreParentModalClose(event)">
        <span id="modalCloseButton" onClick="hideModal()">×</span>
        ここがモーダル表示エリアです!
      </div>
    </div>
  </body>
</html>

モーダルデザイン部

デザイン用のCSSを作成します。画面構成としては、モーダル表示時の背景透過(div.modal)、コンテンツ表示部(div.modal-content)、閉じる(x)ボタン(#modalCloseButton)で構成されています。

/* モーダルウィンドウの背景(グレー)表示 */
div.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}
/* コンテンツ表示 */
div.modal-content {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  width: 300px;
  height: 100px;
  background-color: #fefefe;
  border: 1px solid #888888;
  border-radius: 10px;
}
/* 閉じる(X)ボタン表示 */
#modalCloseButton {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  top: -15px;
  right: -15px;
  font-size: 30px;
  font-weight: bold;
  cursor: pointer;
  color: #ffffff;
  width: 40px;
  height: 40px;
  background-color: #444444;
  border: #333333;
  border-radius: 50%;
}

表示・非表示コントロール部

モーダルの表示・非表示を制御するプログラムを記載します。モーダルのdisplayスタイルをblockまたはnoneとして表示・非表示を制御します。

/** モーダル表示 */
const showModal = () => {
  const modal = document.getElementById('modal');
  modal.style.display = 'block';
}

/** モーダル非表示 */
const hideModal = () => {
  const modal = document.getElementById('modal');
  modal.style.display = 'none';
}

/**
 * 親要素のモーダル非表示停止
 *
 * @param {Object} event 発生したクリックイベントオブジェクト
 */
const ignoreParentModalClose = (event) => {
  event.stopPropagation();
}

モーダルの枠外をクリックした場合の処理についてはwindow.clickaddEventListenerを使用する方法がよく紹介されていますが今回はstopPropagationを使用しました。

モーダルの内容を表示する要素をクリックした際に、クリックイベントを親要素に伝播しないようにします。そうすることで、親要素で指定しているonClick=”hideModal()”を実行しなくなるため内容をクリックした場合にはモーダルの非表示処理が行われなくなります。

親要素でクリック検知をしたい場合には使用できないので最初に紹介したほかの方法をお試しください。

動作イメージ

ボタンをクリックするとモーダルが表示されます。

× ここがモーダル表示エリアです!

これで簡単なモーダル表示が完成しました。

ポップアップが使えない場面や簡単な確認などに使用すると重宝します。今回作成したコードをいくつかカスタマイズすることでさらに幅広い表示を行うことができますので是非やってみてください!

コメント

タイトルとURLをコピーしました