HTMX is a modern JavaScript library that allows you to access AJAX, CSS Transitions, WebSockets, and Server-Sent Events directly in HTML, making it easier to build dynamic web applications. HTMX is designed to be highly accessible, requiring minimal JavaScript to enhance web pages.
Getting Started with HTMX
Installation
Include HTMX in your HTML:
1
<script src="https://unpkg.com/htmx.org"></script>
Basic Usage
HTMX extends HTML by adding custom attributes. The most common attributes are:
hx-get
: Load content from a URL via AJAX GET request.hx-post
: Send data to a server via AJAX POST request.hx-put
: Update data on a server via AJAX PUT request.hx-delete
: Send a DELETE request to a server.hx-trigger
: Define when the AJAX request should be triggered.hx-target
: Specifies where to place the returned content.hx-swap
: Controls how the new content is swapped into the DOM.
Examples
Basic GET Request
1
<a href="/example" hx-get="/example" hx-trigger="click">Load Content</a>
Form Submission via POST
1
2
3
4
5
<form hx-post="/submit-form" hx-target="#result">
<input type="text" name="message">
<button type="submit">Submit</button>
</form>
<div id="result"></div>
Lazy Loading
1
2
3
<div hx-get="/load-content" hx-trigger="revealed">
<!-- Content will be loaded when this div is scrolled into view -->
</div>
Advanced Features
WebSockets
HTMX can interact with WebSockets:
1
2
3
<div hx-ws="connect:/my-websocket">
<!-- Content here can be updated via WebSocket messages -->
</div>
Server-Sent Events (SSE)
HTMX supports SSE for real-time updates from the server:
1
2
3
<div hx-sse="connect:/my-sse">
<!-- Content here can be updated in real-time from the server -->
</div>
Boosting Links and Forms
The hx-boost
attribute enhances standard HTML forms and links with AJAX capabilities:
1
2
3
4
5
6
7
<!-- Link boosting -->
<a href="/example" hx-boost="true">Load with AJAX</a>
<!-- Form boosting -->
<form action="/submit-form" method="post" hx-boost="true">
<!-- Form elements -->
</form>
Events
HTMX emits custom events for various stages of the request lifecycle, such as:
htmx:beforeRequest
htmx:afterRequest
htmx:beforeSwap
htmx:afterSwap
Example of handling an HTMX event:
1
2
3
document.body.addEventListener('htmx:afterSwap', function(event) {
console.log('Content swapped!', event.detail);
});
Tips and Best Practices
- Progressive Enhancement: Use HTMX as an enhancement; ensure basic functionality works without JavaScript.
- Debugging: Use browser developer tools to inspect HTMX requests and responses.
- Performance: Keep an eye on the number of AJAX requests to avoid performance issues.