Modals & Dialogs
MediumOverlay dialogs with backdrop blur and smooth animations
Updated 2 days ago
Tested & Responsive
Live Demo
<button
class="px-6 py-3 bg-forest-600 hover:bg-forest-700 text-forest-50 font-medium rounded-lg transition-colors duration-200"
data-controller="modal"
data-action="click->modal#open"
>
Open Modal Demo
</button>
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["container", "backdrop", "panel"]
connect() {
// Bind the keydown event to close modal on Escape
this.boundKeydown = this.keydown.bind(this)
}
open() {
if (this.hasContainerTarget) {
this.containerTarget.classList.remove("hidden")
document.body.classList.add("overflow-hidden")
// Add event listener for Escape key
document.addEventListener("keydown", this.boundKeydown)
// Focus management for accessibility
setTimeout(() => {
const focusableElement = this.containerTarget.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')
if (focusableElement) {
focusableElement.focus()
}
}, 100)
}
}
close() {
if (this.hasContainerTarget) {
this.containerTarget.classList.add("hidden")
document.body.classList.remove("overflow-hidden")
// Remove event listener
document.removeEventListener("keydown", this.boundKeydown)
}
}
// Close modal when clicking the backdrop
closeOnBackdrop(event) {
if (event.target === event.currentTarget) {
this.close()
}
}
// Close modal when pressing Escape
keydown(event) {
if (event.key === "Escape") {
this.close()
}
}
disconnect() {
document.removeEventListener("keydown", this.boundKeydown)
document.body.classList.remove("overflow-hidden")
}
}
Installation & Usage
1
Copy the ERB template
Copy the ERB code from the template tab above and paste it into your Rails view file.
2
Add the Stimulus controller
Create the Stimulus controller file in your JavaScript controllers directory.