This is a environment-agnostic backend for HTMX. It simply generates the HTMX response headers and provides a state object that contains information about the HTMX request.
import { HXHeaders } from "https://deno.land/x/backend_htmx/main.ts";
const reqHeaders = { "HX-Request": "true" };
const resHeaders = {};
const hx = new HXHeaders(reqHeaders, resHeaders);
console.log(hx.isHTMX); // true
hx.location("/new/url");
console.log(resHeaders); // { "HX-Location": "/new/url" }A boolean that is true if the request is an HTMX request.
Indicates that the request is via an element using hx-boost
true if the request is for history restoration after a miss in the local
history cache
The current URL of the browser
The user response to a HX-Prompt header
The ID of the element that is the target of the request
The ID of the element that triggered the request
The name of the element that triggered the request
The HX-Location header is used to tell the client to navigate to a new URL.
hx.location("/new/url");
// => { "HX-Location": "/new/url" }The HX-Push-Url header is used to tell the client to push a new URL to the
history stack.
hx.pushUrl("/new/url");
// => { "HX-Push-Url": "/new/url" }The HX-Replace-URL header is used to tell the client to replace the current
URL in the history stack.
hx.replaceUrl("/new/url");
// => { "HX-Replace-URL": "/new/url" }The HX-Redirect header is used to tell the client to redirect to a new URL.
hx.redirect("/new/url");
// => { "HX-Redirect": "/new/url" }The HX-Refresh header is used to tell the client to refresh the current page.
hx.refresh();
// => { "HX-Refresh": "true" }Allows you to specify how the response will be swapped. See hx-swap for possible values
See HX-Reswap for more information.
hx.reswap("innerHTML");
// => { "HX-Reswap": "innerHTML" }A CSS selector that updates the target of the content update to a different element on the page.
See HX-Retarget for more information.
hx.retarget("#my-element");
// => { "HX-Retarget": "#my-element" }The HX-Trigger header is used to tell the client to trigger an event on the
current page.
Trigger an event on the current page.
hx.trigger({ "my-event": "my message" });
// => { "HX-Trigger": '{"my-event": "my message"}' }Trigger an event on the current page after the page has settled.
hx.trigger({ "my-event": "my message" }, "afterswap");
// => { "HX-Trigger-After-Swap": '{"my-event": "my message"}' }Trigger an event on the current page after the page has settled.
hx.trigger({ "my-event": "my message" }, "aftersettle");
// => { "HX-Trigger-After-Settle": '{"my-event": "my message"}' }BSD-2