### Example of outerMorph Swap Source: https://four.htmx.org/docs/full.md Demonstrates how 'outerMorph' can be used to swap content while preserving element states like video playback. The example shows an HTML structure and a button that triggers a swap, with the response content designed to be morphed into the existing DOM. ```html

Title

``` ```html

Title

``` -------------------------------- ### Install htmx using npm Source: https://four.htmx.org/docs/get-started/installation.md Install the htmx.org package using npm. This command installs version 4.0.0-beta4. ```sh npm install htmx.org@4.0.0-beta4 ``` -------------------------------- ### HTML Content Example Source: https://four.htmx.org/docs/features/css-transitions.md This is the initial HTML content of a div. ```html
Original Content
``` -------------------------------- ### Server Response for hx-get Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md The server should return HTML content to be swapped into the target element. This example shows a simple HTML response. ```html
You have 3 new messages
``` -------------------------------- ### Progressive Enhancement for Active Search Source: https://four.htmx.org/docs/features/boosting.md This example shows how to make an active search input progressively enhanced by wrapping it in a form. JavaScript-enabled clients get AJAX search, while non-JavaScript clients can still submit the form. ```html
``` -------------------------------- ### Customizing Out-of-Band Swap Style Source: https://four.htmx.org/docs/core-concepts/multi-target-updates.md Specify a different swap style for out-of-band updates by providing the swap style after `hx-swap-oob`. This example appends content instead of replacing it. ```html
New notification
``` -------------------------------- ### HX-Location Response Header Examples Source: https://four.htmx.org/docs/core-concepts/hcon.md The server can return HCON or JSON in the HX-Location header to control client-side navigation. Examples show basic path and configured navigation. ```HTTP Response Header HX-Location: /new-page HX-Location: path:"/new-page" push:"true" HX-Location: {"path":"/new-page","push":"true"} ``` -------------------------------- ### HCON JSON Fallback Example Source: https://four.htmx.org/docs/core-concepts/hcon.md When a value starts with '{', it's parsed as JSON instead of HCON. This allows server-side composition of configuration. ```HTML ``` -------------------------------- ### Set Content Security Policy via HTTP Header Source: https://four.htmx.org/docs/security/best-practices.md Configure a Content Security Policy using an HTTP header to enhance browser security. This example sets the default source to the same origin and allows scripts from the same origin with a specific nonce. ```http Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-' ``` -------------------------------- ### Custom CSS for Request Indicators Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md Customize the visibility of request indicators using CSS. This example uses 'display: none' and 'display: inline' to show/hide the indicator. ```css .htmx-indicator { display: none; } .htmx-request .htmx-indicator { display: inline; } .htmx-request.htmx-indicator { display: inline; } ``` -------------------------------- ### Conditional Swapping for 404 and 500 Responses Source: https://four.htmx.org/docs/full.md Use `hx-status` to define specific swap behaviors for different HTTP error codes. This example shows handling 404 with 'none' and 500 by targeting an error container. ```html ``` -------------------------------- ### HCON Value Types Example Source: https://four.htmx.org/docs/core-concepts/hcon.md Demonstrates parsing of boolean, integer, quoted string, and bare-word string values in HCON. Unspecified values default to true. ```HTML Loading... ``` -------------------------------- ### Import htmx in JavaScript (Default) Source: https://four.htmx.org/docs/get-started/installation.md Import the htmx library into your JavaScript project after installing it via npm. This makes htmx globally available. ```javascript import 'htmx.org'; ``` -------------------------------- ### Load Data on Click with hx-get Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md Use the `hx-get` attribute on an element to trigger an AJAX GET request when the element is clicked. The response HTML will replace the element's content. ```html ``` -------------------------------- ### hx-status for status code specific swaps Source: https://four.htmx.org/docs/get-started/migration.md Configure different swap behaviors based on HTTP status codes using the hx-status attribute. This example shows how to handle validation errors (422) and server errors (5xx) differently. ```html
``` -------------------------------- ### Displaying Request Indicators with 'htmx-indicator' Class Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md Show users that an AJAX request is in progress by using the 'htmx-indicator' class. This example reveals a spinner image on button click. ```html ``` -------------------------------- ### Active Search with Input Delay and Enter Key Trigger Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md This example demonstrates advanced trigger modifiers: `delay:500ms` to wait 500ms after input before sending a request, and `keyup[key=='Enter']` to trigger on Enter key press. Results are targeted to `#search-results`. ```html
``` -------------------------------- ### Using Partials for Explicit Targeting Source: https://four.htmx.org/docs/core-concepts/multi-target-updates.md Wrap content in `` tags and use `hx-target` and `hx-swap` to explicitly define where the content should be placed. This provides granular control over updates. ```html
New message content
5
``` -------------------------------- ### hx-trigger Modifiers Example Source: https://four.htmx.org/docs/core-concepts/hcon.md Event names in hx-trigger are followed by modifiers parsed as HCON. This example shows delay and throttle. ```HTML ``` -------------------------------- ### Preventing Triggers with Shift-Click Filter Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md Use trigger filters to conditionally prevent htmx requests. This example triggers only on a Shift-Click event. ```html
Shift Click Me
``` -------------------------------- ### Load htmx 2-compat Extension Source: https://four.htmx.org/docs/get-started/migration.md Include the htmx-2-compat extension to restore implicit inheritance, old event names, and previous error-swapping defaults. ```html ``` -------------------------------- ### Run htmx Upgrade Checker Source: https://four.htmx.org/docs/get-started/migration.md Use the command-line tool to scan project files for htmx 2.x code that requires updating for htmx 4.x compatibility. ```bash npx htmx.org@next upgrade-check -- ./path/to/project/root ``` ```bash npx htmx.org@next upgrade-check --ext .vue ./path/to/project/root ``` -------------------------------- ### Load htmx and an Extension with a Bundler Source: https://four.htmx.org/docs/features/extensions.md Import htmx and the desired extension when using a JavaScript bundler. ```javascript import 'htmx.org'; import 'htmx.org/dist/ext/hx-sse'; ``` -------------------------------- ### Initialize htmx in Shadow DOM Source: https://four.htmx.org/docs/features/web-components.md Call `htmx.process` on the shadow root after creating it to enable htmx functionality within the component. ```javascript customElements.define('my-counter', class extends HTMLElement { connectedCallback() { const shadow = this.attachShadow({mode: 'open'}) shadow.innerHTML = " \n
0
" htmx.process(shadow) // Initialize htmx for this shadow DOM } }) ``` -------------------------------- ### Custom Swap Style with handle_swap hook Source: https://four.htmx.org/docs/get-started/migration.md Illustrates how to implement a custom swap style using the special handle_swap hook, which receives positional parameters. ```javascript handle_swap: (swapStyle, target, fragment, swapSpec) => { if (swapStyle === 'my-swap') { target.appendChild(fragment); return true; } return false; } ``` -------------------------------- ### Attribute Inheritance with :append Source: https://four.htmx.org/docs/core-concepts/hcon.md The :append composition feature merges child attribute values with inherited parent values by concatenation. This example appends headers. ```HTML
``` -------------------------------- ### HCON Dot-Notation for Nested Keys Source: https://four.htmx.org/docs/core-concepts/hcon.md Use dot-notation to set nested object properties within HCON. This example configures SSE reconnect behavior. ```HTML ``` -------------------------------- ### Set htmx Target Element Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md Use the `hx-target` attribute to specify which element should receive the response from an htmx request. This example targets an element with the ID `results`. ```html
``` -------------------------------- ### hx-config for Per-Element Fetch Options Source: https://four.htmx.org/docs/core-concepts/hcon.md Use hx-config to set fetch options like timeout and credentials for individual elements. Supports HCON and JSON. ```HTML ``` -------------------------------- ### Selecting Specific Elements for Out-of-Band Swaps Source: https://four.htmx.org/docs/core-concepts/multi-target-updates.md Use `hx-select-oob` on the triggering element to specify which elements from the response should be swapped out-of-band. This allows for OOB swaps even if the response elements lack `hx-swap-oob` attributes. ```html ``` -------------------------------- ### Self-host htmx (Minified) Source: https://four.htmx.org/docs/get-started/installation.md After downloading htmx.min.js and saving it to your project, include it in your HTML's head tag using a relative path. ```html ``` -------------------------------- ### Include Extensions in htmx 4 Source: https://four.htmx.org/docs/get-started/migration.md Demonstrates how to load extensions in htmx 4 by including their script files directly. ```html ``` -------------------------------- ### Trigger Request on Mouse Enter Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md Use the `hx-trigger` attribute to specify custom events that initiate an AJAX request. This example triggers a POST request when the mouse enters the div. ```html
Mouse Trap
``` -------------------------------- ### Initialize 3rd Party Library with htmx.onLoad Source: https://four.htmx.org/docs/core-concepts/client-scripting.md The `htmx.onLoad` function provides a clean way to initialize third-party libraries on elements processed by htmx, similar to using `htmx:after:process`. ```javascript htmx.onLoad(function (target) { myJavascriptLib.init(target); }); ``` -------------------------------- ### Migrate Extension Registration and Callbacks Source: https://four.htmx.org/docs/get-started/migration.md Shows the conversion from htmx 2.x's defineExtension with onEvent to htmx 4's registerExtension with specific event hooks. ```javascript htmx.defineExtension('my-ext', { onEvent: function(name, evt) { if (name === 'htmx:beforeRequest') { /* ... */ } } }); ``` ```javascript htmx.registerExtension('my-ext', { htmx_before_request: (elt, detail) => { /* ... */ } }); ``` -------------------------------- ### Basic HTML Anchor Tag Source: https://four.htmx.org/docs/core-concepts/mental-model.md A standard HTML anchor tag used to navigate to a URL. Clicking this link triggers a GET request and loads the response into the browser window. ```html Blog ``` -------------------------------- ### Load htmx and an Extension via Script Tags Source: https://four.htmx.org/docs/features/extensions.md Include the htmx core library and a specific extension script after each other in your HTML. ```html ``` -------------------------------- ### Using :inherited Modifier for Attribute Inheritance Source: https://four.htmx.org/docs/features/attribute-inheritance.md This example demonstrates hoisting the hx-confirm attribute to a parent div using the :inherited modifier. All htmx elements within the div will now inherit this attribute. ```html
``` -------------------------------- ### Enable View Transitions for Boosted Elements Source: https://four.htmx.org/docs/full.md Enable view transitions for boosted elements by setting hx-boost to 'transition:true'. ```html Boosted Link ``` -------------------------------- ### hx-swap scroll modifiers: htmx 4 syntax Source: https://four.htmx.org/docs/get-started/migration.md Use separate keys for 'show' and 'scroll' modifiers in hx-swap for htmx 4. This example demonstrates the correct syntax for targeting specific positions. ```html
``` -------------------------------- ### Configure CSP for Connect Source Source: https://four.htmx.org/docs/security/best-practices.md Set the `connect-src` directive in a Content Security Policy meta tag to explicitly allow connections to specific origins, such as an API on a different subdomain, while maintaining security. ```html ``` -------------------------------- ### Reset Form After Request Source: https://four.htmx.org/docs/core-concepts/client-scripting.md This example demonstrates how to reset a form after an HTMX request has successfully completed. It uses the `htmx:after:request` event and the `find()` helper to locate and reset the closest form element. ```html ``` -------------------------------- ### HTTP Methods with htmx Attributes Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md htmx provides specific attributes for different HTTP methods (GET, POST, PUT, PATCH, DELETE) to control the request type. Each attribute includes the target URL. ```html ``` -------------------------------- ### HTML Structure for Morph Swap Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md This HTML demonstrates a structure with a video element and a button that triggers an outerMorph swap. It's used to show how morphing preserves video playback. ```html

Title

``` -------------------------------- ### Form Submission with Status-Code Specific Error Handling Source: https://four.htmx.org/docs/full.md Configure form submissions to direct different error responses to specific target elements. This example handles 422, 500, and 503 status codes distinctly. ```html
``` -------------------------------- ### htmx Button for Dynamic Updates Source: https://four.htmx.org/docs/core-concepts/mental-model.md An example of an htmx-enhanced button that triggers a POST request on click and swaps the target element's outer HTML with the response. This demonstrates htmx's generalization of HTML hypermedia controls. ```html ``` -------------------------------- ### Server Response with HTML Content Source: https://four.htmx.org/docs/core-concepts/hypermedia-controls.md The server should respond with standard HTML content. htmx will then use this HTML to update the DOM. ```http HTTP/1.1 200 OK Content-Type: text/html
You have 3 new messages
``` -------------------------------- ### HTMX Configuration with JSON Fallback Source: https://four.htmx.org/docs/full.md Configure HTMX globally or per-element using JSON strings. This allows server-side composition of configurations. ```html ``` ```html ``` -------------------------------- ### SortableJS Integration Example Source: https://four.htmx.org/docs/core-concepts/client-scripting.md This HTML structure is used in conjunction with SortableJS and HTMX to enable drag-and-drop reordering of items. The `hx-trigger="end"` attribute on the form ensures that an HTMX POST request is sent when the sorting action ends. ```html
Updating...
Item 1
Item 2
Item 3
``` -------------------------------- ### Migrate getSelectors to htmx_after_init hook Source: https://four.htmx.org/docs/get-started/migration.md Demonstrates replacing the htmx 2.x getSelectors callback with the htmx 4 htmx_after_init hook for checking attributes. ```javascript // htmx 2.x getSelectors: function() { return ['[my-custom-attr]']; }, onEvent: function(name, evt) { if (name === 'htmx:afterProcessNode') { initializeCustomBehavior(evt.target); } } ``` ```javascript // htmx 4 htmx_after_init: (elt) => { if (api.attributeValue(elt, 'my-custom-attr')) { initializeCustomBehavior(elt); } } ``` -------------------------------- ### Target Multiple Elements with hx-partial Source: https://four.htmx.org/docs/get-started/migration.md Use `` to target multiple elements with explicit control over targeting and swap strategy. Each instance specifies its own `hx-target` and `hx-swap`. ```html
New message
5 ``` -------------------------------- ### New hx-swap Styles: Morph, TextContent, Delete Source: https://four.htmx.org/docs/full.md Introduces morph swaps for state preservation, textContent for plain text updates, and delete for element removal. ```html
...
``` ```html
...
``` ```html
...
``` ```html
...
``` -------------------------------- ### Initialize htmx in Component Without Shadow DOM Source: https://four.htmx.org/docs/features/web-components.md Call `htmx.process` on the component itself if it does not use a shadow DOM. ```javascript customElements.define('simple-widget', class extends HTMLElement { connectedCallback() { this.innerHTML = `Load` htmx.process(this) } }) ``` -------------------------------- ### Referencing the Window Object with 'window' Source: https://four.htmx.org/docs/features/extended-selectors.md Use the 'window' keyword to reference the window object. This is primarily used with window events. ```html
...
``` -------------------------------- ### Enable View Transitions Source: https://four.htmx.org/docs/get-started/migration.md Enable View Transitions API support by setting `htmx.config.transitions` to true. This feature is disabled by default. ```javascript htmx.config.transitions = true; ``` -------------------------------- ### Alternative Partial Syntax with