Intro to HTMX: Dynamic HTML without JavaScript

By Akash
on 29-09-2023 10:43 AM

HTMX is the HTML extension syntax that replaces JavaScript with simple markup. It could change the course of web development.

HTMX lets you use an extended HTML syntax instead of JavaScript to achieve interactivity. HTMX gives you HTTP interactions directly in the markup, and it supports many other interactive needs without resorting to JavaScript. It’s an interesting idea that could end up influencing the way web front-ends work. Let’s see how HTMX is used and what makes it so compelling.HTMX has been around for some time, but it has been a bit of a sleeper project. Its recent acceptance into the GitHub Accelerator may change all that. The basic idea is to take common use cases that require boilerplate JavaScript-and-HTML interactions and just use an HTML syntax, without the JavaScript. Many interactions become declarative with HTMX.This already sounds promising, doesn’t it? Every web developer knows there are many common boilerplate cases. Carson Gross, the creator of HTMX, says he’s hoping to “complete HTML as a hypertext, increasing its expressiveness enough to make it a competitive alternative for more advanced, modern web applications.”To get a quick taste, see this HTMX demo. Basically, we click on a button to enable editing the fields on the user object. The data is actually PUT into a back-end endpoint. You can see the demo in Figure 1—notice the network interaction in the bottom frame after you click Show.
Normally, this all would require JavaScript of some kind, no matter what framework you were using. HTMX turns the interaction into two chunks of markup: one for the display UI and one for the edit UI, as shown in Listing 1.If you look at the markup in Listing 1, it is easy to see what is happening: the hx-swap property provides the HTML for the div before it is edited, and outerHTML tells the framework how it relates to the dynamic content inside. The editable version arrives as a form element that contains the x-put property, which identifies the PUT HTML method and what endpoint to use.