While making this blog I encountered a problem that seemed to have sloppy solutions at best. Changing the page’s title tag during htmx requests.
After doing some quick research I concluded that I could either use some form of out-of-band swaps or create a custom extension to handle this behavior how I prefer to have it handled.
The idea of the extension is very simple. If a specific header on the response exists(HX-Title
), update the page title to the value of that header, otherwise, do nothing.
So let’s see code!
htmx.title.js
:
1(function() {
2 htmx.defineExtension("title", {
3 onEvent: function (name, evt) {
4 if (name === "htmx:afterSettle") {
5 const titleHeader = evt.detail.xhr.getResponseHeader("HX-Title");
6 if (!!titleHeader) {
7 document.title = titleHeader;
8 }
9 }
10 }
11 });
12})();
You can activate the extension by adding title
to the hx-ext
attribute on the body tag of your page.
For a more in-depth look, you can check out the repo for my blog here on GitHub!