ES2015でポップアップのテンプレートを作ってみた!

今回はJavaScriptで簡単なポップアップのテンプレートを作ってみたのでサンプルコードを載せておきます。

<!DOCTYPE html>
<html lang='ja'>
<head>
   <meta charset='UTF-8'>
   <meta name='viewport' content='width=device-width, initial-scale=1.0'>
   <meta http-equiv='X-UA-Compatible' content='ie=edge'>
   <title>ポップアップのサンプル</title>
   <link rel='stylesheet' href='css/style.css'>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js"></script>
</head>
<body>
    <button class="popupButton" id="js-clickEl">クリックする要素</button>
    <div class='popup' id="js-popup">
        <div class='popup_content'>
            <p class='popup_content_closeButton' id="js-popupCloseButton">X</p>
            <div class='popup_content_description'>何か文言が入ります</div>
        <div>
    </div>
    <script src="js/Popup.js"></script>
</body>
</html>
.popupButton {
    border: none;
    background: #323232;
    color: #fff;
    padding: 20px;
    border-radius: 33px;
    cursor: pointer;
}
.popup {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(5,5,5,0.8);
    opacity: 0;
    transition:all .3s;
    transform: scale(0);
}

.popup.is-active {
    transform: scale(1);
    opacity: 1;
}

.popup_content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    width: 400px;
    height: 360px;
    padding: 30px;
}

.popup_content_closeButton {
    cursor: pointer;
    text-align: right;
}

.popup_content_description {
    margin-top: 30px;
}
class PopUp {
    constructor(clickEl, popupEl, closeEl){
        this.clickEl = document.getElementById(clickEl)
        this.popupEl = document.getElementById(popupEl)
        this.closeEl = document.getElementById(closeEl)
    }
    setEventListener(){
        this.clickEl.addEventListener("click", this.displayPopup.bind(this));
        this.closeEl.addEventListener("click", this.closePopup.bind(this));
    }
    displayPopup(){
    this.popupEl.classList.add("is-active")
    }
    closePopup(){
        this.popupEl.classList.remove("is-active")
    }
}
const simplePopup = new PopUp('js-clickEl', "js-popup", "js-popupCloseButton");
simplePopup.setEventListener();

このPopupクラスを使って初期化した後の引数に対象となる要素のIDを入れればデザインの違うポップアップにも対応できます!

是非使ってみてください!