Skip to content

Instantly share code, notes, and snippets.

@maekoos
Last active July 18, 2024 22:04
Show Gist options
  • Save maekoos/886d5b7a79277355eb072db1f894b12d to your computer and use it in GitHub Desktop.
Save maekoos/886d5b7a79277355eb072db1f894b12d to your computer and use it in GitHub Desktop.
Server sent toasts in HTMX
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);
}
})
// 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-Retarget", "none")
return c.Render(http.StatusOK, "toast-fallback", message)
}
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