-
-
Save mybigman/8deab0deb6b08accdb68083c64e39145 to your computer and use it in GitHub Desktop.
Server sent toasts in HTMX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
htmx.on("htmx:afterRequest", (e) => { | |
const toast = e.detail.xhr.getResponseHeader('HX-Toast'); | |
// Can be expanded with HX-Toast-Type or similar to specify success, warning, info, etc | |
if(toast) { | |
const el = document.createElement('span'); | |
el.innerText = toast; | |
el.style.position = 'fixed'; | |
el.style.top = '10px'; | |
// Right aligned: | |
// el.style.right = '10px'; | |
// or centered: | |
el.style.left = '50%'; | |
el.style.transform = 'translateX(-50%)'; | |
el.style.width = '300px'; | |
el.style.padding = '1rem'; | |
el.style.background = '#d20d0d'; | |
el.style.color = 'white'; | |
el.style.borderRadius = '8px'; | |
el.style.cursor = 'pointer'; | |
el.style.transition = 'opacity 400ms ease'; | |
el.style.opacity = 0; | |
document.body.append(el); | |
setTimeout(() => el.style.opacity = 1); | |
el.onclick = () => el.style.opacity = 0; | |
const delay = 4000; | |
setTimeout(() => el.style.opacity = 0, delay); | |
setTimeout(() => el.remove(), delay + 1000); | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add this function to your context and use via `c.SendToast("...")` | |
func (c *CustomContext) SendToast(message string) error { | |
c.Response().Header().Set("HX-Toast", message) | |
c.Response().Header().Set("HX-Reswap", "none") | |
return c.Render(http.StatusOK, "toast-fallback", message) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function htmxSendError(ctx: Context, msg: string) { | |
ctx.response.headers.set('HX-Toast', msg); | |
ctx.response.headers.set('HX-Retarget', 'none'); | |
} | |
appRouter.post("/form", checkAuth(), async (ctx) => { | |
const fd = await ctx.request.body.formData(); | |
const date = fd.get('date')?.toString(); | |
if (!date) return htmxSendError(ctx, 'Invalid date'); | |
ctx.response.body = render(<h1>Success!!</h1>); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment