Stimulus Modal Dialog
stimulus
Tailwind
This note is now deprecated.
Tailwind 4.1 offers Custom element Vanilla JS functionality that works out of the box for Rail and you don't need to figure out this with Stimulus anymore
more: https://tailwindcss.com/blog/vanilla-js-support-for-tailwind-plus
--------------------------
<dialog data-dialog-target="dialog" class="mx-auto bg-indigo-50 shadow p-5 rounded-md w-full md:w-3/4 lg:w-2/3 z-30 mt-12">
<!-- load search after modal is revealed/oppened -->
<%= turbo_frame_tag "search", src: search_path %>
</dialog>
<button
type="button"
data-action="click->dialog#open"
data-dialog-target="open"
class="flex gap-2 cursor-pointer ml-5 flex-shrink-0 rounded-full bg-white p-1 text-gray-400 hover:text-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
<div class="pointer-events-none">Search</div>
</button>
// app/javascript/controllers/dialog_controller.js
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="dialog"
export default class extends Controller {
static targets = [ "dialog", "open" ]
open() {
console.log(this.dialogTarget)
this.dialogTarget.show()
}
close() {
this.dialogTarget.close()
}
clickOutside(event) {
if (!this.dialogTarget.contains(event.target) && event.target != this.openTarget) {
this.close();
}
}
}