HTMX: Building Interactive Web Apps Without JavaScript
Tags: webdev, javascript, programming, beginners
Published: 2023-11-21 14:06:45

## Contents
[Introduction](#intro)
[What is HTMX?](#htmx)
[Why use HTMX?](#why)
[Key Features of HTMX](#features)
[Getting Started with HTMX](#start)
[AJAX](#ajax)
[HTMX Attributes and Use Cases](#det)
[The `hx-on` attribute](#hxon)
[Resources for Learning HTMX](#resources)


## Introduction <a name="intro"></a>

In the realm of web development, JavaScript has long been the go-to language for creating dynamic and interactive web pages. However, HTMX (Hypermedia.js) emerges as a compelling alternative, offering a JavaScript-free approach to building modern web applications.

### What is HTMX? <a name="htmx"></a>

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? <a name="why"></a>

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 <a name="features"></a>

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 <a name="start"></a>

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 <a name="ajax"></a>
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tup93rd2u54qtjijlfvy.png)

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 <a name="det"></a>
**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vumt231saoyy7w6m254g.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/app5jrviv8daodxr1lf8.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x01nftke97qogtsccl1a.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6guq8guw8y91pdp4co9b.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hr3plmdxuolchbtfrzy3.png)
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 <div> element.

**Project 2**

![Modal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfe3qdgw6rqsmf0n4e62.png)
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 <a name="hxon"></a>
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42g1hlln6zln7b1s8usx.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jzvrjjqle62vm8ql7od7.png)

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 <a name="resources"></a>

To delve deeper into HTMX, explore these valuable resources:

* **Official HTMX Documentation:** [https://htmx.org/docs/](https://htmx.org/docs/)

* **HTMX GitHub Repository:** [https://github.com/bigskysoftware/hypermedia-systems](https://github.com/bigskysoftware/hypermedia-systems)

* **HTMX Community Forums:** [https://htmx.org/essays/hypermedia-friendly-scripting/](https://htmx.org/essays/hypermedia-friendly-scripting/)

* **HTMX Tutorials and Articles:** [https://htmx.org/docs/](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](https://www.buymeacoffee.com/cqvuesleq)**

**Also open for technical writing and frontend dev roles!**