Skip to main content

Modal

By default, when the modal opens, the first focusable element receives focus. This is useful for a <form> within a modal where the first field should already have focus. The focusOnFirstFocusable option can be used to disable this behavior.

The focus is trapped within the modal, allowing navigation with Tab key forward and Shift+Tab key backward.

Multiple modals on the same page are also possible. Just make sure that the ID of your modal and the data-fn-target attribute of your button are unique.

Demo

Installation

Import the function into the JavaScript file of your project

import { Modal } from "@overdog/fn"

Create and initialize an instance

new Modal("#my-modal-button", {
  // options goes here
}).init()

Add the Tailwind variants to the plugins section of your config file.

If you are using multiple elements from Overdog FN that require the same variants, you only need to add them once. You can also modify the data attributes added to each function using the attributes parameter {}.

module.exports = {
   // ...
   plugins: [
      plugin(function ({ addVariant }) {
         addVariant("is-open", "&[data-fn-is-open]")
         addVariant("parent-is-open", "[data-fn-is-open] &")
      })
   ]
}

Twig template Code


{# place your overlay anywhere before the closing body tag #}
<div 
   id="overlay" 
   data-fn-overlay 
   class="fixed z-50 inset-0 hidden bg-slate-900/50 opacity-0 transition-opacity is-open:opacity-100">
</div>

{# open button #}
<button 
   data-fn-modal-button
   data-fn-target="modal-1"
   id="my-modal-button" {# selector for your JS instance - you can use a CSS class too #}
   class="bg-slate-800 px-8 py-4 inline-block text-white is-open:bg-slate-900"
   aria-haspopup="dialog" 
   aria-expanded="false">
   Open modal #1
</button>

{# modal #}
<div 
   class="fixed z-[1000] inset-1/2 hidden w-[600px] max-w-[80%] h-[400px] p-8 
          bg-white transform -translate-x-1/2 -translate-y-1/2 drop-shadow-md
          is-open:block"
   data-fn-modal-box
   id="modal-1"
   role="dialog" 
   aria-label="Modal 1" 
   aria-modal="true"
>
   {# close button #}
   <button data-fn-modal-close class="w-12 h-12 bg-gray-300 rounded-full mb-quarter">x</button>
  {# content #}
  <p>Press escape, click on the body overlay or on the close button to get rid of me!</p>
</div>

Options