Search code examples
javascripthtmlcssbulmacodepen

Modal javascript code only works temporarily?


Anyone can guess why this short script isn't working?

Oddly enough, I only got it to work on CodePen, and only temporarily (i.e. if it will work in the preview for a bit after you save and then stop)

https://gist.github.com/IlanVivanco/694a19541ba58590e149df9cdccef4aa

https://codepen.io/alain_invasion/pen/mdmXPgq

BulmaModal.js

class BulmaModal {
   constructor(modalButton) {
     const target = modalButton.dataset.target;

     if (target) {
       this.button = modalButton;
       this.modal = document.querySelector(target);
       this.html = document.querySelector("html");

       this.openEvent();
       this.closeEvents();
     }
   }

   show() {
     this.modal.classList.toggle("is-active");
     this.html.classList.add("is-clipped");

     this.onShow();
   }

   close() {
     this.modal.classList.toggle("is-active");
     this.html.classList.toggle("is-clipped");

     this.onClose();
   }

   openEvent() {
     this.button.addEventListener("click", (e) => {
       e.preventDefault();
       this.show();
     });
   }

   closeEvents() {
     const closeElements = this.modal.querySelectorAll(".modal-background, .modal-close");

     closeElements.forEach((element) => {
       element.addEventListener("click", (e) => {
         e.preventDefault();
         this.close();
       });
     });
   }

   onShow() {
     const event = new Event("modal:show");
     this.modal.dispatchEvent(event);
   }

   onClose() {
     const event = new Event("modal:close");
     this.modal.dispatchEvent(event);
   }
 }

 export default BulmaModal;

index.html

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.2/css/bulma.min.css">
<button class="modal-button" data-toggle="modal" data-target="#video">Open modal</button>

<div class="modal" id="video">
  <div class="modal-background"></div>
  <div class="modal-content">
    Lorem ipsum dolor sit amet
  </div>
  <button class="modal-close is-large" aria-label="close"></button>
</div>

<script src="./main.js" type="module"></script>

main.js

import BulmaModal from './BulmaModal.js'

const modals = document.querySelectorAll("[data-toggle='modal']");
modals.forEach((modal) => new BulmaModal(modal));

/** show events */
document.querySelector(".modal").addEventListener("modal:show", (event) =>{ console.log(event) });

/** show events */
document.querySelector(".modal").addEventListener("modal:close", (event) =>{ console.log(event) });

Solution

  • If anyone has the same issue: javascript modules just don't work on a local PC or on CodePen. So if you find yourself in the same situation, the solution is either to work on a web server (either local or online) or edit the script to avoid modules altogether (which is what I did)