Featured image of post HTMX First Experience

HTMX First Experience

`htmx` simplifies front-end development by enhancing HTML with attributes, reducing JavaScript reliance, and promoting code readability. #htmx

 

htmx is a novel front-end development tool that complements existing HTML, CSS, and JavaScript technologies rather than completely replacing them.
htmx can be used with other technologies and tools like Vue.js, React, and Angular. Its core philosophy is “using HTML as the programming language for applications,” meaning dynamic behavior is achieved by adding various attributes to HTML tags, eliminating the need to write extensive JavaScript code.

Htmx Design Philosophy

  1. Leverage familiar HTML and CSS knowledge, requiring minimal JavaScript code.
  2. Reduce the complexity of front-end development and lessen dependence on complex JavaScript frameworks.
  3. Make code more readable and maintainable by specifying behavior directly in HTML through declarative markup.
  4. Enable progressive enhancement, allowing web applications to run on varying technology stacks, improving compatibility and accessibility.

htmx provides a series of custom HTML attributes that allow developers to simplify JavaScript, enabling dynamic interactive functions that initially require complex scripts using only HTML tags. This allows developers to focus on content and structure rather than implementation details of behavioral logic, thus developing modern web applications more quickly and efficiently.

Installation and Usage

To install and start using htmx, you can integrate it into your web page in several simple ways.

1. Inclusion via CDN

Add the following <script> tag directly to your HTML file to load htmx. Place this code at the end of the <head> or <body> tag.

1
<script src="https://unpkg.com/htmx.org"></script>

Alternatively, you can use other CDN services or specify a particular version of htmx:

1
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

Using a CDN is the easiest and fastest way to start using htmx.

2. Installation Using Npm or Yarn

If your project uses Node.js and npm (or yarn), you can install htmx through a package manager.

  • Using npm:
1
npm install htmx.org --save
  • Using yarn:
1
yarn add htmx.org
  • Then import htmx into your JavaScript module or entry file:
1
import "htmx.org";

Alternatively, you can import it into a specific script file and include it in your final bundled file through a build process (e.g., Webpack or Parcel).

Golang

If you are also a Gopher, then I recommend you to use the html/template package to use HTMX, there is a simple example afterward。

htmx provides a set of easy-to-use HTML attributes for implementing various dynamic behaviors, such as:

  • hx-get: for loading data asynchronously.
  • hx-post: for submitting form data.
  • hx-trigger: used to define the trigger behavior.

By adding these attributes to the HTML markup, we can easily implement a variety of interactive features without having to write a lot of JavaScript code. For example, to load data when a button is clicked, we could write something like this:

1
2
3
<button hx-get="/api/data" 
		hx-target="#result">Load Data</button>
<div id="result"></div>

The above code defines a button; when the user clicks on the button, htmx will use AJAX to load the data returned by the specified URL and populate the result into the selected elements.

htmx It also supports controlling the update of elements on the page through server responses。

You can utilize the hx-swap attribute to define how the response content should be replaced or inserted in the DOM, or you can use the extended CSS selector syntax to specify the target element for the update.

为了优To optimize the user experience, htmx also provides a loading indicator that shows the user-visible feedback when an AJAX request is initiated, such as a loading animation.

htmx has many other advanced features, such as View Transitions, history support, events, and logging. These features allow developers to create rich and efficient user interfaces while reducing the effort of writing and maintaining JavaScript code.

More Examples (using Golang)

Full code click here.

1. AJAX Load Content

Suppose you have a server-side URL /get-content that returns some HTML content. You can use the hx-get attribute to create a button that, when clicked, will asynchronously load the content and insert it into the specified element on the page.

1
2
3
<h2>1. AJAX load</h2>
<button hx-get="/get-content" hx-target="#content">click me</button>
<div id="content"></div>

2. Submit Form

You can use htmx to submit forms asynchronously. This means that the user can submit the form without refreshing the page, and the response to the form will be displayed directly on the page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<h2>2. from submit</h2>
<form
hx-debug="true"
hx-post="/submit-form"
hx-target="#form-result"
hx-swap="outerHTML">
<input type="text" name="name" placeholder="inputName">
<input type="submit" value="summit">
</form>
<div id="form-result"></div>

Using htmx it is also very easy to create live search forms where the search results can be constantly refreshed as the user types in the search box, an example of which is shown below:

1
2
3
4
5
6
7
8
9
<h2>3. search</h2>

<input
name="q"
hx-get="/search"
hx-target="#search-results"
hx-trigger="keyup changed delay:500ms"
placeholder="input search term">
<div id="search-results"></div>

The content typed in the search box will be sent to /search?q=<value entered>, and the server needs to return the appropriate search results based on the query parameter q.

4. Delete

With htmx, you can easily realize to delete items without refreshing the page:

1
2
3
4
5
<h2>4. delete</h2>
<div id="item-123">
project 123
<button hx-delete="/delete-item/123" hx-target="#item-123" hx-swap="outerHTML">Delete </button>
</div>

When the button is clicked, a DELETE request is sent to the server to delete the item with ID 123.

5. Load More

Create a “Load More” button that, when clicked, loads the next page of content.

1
2
3
4
5
6
<h2>5. load more</h2>
<div id="items">
	<div>input 1</div>
	<div>input 2</div>
</div>
<button hx-get="/get-more-items?page=2" hx-target="#items" hx-swap="afterend">load more</button>

In practice, you will need to dynamically update the page parameter in the hx-get property in order to load the correct content page.

Instead of relying on JavaScript, htmx allows you to add rich interactivity through HTML, and these examples show just a few of the features of htmx. You can learn more about advanced features and usage by checking out the official htmx documentation.

List of Command Tags

htmx works through a set of custom HTML attributes, which usually begin with the prefix hx-. These attributes can be added to the standard HTML tag to provide various dynamic behaviors. The following are some commonly used htmx attributes (commands and labels):

Core Attributes

  • hx-get: Initiate an AJAX GET request.
  • hx-post: Initiate an AJAX POST request.
  • hx-put: Initiate an AJAX PUT request.
  • hx-delete: Initiate an AJAX DELETE request.
  • hx-patch: Initiate an AJAX PATCH request.
  • hx-trigger: Define events that trigger AJAX requests, such as click, keyup, etc.
  • hx-target: Specify which element will be replaced or updated by the requested response.
  • hx-swap: Define how to insert the response content into the target element, such as innerHTML, outerHTML, beforebegin, afterend, etc.

Enhance Attributes

  • hx-params: Control which parameters are included in the request, such as none, *, vals, etc.
  • hx-include: Clearly specify which element values should be included in the request parameters.
  • hx-indicator: Specify one or more elements and display them as loading indicators when the AJAX request is in progress.
  • hx-push-url: Control whether to push the URL of AJAX request to the browser’s history.
  • hx-prompt: Prompt the user to enter the message before initiating the request.
  • hx-confirm: Ask the user to confirm before performing the operation.

Response Processing

  • hx-select: Select part of the content from the AJAX response to update instead of the entire response.
  • hx-headers: Allow the setting of custom request headers.

Event Attributes

  • hx-on: Specify specific events and their handling, such as hx-on="click: doSomething".

Web Sockets

  • hx-ws: Define the behavior related to WebSocket connection.

Tool Attributes

  • hx-boost: Automatically enhance the links and forms on the page to make them work asynchronously through AJAX.
  • hx-history-elt: Specify an element whose content change will trigger the update of the browser history.

My Opinion on HTMX

Everyone has many different views on this technology.

  • This is said to have happened 15 years ago, and integrating the front and back ends is not conducive to maintenance.
  • Some people also say that “handwriting grammar tree in XML” is outdated and unsuitable for modern large-scale software engineering.

“High power tools for HTML” is written on the homepage of the [official website] (https://htmx.org/) of HTMX. The success of a technology depends on the degree of recognition by most people in the future.

My current opinion on HTMX is as follows:

The core idea of HTMX is to use HTML language to obtain data, as well as asynchronous form submissions and other interactive scenarios. There is no need to use JS knowledge and some frameworks, nor to learn front-end construction engineering.

The back-end returns its front-end code, which is suitable for back-end engineers to make simple interactive interfaces. If you need to make complex pages, HTMX does not support or currently has limited support. HTMX has many advanced features, and it is not particularly easy to master.

HTMX allows developers not only to learn JavaScript but also to learn HTMX, and the learning curve does not decrease.

参考连接

Licensed under CC BY-NC-SA 4.0
Last updated on Jan 01, 2025 16:01 CST
Built with Hugo
Theme Stack designed by Jimmy