Skip to content

Instantly share code, notes, and snippets.

@bjinwright
Created September 28, 2023 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjinwright/69e4ba008fb8ad289598e8df61a757ee to your computer and use it in GitHub Desktop.
Save bjinwright/69e4ba008fb8ad289598e8df61a757ee to your computer and use it in GitHub Desktop.
Ajax Dialog Web Component
class AjaxDialog extends HTMLElement {
connectedCallback() {
// Store the original children (the slot content)
const originalChildren = this.innerHTML;
this.open = this.getAttribute('open') || false;
this.loaded = this.getAttribute('loaded') || false;
this.content = this.getAttribute('content') || '';
this.url = this.getAttribute('url') || '';
this.button_class = this.getAttribute('button-class') || 'bg-green-600 text-white';
this.dialog_class = this.getAttribute('dialog-class') || 'bg-white';
// Assemble the new content, keeping the original children
this.innerHTML = `
<div x-data="{ open: ${this.open}, loaded: ${this.loaded}, content: '${this.content}', url: '${this.url}' }" @open-changed.window="if ($event.detail.id === '${this.id}') { open = $event.detail.value; }" class="relative">
<button @click="open = !open" hx-get="${this.url}" hx-trigger="click once" hx-target="div.dialog-inner" class="${this.button_class} rounded-lg font-bold p-4">
<slot>${originalChildren}</slot>
</button>
<dialog id="mydialog" class="${this.dialog_class} ajax-modal p-0" x-bind:open="open" x-transition>
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="absolute top-0 right-0" @click="open = false">
<path d="M8.27273 0.727272L12.0909 7.5H12.2727L16.1364 0.727272H23.1818L16.2273 12.3636L23.4545 24H16.2273L12.2727 17.0909H12.0909L8.13636 24H0.954545L8.09091 12.3636L1.18182 0.727272H8.27273Z" fill="black"/>
</svg>
<div class="dialog-inner shadow-gray-600 shadow-2xl rounded-lg p-10 mt-10">
</div>
</dialog>
</div>
`;
}
}
customElements.define('ajax-dialog', AjaxDialog);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CarCamp UI</title>
<link rel="stylesheet" href="dist/style.css">
</head>
<body>
<div class="container mx-auto">
<h2 class="font-bold text-2xl py-6">Dialog Component</h2>
<ajax-dialog url="form.part.html" button-class="bg-blue-600 text-white" dialog-class="w-1/2">Change</ajax-dialog>
</div>
<script src="dist/alpine.js" defer></script>
<script src="dist/htmx.js"></script>
<script type="module" src="src/ajax-dialog.js"></script>
<script type="module" src="src/editor.js"></script>
<script type="module" src="src/button-menu.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment