ทำ Modal โดยไม่ใช้ Library

Web Development

ทำ Modal โดยไม่ใช้ Library

9 เดือนที่ผ่านมา

2 min read

Table of Contents

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Awesome Modal</title>
  </head>
  <body>
    <dialog id="awesome-modal">
      <p>
        You know what? You can do modal with native HTML DOM API without using
        any libraries. 🥳
      </p>
      <button id="hide-modal">Close</button>
    </dialog>
 
    <button id="show-modal">Show Modal</button>
 
    <script>
      const awesomeModal = document.getElementById("awesome-modal");
      const showModalButton = document.getElementById("show-modal");
      const cancelButton = document.getElementById("hide-modal");
 
      function openCheck(dialog) {
        if (dialog.open) {
          console.log("Dialog open");
        } else {
          console.log("Dialog closed");
        }
      }
 
      showModalButton.addEventListener("click", () => {
        awesomeModal.show();
      });
 
      cancelButton.addEventListener("click", () => {
        awesomeModal.close();
      });
    </script>
  </body>
</html>

Styling with TailwindCSS

มาลอง style ด้วย TailwindCSS

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Awesome Modal</title>
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body class="h-screen flex justify-center items-center">
    <dialog id="awesome-modal" class="w-1/2 h-1/2 bg-blue-50 border-blue-500 border-4 rounded-xl p-5">
      <p class="text-2xl mb-10">
        You know what? You can do modal with native HTML DOM API without using
        any libraries. 🥳
      </p>
      <button class="px-3 py-2 bg-blue-500 text-white rounded" id="hide-modal">Close</button>
    </dialog>
 
    <button class="px-3 py-2 bg-blue-500 text-white rounded" id="show-modal">Show Modal</button>
 
    <script>
      const awesomeModal = document.getElementById("awesome-modal");
      const showModalButton = document.getElementById("show-modal");
      const cancelButton = document.getElementById("hide-modal");
 
      function openCheck(dialog) {
        if (dialog.open) {
          console.log("Dialog open");
        } else {
          console.log("Dialog closed");
        }
      }
 
      showModalButton.addEventListener("click", () => {
        awesomeModal.show();
      });
 
      cancelButton.addEventListener("click", () => {
        awesomeModal.close();
      });
    </script>
  </body>
</html>

Result

Reference

Tags:

HTML TailwindCSS