Contents
Introduction
What is HTMX?
Why use HTMX?
Key Features of HTMX
Getting Started with HTMX
AJAX
HTMX Attributes and Use Cases
The hx-on
attribute
Resources for Learning HTMX
Introduction
JavaScript has long been the go-to language for creating interactive web pages. However, HTMX (Hypermedia.js) emerges as a lightweight alternative, offering a JavaScript-free approach to building modern web applications.
What is HTMX?
HTMX is a lightweight JavaScript library that empowers developers to create interactive web experiences without writing a single line of JavaScript code. It achieves this by extending HTML with new attributes that enable seamless communication between the browser and the server, allowing for dynamic updates and user interactions without the need for complex JavaScript frameworks.
Why Use HTMX?
HTMX offers several advantages over traditional JavaScript-based approaches:
Simplicity: HTMX leverages the familiarity of HTML, making it easier for developers of all skill levels to create interactive web pages.
Performance: HTMX applications are generally faster and more responsive as they avoid the overhead of parsing and executing JavaScript code.
Maintainability: HTMX code is more readable and maintainable compared to JavaScript-heavy applications.
Search Engine Optimization (SEO): HTMX applications adhere to standard HTML syntax, ensuring better search engine visibility and crawlability.
Key Features of HTMX
HTMX provides a range of powerful capabilities for building interactive web applications:
Asynchronous HTTP Requests: HTMX facilitates asynchronous HTTP requests to the server, enabling partial page updates without full reloads.
DOM Manipulation: HTMX empowers developers to manipulate the Document Object Model (DOM), adding, removing, and updating elements on the page.
Client-Side Routing: HTMX integrates a built-in client-side router, enabling single-page application (SPA) development.
WebSockets Support: HTMX supports WebSockets, enabling real-time communication between the client and the server.
Getting Started with HTMX
Using HTMX is straightforward:
Include the HTMX JavaScript library: Add the HTMX script tag to your HTML document's head section.
Utilize HTML attributes: Employ HTMX attributes on HTML elements to trigger HTTP requests, handle responses, and manipulate the DOM.
Structure your HTML: Organize your HTML content to define the areas that should be dynamically updated using HTMX.
Set up server-side routing: Configure your server-side framework to handle the routes triggered by HTMX requests.
AJAX
The core of HTMX is a set of attributes that allow you to issue AJAX requests directly from HTML. These attributes are:
-
hx-get
: Issues a GET request to the specified URL. -
hx-post
: Issues a POST request to the specified URL. -
hx-put
: Issues a PUT request to the specified URL. -
hx-patch
: Issues a PATCH request to the specified URL. -
hx-delete
: Issues a DELETE request to the specified URL.
In addition to these basic request-issuing attributes, HTMX also provides a number of other attributes that can be used to control the behavior of AJAX requests, such as:
-
hx-confirm
: Displays a confirmation prompt before the request is sent. -
hx-swap
: Specifies how the response from the request should be swapped into the DOM. -
hx-trigger
: Specifies which events should trigger the request. -
hx-vars
: Specifies additional data that should be sent with the request.
These attributes make it possible to create very powerful and flexible AJAX applications without writing any JavaScript code.
hx-get
The hx-get
attribute is used to issue a GET request to the specified URL. This is the default behavior for HTML links, so you can use it to create links that trigger AJAX requests instead of reloading the page.
Use cases:
- Loading data from the server
- Filtering data based on user input
- Updating a portion of the page without reloading the entire page
Example:
This code will fetch the /users
endpoint on the server and replace the current content of the page with the response.
HTMX Attributes and Use Cases
hx-post
The hx-post
attribute is used to issue a POST request to the specified URL. This is typically used to submit form data to the server.
Use cases:
- Submitting form data to the server
- Creating new records
- Updating existing records
Example:
This code will submit the form data to the /create-user
endpoint on the server.
hx-put
The hx-put
attribute is used to issue a PUT request to the specified URL. This is typically used to update existing records.
Use cases:
- Updating existing records
- Replacing existing resources
- Upserting data
Example:
This code will send a PUT request to the /update-user/1
endpoint on the server with the current user's data.
hx-patch
The hx-patch
attribute is used to issue a PATCH request to the specified URL. This is typically used to partially update existing records.
Use cases:
- Updating specific fields of an existing record
- Applying incremental changes to data
- Performing partial updates
Example:
This code will send a PATCH request to the /update-user/1
endpoint on the server with the updated email address for the current user.
hx-delete
The hx-delete
attribute is used to issue a DELETE request to the specified URL. This is typically used to delete records.
Use cases:
- Deleting records
- Removing resources
- Managing data integrity
Example:
This code will send a DELETE request to the /delete-user/1
endpoint on the server, which will delete the user with the ID of 1.
Projects
Simple Form
Let use HTMX to create a simple form that submits data to the server and updates the page without reloading
This code will submit the form data to the /submit endpoint on the server. The server will then return a fragment of HTML that contains a list of users. HTMX will automatically insert this fragment into the
Project 2
This code will display a modal dialog box with the message "Are you sure you want to delete your account?" before deleting the account. The user can click the "Delete My Account" button to delete their account, or they can click the "Cancel" button to cancel the deletion.
Here is a breakdown of the code:
- The
hx-confirm
attribute on the<div>
element specifies the text of the confirmation prompt. - The
hx-delete
attribute on the first button specifies the URL of the endpoint to call when the user clicks the button. - The
hx-put
attribute on the second button specifies the URL of the endpoint to call when the user clicks the button. - The
hx-confirm="unset"
attribute on the third button specifies that no confirmation prompt should be displayed when the user clicks the button. - The `hx-get="/" attribute on the third button specifies that the page should be reloaded when the user clicks the button.
The hx-on
attribute
The hx-on
attribute is a versatile tool in HTMX that allows developers to directly embed JavaScript code within HTML elements. It enables the execution of custom JavaScript functions in response to various events, such as clicks, form submissions, and DOM changes. This attribute simplifies event handling and eliminates the need for separate JavaScript files, making it a valuable addition to HTMX's capabilities.
Syntax and Usage:
The hx-on
attribute follows a straightforward syntax:
where:
<event>
represents the event to trigger the JavaScript function. Common events includeclick
,submit
,change
, andkeyup
.<JavaScript function>
is the inline JavaScript code that will be executed when the specified event occurs.
Use Cases:
The hx-on
attribute offers a range of use cases in HTMX development:
Handling Form Submissions: Attach custom JavaScript functions to form submissions to perform validation, process user input, or update the DOM dynamically.
Responding to User Actions: Capture user interactions, such as button clicks, and trigger JavaScript functions to handle specific actions or provide feedback.
Reacting to DOM Changes: Monitor changes in the DOM, such as input value modifications or element visibility changes, and execute JavaScript functions accordingly.
Enhancing User Experience: Implement interactive elements and animations using JavaScript functions triggered by user actions or DOM events.
Customizing HTMX Behavior: Modify the default behavior of HTMX attributes or extend their functionality using inline JavaScript functions.
Example:
Consider a scenario where you want to display a confirmation message before deleting an item:
The hx-on
attribute triggers the confirmDelete()
JavaScript function when the button is clicked. This function can display a confirmation message and return true
or false
to allow or prevent the deletion based on user confirmation.
The hx-on
attribute provides a convenient and powerful way to integrate JavaScript code into HTMX applications, enhancing their interactivity and customization without sacrificing the simplicity of HTMX syntax.
Resources for Learning HTMX
To delve deeper into HTMX, explore these valuable resources:
Official HTMX Documentation: https://htmx.org/docs/
HTMX GitHub Repository: https://github.com/bigskysoftware/hypermedia-systems
HTMX Community Forums: https://htmx.org/essays/hypermedia-friendly-scripting/
HTMX Tutorials and Articles: https://htmx.org/docs/
Embrace HTMX and discover a simpler, more performant way to build interactive web applications without relying heavily on JavaScript.
☕ Enjoyed this article? Support my work with a coffee: https://www.buymeacoffee.com/cqvuesleq
Also open for technical writing and frontend dev roles!
Top comments (40)
Then ask chatgpt na, must you bring your negative attitude here, this is a well researched content published after hours of work and practice. If you have something to contribute like experience, tips or best practices, then go ahead and add it.
I appreciate your kind words. I'm glad you found the article informative.
HTMX is not a JavaScript framework in the traditional sense. It is a library that extends HTML with new attributes that allow you to make HTTP requests and manipulate the DOM without writing any JavaScript code. This makes it a very lightweight and easy-to-use alternative to JavaScript frameworks.
Whether or not HTMX will still be around in a year is a difficult question to answer. It is a relatively new library, and it has not yet been adopted by a large number of developers. However, it has been growing in popularity in recent years, and it has been praised by many developers for its simplicity and ease of use.
I believe that HTMX has the potential to be a very popular library in the future. It is a well-designed and well-implemented library, and it addresses a real need in the web development community. I encourage you to keep your eye on HTMX in the future, and I believe that it will be a valuable tool for many developers.
It's no different than adding data-something attributes and capturing click events to submit things.
The whole premise of "it's not javascript" is ridiculous. That tag that you include in the head of the html...that's javascript. It's all javascript and just another way to do the same things we already do every day. It doesn't solve any problems, just adds another set of random syntax for devs to memorize.</p>
While it's true that HTMX leverages HTML attributes to trigger HTTP requests and handle responses, it fundamentally differs from simply adding data attributes and capturing events using JavaScript. The key distinction lies in the separation of concerns and the level of abstraction provided by HTMX.
HTMX promotes a declarative approach to web development, allowing developers to focus on the structure and content of their web pages rather than the intricate details of JavaScript code. Instead of manually writing event handlers and manipulating the DOM, developers can simply express their intent using HTML attributes, and HTMX handles the underlying JavaScript mechanics.
In short, HTMX is not just another way to do the same things with JavaScript. It offers a distinct approach to web development that promotes simplicity, maintainability, accessibility, and SEO-friendliness. By abstracting away the complexities of JavaScript, HTMX empowers developers to create interactive web applications without sacrificing clarity and ease of maintenance.
you're right, it's still just doing the same things with javascript, but in a more controlled and restrictive manner where you're now limited to what HTMX allows you to do versus using vanilla JS which just lets you do whatever you want to.
Yeah, relatively. But instead of restrictive, you can say simply.
I never thought that one day I would realize real content and content coming from AI. Until I came across this article.
That's just an assumption, I'm not surprised by your reaction though, and how do you expect me to blindly write about something I have not used? If you go over the article, you'll find use cases and examples.
It's a relatively new library and there's still lots to improve on It.
What is writing the snippets of HTML/HTMX coming back from the server? I would imagine you would need some sort of templating language on the back end. This doesn't seem like it's getting rid of most of the coding. It just moves it down
Definitely, as long as the server needs to generate HTML dynamically based on the data it receives and the current state of the application, some form of templating language on the backend will be necessary. While HTMX does make it easier to write client-side code by reducing the need for explicit JavaScript, it doesn't completely eliminate the need for backend coding altogether. Templating languages assist in the creation of reusable and maintainable code by providing a structured and reusable way to embed data and logic into HTML templates.
Won't the templating language also require scripting of some kind. I've never worked in a pure templating language before that didn't have some need for scripting or at least a MVVM/MVP/MVC layer to provide transformed data.
Ultimately, this feels more like an incremental update over traditional AJAX than a major new improvement, though ultimately, I imagine that will be enough for a lot of people.
Yes it moves it down. But not everyone wants to write JS only. :)

In my experience, it's painful to redeploy the server every time you need to tweak the structure of the HTML. It also prevents a lot of CDN benefits. It does seem like SPAs need a rethink around SSR/SSG. I don't think the latest wave is it, either. But I also think that HTMX is a return to a bunch of problems that had been mostly solved (i.e., better cache-ability, simpler API design, merged web/native/desktop APIs, simpler change management, dark launch via feature flags/treatments).
That's not to say a return to more HTML-centric code can't solve those problems, but I'm still skeptical that it's going to be a better overall experience right now.
I have already posted about another technology like HTMX sadly not well known
which existed long before HTMX (6 years old...)
mavo.io/ from Lea Verou
Life is a great wheel...
Building without JavaScript… htmx is a js library. Ok.
It cannot be more performant than vanilla js by definition. Imported script is not executed somewhere else but in your own browser; to make matters worse, it includes html parser.
It’s not simple from developer perspective either as it creates complexities in backend making you prepare complete html snippets.
It’s not maintainable. Hardly can I imagine how to manage complex reactive apps.
I assume you haven't tried it. For someone who wants to do frontend in his backend programming language of choice (+ templating engine), its a miracle.
Performance has more factors than just html parsing.
You can use Alpinejs with HTMX and create a fully reactive frontend.
Or I can use vanilla js for simple apps and react for more complex ones. The more abstraction provided, the less control you have. I took a brief look at it and immediately encountered a couple of problems boiling down to complexities.
Honestly, new js libs/frameworks turn up almost everyday and inspecting them all is a waste of time.
Doesn't that scream XSS?
Only if you let it.
Yes, if not handled carefully.
To mitigate XSS risks in HTMX applications, developers should employ proper input sanitization techniques to ensure that user-provided data is safely escaped before being incorporated into HTML attributes. This involves removing or encoding potentially harmful characters that could be interpreted as JavaScript code.
Developers should also consider using a content security policy (CSP) to further restrict the execution of JavaScript code and limit the potential for malicious scripts to be injected.
Additionally, use server-side validation to ensure that user-provided data is valid and safe before sending it to the client.
Also, avoid using inline JavaScript code in HTMX attributes whenever possible. Instead, encapsulate JavaScript logic in separate JavaScript files and use HTMX attributes to trigger or interact with these functions.
HTMX has worse developer experience compared to React because of missing HMR.
HMR makes sure you keep your web app state while the dev server replaces the components.
This is acceptable for static or data heavy pages.
This is nearly always completely unacceptable for highly complex/dynamic web apps.
Why? Because if you have to open a Dialog and then input something into a text field to see if an form error message pops up -> each code line without HMR will completely reset the page. Opening the form again and again typing something into a text field can very fast get pretty annoying even for the most patient developer. Do that 100-200 times a day and you will start to worship HMR for the developer experience.
React is one of the slowest javascript solutions (and the ecosystem around it with Next.js, Remix, Vite) but it provides one of the best developer experiences a frontend developer can want.
Well. For me it is the best developer experience that I don't need to use overly complicated frontend frameworks all over the place. Not to talk about that I can write less JS and more the language I truly love. Thx HTMX!
Not having HMR is one of HTMX limitations which makes React a better choice in terms of smooth and efficient development workflow. HTMX offers some advantages in terms of simplicity and maintainability. Hence, if you prefer a more declarative and HTML-centric approach, HTMX may be worth considering for smaller or simpler projects.
"but it provides one of the best developer experiences a frontend developer can want."
Well, I guess Svelte or Solid developers would challenge this.
things like HTMX, Qwik, Astro, Solid, etc are changing the way we think about web development, reducing the amount of JS, which should speed up the web in the future. Ironically obviously we have faster internet now than ever, but we are optimizing more for speed/size than ever before as well. As we are used to things being fast, if anything is remotely slow, we give up on it.
I mentionedQwik, Astro, and Solid as well, and I recommend people who are interested in learning something non React, look at those as well. React is great, its been around a decent amount so theres a lot of packages for it, but these new comers are no slouches
This is not my first article though, I actually started writing before you as well.
I have done this enough to publish a book that can not be generated by chatgpt.
Check it out, t.co/I12JVBCWc6
Some comments have been hidden by the post's author - find out more