Modal - H T M L

  • <dialog class = "modal"></dialog> => Body inside will be hidden by default
    • <form method = "dialog"> => Modal closes when clicked on submit button
  • <dialog open></dialog> => body is visible
  • JS Functions
    • modal.show()
    • modal.showModal() => Can't select background, Background becomes dark, Can be closed by esc
    • modal.close()
    • Closing Dialog when clicked on outside, We create another element which takes up the entire space of the dialog, which should receive clicks first
          dialog.addEventListener('click', (e) => {
              if (e.target === dialog) {
              dialog.close();
              }
          });
      
    • Prevent esc button function
          d.addEventListener('cancel', event => event.preventDefault());
      
    • Preventing scroll behind the dialog
          button.addEventListener('click', (event) => {
              dialog.showModal();
              document.body.style.overflow = 'hidden';
          });
          dialog.addEventListener('close', (event) => {
              document.body.style.overflow = '';
          });
      
  • CSS
    • Change Background
          .modal::backdrop {
              background: black;
              opacity: .4;
          }
      
Share: