Our website uses cookies to enhance its functionality and your experience. By using our site, you consent to the use of cookies. To learn more, please review our privacy policy.
When creating a Monaca app, communication with the server is essential. During this process, a technique known as Ajax is commonly used to send requests to the server and update the screen based on the received response.
Writing such processes can be very tedious and complicated. This is where htmx comes in. htmx is a library that enables communication with the server without the need to write any JavaScript code.
In this article, we will introduce how to use htmx with simple code examples.
As mentioned earlier, htmx is a library that allows you to achieve network communication and advanced UX without writing JavaScript.
htmx enables direct access to AJAX, CSS transitions, WebSockets, and server-sent events within HTML using attributes on HTML tags.
By using htmx, you can avoid the hassle of writing repetitive JavaScript code and let htmx handle everything for you, including error handling.
Installing htmx
There are several ways to install htmx. The first and easiest one is to use a CDN.
The second method is to download a JavaScript file distributed by CDN and load it in the application.
<script src="js/htmx.min.js"></script>
Htmx examples
Let’s consider the scenario of writing Ajax code using htmx. Typically, it would be written as follows. We will simplify it for this example, but in reality, it can become more complex with request payload creation and authentication.
The following code utilizes the service “JSONPlaceholder” as a demo server.
JSONPlaceholder is a free online REST API that provides dummy JSON data. It allows you to perform operations such as GET, POST, PUT, PATCH, and DELETE, making it useful for testing and prototyping purposes.
When writing this process with htmx, it would look as follows. You don’t need to write any JavaScript code; you can simply specify it using HTML tag attributes.
<a href="#" hx-get="https://jsonplaceholder.typicode.com/todos/1" hx-trigger="click" hx-target="#result">
Click here to load content
</a>
<div id="result">Loading…</div>
Htmx has the following features.
Ajax
This is an example of server communication. htmx supports the HTTP GET/POST/PUT/PATCH/DELETE methods.
In the following example, when you click on the div tag, it sends a PUT request to /messages and updates the content of the div tag with the received response.
<div hx-put="/messages">
Put To Messages
</div>
Page Replacement
By utilizing htmx, it is possible to update only the content within the `<body>` tag without reloading the entire HTML page. This functionality is similar to Hotwire, which is used in conjunction with Ruby on Rails. With this feature, traditional websites can evolve to have interactivity similar to that of a Single-Page Application (SPA).
To efficiently perform this process, it is recommended to specify `hx-push-url=”true”`. This enables the use of the History API, allowing dynamic rewriting of the URL and enabling features such as dynamically changing the URL and utilizing the browser’s back button.
By including `hx-push-url=”true”`, htmx makes it possible to leverage the History API, which provides seamless URL updates based on the changes made to the content. This allows for a more efficient and user-friendly browsing experience, including the ability to navigate using the browser’s back button.
Communication with servers: Use of Ajax, SSE, and WebSockets
By using htmx, you have more options for server communication beyond just Ajax. It also supports Server-Sent Events (SSE) and WebSocket as communication methods.
For example, when implementing a message receiving feature like a chat, you can use the following code:
In this example, hx-ws=connect: is used to specify the WebSocket server’s connection endpoint, and hx-ws=send: is used to set the information for sending messages.
Additionally, by using SSE, it is possible to receive one-way messages from the server. Unlike WebSocket, SSE only allows messages to be sent from the server. You can describe it as follows:
These pieces of code perform dynamic content updates without reloading the page.
Trigger handling
In htmx, several default event triggers are preconfigured. They are as follows:
input/textarea/select: onchange event
form: submit event
Other tags: click event
If you want to set a trigger for events other than the above, you can use the hx-trigger attribute to specify it. For example, you can trigger the mouse enter event with the following code:
This code sends a POST request to “/mouse_entered” when the mouse enters a specific element (on the occurrence of the mouseenter event). This allows the web page to dynamically respond to user actions and provides a better user experience.
Validation
In htmx, it is generally recommended to use the HTML5 Validation API for form validation. However, there may be cases where you want to implement custom validation.In such cases, although a bit more complex, you can perform input validation using JavaScript-like syntax within htmx.
<form hx-post="/test">
<input _="on htmx:validation:validate
if my.value != "foo"
call me.setCustomValidity("Please enter the value foo")
else
call me.setCustomValidity("")"
name="example"
>
</form>
Rewriting content
In htmx, you can specify how to rewrite the content, and by default, the innerHTML method is used. Rewriting methods can be specified using the hx-swap attribute. Here are some options:
htmx has a mechanism called extensions. You can create your own extensions using the element hx-ext. These extensions are written in JavaScript, and you can find a variety of extensions at </> htmx-Extensions. Here we showcase how to create an extension.
This extension can now be used in <div hx-ext=”my-ext” />.
Up to this point, you should be familiar with the basic concepts and usage of htmx. Now let’s see how it can be used in practical scenarios. It can be effective in the cases when most of the data resides on the server and there is no need to manage state on the client side.
1. Utilizing Simple Ajax
htmx is not necessarily suitable for complex Ajax processing. Instead, it is ideal for simple tasks such as sending information from a form and presenting the results in the user interface (UI). It is well-suited for applications where the server-side handles the request and response processing, and the client-side only displays the results.
2. Converting Existing Websites to Single-Page Applications (SPAs)
By leveraging htmx’s boost feature, it is possible to update the entire body section of the currently displayed HTML. This reduces the number of JavaScript and CSS file loads and efficiently achieves a user experience similar to web applications. This approach is particularly useful when the server-side holds most of the content, and the client-side is responsible for displaying it.
3. Implementing Chat Functionality
Since htmx supports WebSocket, it can be used to implement simple chat applications. This is especially suitable for applications where chatting is not the main functionality but they include chat features.
From the examples above, it is evident that htmx can be a valuable tool in various scenarios of web development by harnessing its unique characteristics. Understanding the efficient usage of htmx and applying it to your own projects will be beneficial.
In this article, we introduced the overview of the htmx library. With htmx, you can achieve Ajax functionality without relying on JavaScript, enabling you to create dynamic Monaca apps even if you are not proficient in programming.
We encourage you to master htmx and create exceptional UI/UX designs.