多くの CSS ツールキットには、モーダルダイアログを作成するためのスタイル (と JavaScript) が含まれます。このサンプルは、HTMX を使用して UIKit を使用した動的ダイアログを表示する方法、および JavaScript をほとんどまたは全く使用せずにアニメーションスタイルをトリガーする方法を示します。
モーダルをトリガーするボタンと、モーダルが読み込まれるマークアップの下部に DIV を使用します
これは、HTMX を使用して UIKit を使用してモーダルダイアログをリモートロードする例です。この例では、スクリプティング言語で htmx と他のライブラリをどのように一緒に組み合わせることができるかを明確に示すために Hyperscript を使用します。
<button
id="showButton"
hx-get="/uikit-modal.html"
hx-target="#modals-here"
class="uk-button uk-button-primary"
_="on htmx:afterOnLoad wait 10ms then add .uk-open to #modal">Open Modal</button>
<div id="modals-here"></div>
このボタンは、クリック時に GET
リクエストを /uikit-modal.html
に使用します。このファイルの内容は、#modals-here
DIV の下に DOM に追加されます。
標準の UIKit JavaScript ライブラリを使用する代わりに、Hyperscript を少し使用して、UIKit のスムーズなアニメーションをトリガーしています。UIKit のアニメーションが正しく実行されるように 10 ミリ秒遅延しています。
最後に、サーバーは UIKit の標準モーダルを少し変更したバージョンで応答します
<div id="modal" class="uk-modal" style="display:block;">
<div class="uk-modal-dialog uk-modal-body">
<h2 class="uk-modal-title">Modal Dialog</h2>
<p>This modal dialog was loaded dynamically by HTMX.</p>
<form _="on submit take .uk-open from #modal">
<div class="uk-margin">
<input class="uk-input" placeholder="What is Your Name?">
</div>
<button type="button" class="uk-button uk-button-primary">Save Changes</button>
<button
id="cancelButton"
type="button"
class="uk-button uk-button-default"
_="on click take .uk-open from #modal wait 200ms then remove #modal">Close</button>
</form>
</div>
</div>
ボタンとフォームの Hyperscript は、このダイアログが完了またはキャンセルされたときにアニメーションをトリガーします。この Hyperscript を使用しなかった場合でも、モーダルは機能しますが、UIKit のフェードインアニメーションはトリガーされません。
もちろん、この作業には Hyperscript ではなく JavaScript を使用することもできますが、コードははるかに多くなります
// This triggers the fade-in animation when a modal dialog is loaded and displayed
window.document.getElementById("showButton").addEventListener("htmx:afterOnLoad", function() {
setTimeout(function(){
window.document.getElementById("modal").classList.add("uk-open")
}, 10)
})
// This triggers the fade-out animation when the modal is closed.
window.document.getElementById("cancelButton").addEventListener("click", function() {
window.document.getElementById("modal").classList.remove("uk-open")
setTimeout(function(){
window.document.getElementById("modals-here").innerHTML = ""
,200
})
})