--- name: htmx description: | htmx gives you access to AJAX, CSS transitions, WebSockets, and Server-Sent Events directly in HTML using attributes. It enables dynamic web UIs without writing JavaScript by letting any element issue HTTP requests and swap content into the DOM. license: Apache-2.0 compatibility: 'any web server, html' metadata: author: terminal-skills version: 1.0.0 category: development tags: - html - hypermedia - ajax - sse - websocket - no-javascript --- # htmx htmx extends HTML with attributes like `hx-get`, `hx-post`, `hx-swap`, and `hx-trigger` to make any element capable of issuing HTTP requests and updating the DOM. The server returns HTML fragments, not JSON. ## Installation ```html ``` ## Core Attributes ```html
``` ## Swap Strategies ```html
Replace my contents
Replace me entirely
With transition
``` ## Triggers ```html
Loading...
Notifications
Status: checking...
``` ## Server Responses (Python/Django Example) ```python # views.py — server returns HTML fragments, not JSON from django.shortcuts import render from django.http import HttpResponse def article_list(request): articles = Article.objects.filter(published=True)[:20] return render(request, "partials/article_list.html", {"articles": articles}) def create_article(request): form = ArticleForm(request.POST) if form.is_valid(): article = form.save() return render(request, "partials/article_card.html", {"article": article}) return render(request, "partials/article_form.html", {"form": form}, status=422) def delete_article(request, pk): Article.objects.filter(pk=pk).delete() return HttpResponse("") # Empty response removes element with outerHTML swap ``` ```html

{{ article.title }}

{{ article.body|truncatewords:30 }}

``` ## Indicators ```html Loading... ``` ## Headers and Request Config ```html My Article ``` ## Server-Sent Events ```html
``` ```python # views.py — SSE endpoint import json from django.http import StreamingHttpResponse def article_events(request): def event_stream(): for article in listen_for_new_articles(): html = render_to_string("partials/article_card.html", {"article": article}) yield f"event: newArticle\ndata: {html}\n\n" return StreamingHttpResponse(event_stream(), content_type="text/event-stream") ``` ## WebSocket ```html
``` ## Boosting (Progressive Enhancement) ```html
``` ## Key Patterns - Server returns HTML fragments, not JSON — this is hypermedia, not REST - Use `hx-target` to control where responses are inserted; `hx-swap` controls how - Use `hx-trigger` with modifiers (`delay`, `throttle`, `changed`, `once`) for precise control - Use `hx-boost="true"` on `` for easy progressive enhancement of existing sites - Use `hx-swap-oob` for updating multiple page sections from a single response - Use `hx-indicator` for loading states — htmx manages the CSS class automatically - Use `hx-push-url` to update browser URL for back-button support