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 (48)

Collapse
 
lnahrf profile image
Info Comment hidden by post author - thread only accessible via permalink
Lev N. • Edited

Building interactive web apps without JavaScript

HTMX is a lightweight JavaScript library

I believe HTMX is yet another Javascript framework, if it will still be around a year from now I will consider checking it out.

Really detailed and nice article tho, thanks for sharing.

Edit: Apparently the author never used HTMX and just aggregated data, probably with AI doing all the heavy-lifting to generate this article. I do not think this has any value without the author's personal experience and opinion about the tool.

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
 
lnahrf profile image
Lev N.

HTMX is an HTML parser, written in Javascript, claiming to be a Javascript replacement (which is why itโ€™s so controversial, if it didnโ€™t claim to be a replacement for Javascript, I would be okay with it. But as it is right now, it feels like a lie).

Iโ€™ll dive deep into HTMXโ€™s code to understand exactly what itโ€™s doing soon enough, but from my understanding it is an HTML parser that replaces custom attributes with their functionality counterpart in.. plain olโ€™ Javascript. Nothing groundbreaking here.
(Please correct me if Iโ€™m wrong, Iโ€™d love for HTMX to actually be something worthwhile).

Thread Thread
 
jr_shittu profile image
Blackie

Your understanding of HTMX as an HTML parser that replaces custom attributes with their JavaScript counterparts is accurate. It's essentially a lightweight JavaScript library that extends HTML with new attributes to handle data fetching, DOM manipulation, and other interactive behaviors without requiring explicit JavaScript code.

While HTMX doesn't eliminate the need for JavaScript entirely, it aims to simplify common web development tasks by providing a more declarative and HTML-centric approach. This can be beneficial for developers who prefer to work with HTML as their primary language and want to avoid the complexity of writing and maintaining large amounts of JavaScript code.

The controversy surrounding HTMX's claim of being a JavaScript replacement stems from the fact that it still relies on JavaScript under the hood. The custom attributes it introduces are processed and executed using JavaScript code, which means that JavaScript is still an integral part of the development process.

However, HTMX proponents argue that by abstracting away the intricacies of JavaScript and providing a more intuitive syntax, it effectively reduces the burden of JavaScript programming for many developers. This can lead to faster development cycles and easier maintenance of interactive web applications.

Ultimately, whether or not HTMX is a worthwhile tool depends on your specific development needs and preferences. If you're comfortable with JavaScript and don't mind writing explicit code, then HTMX may not offer significant advantages. However, if you prefer a more declarative approach and want to reduce your reliance on direct JavaScript coding, then HTMX could be a valuable addition to your toolkit.

Thread Thread
 
joelbonetr profile image
JoelBonetR ๐Ÿฅ‡

Gosh I'm tired of Chat GPT answers. AI is a helper tool, an accelerator, but it doesn't make you understand the details of the topic in any way shape or form.

Moreover Chat GPT has been trained with Internet content, which means it inherited the bloated, unpractical and shitty way of expressing that SEO people use to trick crawlers.

If that wasn't enough we all know how to ask chatgpt for something.

If you write a post about anything, try the tool and check how it's built behind the scenes at the very least, add some value by explaining which has been your experience.

Thread Thread
 
lnahrf profile image
Lev N.

Did not even notice his answer was generated ๐Ÿ˜…, now that I read it again it sure seems this way.

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

Thread Thread
 
lnahrf profile image
Lev N.

He is right about you just prompting GPT to answer us instead of answering us yourself, does not feel genuine. So don't be surprised by our reaction... Did you ever use HTMX yourself? If so, what was your experience with it?

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

Thread Thread
 
lnahrf profile image
Lev N.

I don't think you need to write about things you have not tested/used at least once yourself, it does not feel genuine and is not valuable. Each and every one of us can find any random technology and aggregate data just to write a post - this does not bring much value. Hearing your personal experience about the tool you are writing about - that brings value! And it will also help you gain some form of experience.

Just an advice for the future :)

Thread Thread
 
jr_shittu profile image
Blackie

Yes, you can decide that it's not valuable after you had initially praised the effort.

While this is an introductory article on htmx, you can contribute your experience with it.

Thread Thread
 
lnahrf profile image
Lev N.

I have praised the effort went into creating a detailed article, because I am a polite human being. If you did not use the tool yourself you are merely copying other resources and presenting the data in a way that will make it seem like you are educated and experienced (not the case). Good luck to you!

Thread Thread
 
jr_shittu profile image
Blackie

๐Ÿ˜‚
Generate yours with chatgpt and present it in that manner adding references too.

Thanks for your contribution

Thread Thread
 
lnahrf profile image
Lev N.

I actually write my articles, hours of editing and actual experience poured into them. Hopefully you will be able to do the same one day.

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

Thread Thread
 
lnahrf profile image
Lev N.

I don't click shady links, but thanks.

Thread Thread
 
jr_shittu profile image
Blackie

Fear fear ๐Ÿคฃ๐Ÿคฃ
You're welcome

Thread Thread
 
michaeltharrington profile image
Michael Tharrington

Come on y'all, let's keep things friendly, please!

My name is Michael and I'm a Community Manager here at DEV.

I think it's clear that work was put into organizing the information in this article, but when using ChatGPT to aid in writing a post, we ask that you disclose it as stated in our Guidelines for AI-assisted Articles on DEV. These guidelines are included in our Code of Conduct and we have ways to lower the visibility of content by folks who repeatedly do not follow the guidelines. We believe folks have the right to know the source of the content they're reading, that's why we require this disclosure.

To be clear, I think there is value in using ChatGPT to generate or assist with writing content but it's important for folks to have the context to know where this is coming from. Hope you understand why we have this requirement and keep it in mind for the future.

Thread Thread
 
jr_shittu profile image
Blackie

Thanks Michael for the observation.

I never use Chatgpt to generate the article itself but some of the comments was generated.

This is basically the summary of the docs, which is attached in the references.

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.

Collapse
 
jr_shittu profile image
Blackie

๐Ÿ˜‚
Assumptions

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

Collapse
 
essien1990 profile image
Nana Yaw

Splendid

Collapse
 
fridaycandours profile image
Friday candour

Unofficial hymx docs, love it

Collapse
 
zsomborjoel profile image
Zsombor Joel Gyurkovics

This is my developer experience:

Simpler and more efficient code. Most of it in your favorite programming language (In my case Go).
If you want to eliminate most of client side JS scripting than there is Hyperscript or Alpinejs which is well integrated with HTMX

Image description

Some comments have been hidden by the post's author - find out more