DEV Community

Cover image for HTMX: Building Interactive Web Apps Without JavaScript
Blackie
Blackie

Posted on • Edited on

HTMX: Building Interactive Web Apps Without JavaScript

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:

  1. Include the HTMX JavaScript library: Add the HTMX script tag to your HTML document's head section.

  2. Utilize HTML attributes: Employ HTMX attributes on HTML elements to trigger HTTP requests, handle responses, and manipulate the DOM.

  3. Structure your HTML: Organize your HTML content to define the areas that should be dynamically updated using HTMX.

  4. 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:

hxget

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:

hxpost

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:

hxput

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:

hxpatch
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:

delete

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

form
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

element.

Project 2

Modal
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:

hxon

where:

  • <event> represents the event to trigger the JavaScript function. Common events include click, submit, change, and keyup.

  • <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:

  1. Handling Form Submissions: Attach custom JavaScript functions to form submissions to perform validation, process user input, or update the DOM dynamically.

  2. Responding to User Actions: Capture user interactions, such as button clicks, and trigger JavaScript functions to handle specific actions or provide feedback.

  3. Reacting to DOM Changes: Monitor changes in the DOM, such as input value modifications or element visibility changes, and execute JavaScript functions accordingly.

  4. Enhancing User Experience: Implement interactive elements and animations using JavaScript functions triggered by user actions or DOM events.

  5. 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:

hxon comp

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:

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)

 
jr_shittu profile image
Blackie • Edited

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.

Collapse
 
jr_shittu profile image
Blackie

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.

Collapse
 
ravavyr profile image
Ravavyr

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&#39;s javascript. It&#39;s all javascript and just another way to do the same things we already do every day. It doesn&#39;t solve any problems, just adds another set of random syntax for devs to memorize.</p>

Thread Thread
 
jr_shittu profile image
Blackie

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.

Thread Thread
 
ravavyr profile image
Ravavyr

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.

Thread Thread
 
jr_shittu profile image
Blackie • Edited

Yeah, relatively. But instead of restrictive, you can say simply.

Collapse
 
trdbau profile image
trdbau

I never thought that one day I would realize real content and content coming from AI. Until I came across this article.

 
jr_shittu profile image
Blackie • Edited

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.

Collapse
 
oadrian2 profile image
oadrian2

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

Collapse
 
jr_shittu profile image
Blackie

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.

Collapse
 
oadrian2 profile image
oadrian2

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.

Collapse
 
zsomborjoel profile image
Zsombor Joel Gyurkovics

Yes it moves it down. But not everyone wants to write JS only. :)
Image description

Collapse
 
oadrian2 profile image
oadrian2

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.

Collapse
 
artydev profile image
artydev • Edited

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...

Collapse
 
tsolan profile image
Eugene • Edited

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.

Collapse
 
zsomborjoel profile image
Zsombor Joel Gyurkovics • Edited

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.

Collapse
 
tsolan profile image
Eugene

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.

Collapse
 
dagnelies profile image
Arnaud Dagnelies

Doesn't that scream XSS?

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

Only if you let it.

Collapse
 
jr_shittu profile image
Blackie

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.

Collapse
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

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.

Collapse
 
zsomborjoel profile image
Zsombor Joel Gyurkovics

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!

Collapse
 
jr_shittu profile image
Blackie

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.

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

"but it provides one of the best developer experiences a frontend developer can want."
Well, I guess Svelte or Solid developers would challenge this.

Collapse
 
rumncode profile image
RumNCode

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

 
jr_shittu profile image
Blackie • Edited

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