### HTMX Demo Example with Mock Response Source: https://htmx.org/docs An example demonstrating HTMX usage with a mock response defined using a template tag. It includes a button to trigger a POST request and a script to dynamically update a counter. ```html ``` -------------------------------- ### Install htmx via npm Source: https://htmx.org/docs Installs the htmx library using npm, typically for use in projects with module bundlers. ```bash npm install htmx.org@2.0.10 ``` -------------------------------- ### Install htmx Extension via npm Source: https://htmx.org/docs Install an htmx extension using npm for use in build systems. The extension's JavaScript file can then be bundled with htmx core and project code. ```bash npm install htmx-ext-extension-name ``` -------------------------------- ### HTMX Response Handling Configuration Example Source: https://htmx.org/docs This example shows the structure of the 'htmx.config.responseHandling' array, which configures how HTMX processes responses based on their HTTP status codes. It defines rules for swapping content and identifying errors. ```javascript responseHandling: [ {code:"204", swap: false}, // 204 - No Content by default does nothing, but is not an error {code:"[23]..", swap: true}, // 200 & 300 responses are non-errors and are swapped {code:"[45]..", swap: false, error:true}, // 400 & 500 responses are not swapped and are errors {code:"...", swap: false} // catch all for any other response code ] ``` -------------------------------- ### Install htmx via CDN Source: https://htmx.org/docs Includes the minified htmx library from a CDN into the document's head for immediate use. ```html ``` -------------------------------- ### Install htmx via CDN (unminified) Source: https://htmx.org/docs Includes the unminified htmx library from a CDN into the document's head, useful for debugging or development. ```html ``` -------------------------------- ### Include HTMX Demo Script Source: https://htmx.org/docs Add this script tag to your demo environment (like jsfiddle) to automatically install HTMX, hyperscript, and a request mocking library. ```html ``` -------------------------------- ### Install htmx Extension via CDN Source: https://htmx.org/docs Load htmx core and an extension (e.g., response-targets) from a CDN into the head of your HTML document. Ensure the core library is included before extensions. ```html ... ``` -------------------------------- ### htmx Button Example Source: https://htmx.org/docs An htmx-enabled button that triggers an HTTP POST request on click and updates a target element with the response. ```html ``` -------------------------------- ### Attribute Inheritance Example Source: https://htmx.org/docs Demonstrates how htmx attributes like hx-confirm can be inherited by child elements. This reduces code duplication by applying attributes at a higher DOM level. ```html
``` -------------------------------- ### HTMX Load Polling Example Source: https://htmx.org/docs This snippet demonstrates load polling, where an element repeatedly fetches content from a URL at a specified interval. It's useful for progress indicators or status updates that have a natural end point. ```html
``` -------------------------------- ### Basic Content Security Policy Source: https://htmx.org/docs Example of a Content Security Policy (CSP) meta tag that restricts requests to the origin domain. This can be used in conjunction with HTMX's security configurations for layered security. ```html ``` -------------------------------- ### Out-of-Band Swap within a Template for Table Rows Source: https://htmx.org/docs This example uses a template tag to encapsulate a table row for an out-of-band swap. This is necessary because elements like 'tr' cannot stand alone in the DOM according to HTML specifications. ```html ``` -------------------------------- ### GET Request on Control-Click Source: https://htmx.org/docs This div triggers a GET request to '/clicked' only when the element is control-clicked. ```html
Control Click Me
``` -------------------------------- ### HTMX Target Attribute for Live Search Source: https://htmx.org/docs Illustrates the use of the 'hx-target' attribute to specify a different DOM element for loading the response. This example shows results being loaded into a dedicated div for a live search input. ```html
``` -------------------------------- ### Active Search Input Source: https://htmx.org/docs This input field triggers a GET request to '/trigger_delay' with a 500ms delay after typing, updating '#search-results'. ```html
``` -------------------------------- ### Polling GET Request Source: https://htmx.org/docs This div polls the '/news' URL every 2 seconds. ```html
``` -------------------------------- ### Custom Validation with hx-on Source: https://htmx.org/docs This example demonstrates how to use the hx-on attribute to catch the htmx:validation:validate event for custom input validation. It requires the input value to be 'foo' and reports the issue if it's not. ```html
``` -------------------------------- ### Programmatic Request Cancellation with htmx:abort Event Source: https://htmx.org/docs This example shows how to cancel an in-flight htmx request programmatically. Clicking the 'Cancel Request' button triggers the 'htmx:abort' event on the 'Issue Request' button, canceling its ongoing POST request. ```html ``` -------------------------------- ### Initialize Library with htmx.onLoad Source: https://htmx.org/docs Utilize the `htmx.onLoad` helper function to initialize third-party libraries when content is loaded by htmx. This is a cleaner alternative to manually listening for 'htmx:load'. ```javascript htmx.onLoad(function(target) { myJavascriptLib.init(target); }); ``` -------------------------------- ### Include downloaded htmx.min.js Source: https://htmx.org/docs Includes a locally downloaded copy of the minified htmx library using a script tag. ```html ``` -------------------------------- ### Listen for htmx Events with htmx.on Source: https://htmx.org/docs Use the htmx helper function `htmx.on` to register a listener for htmx events. This provides a more concise way to handle events like 'htmx:load'. ```javascript htmx.on("htmx:load", function(evt) { myJavascriptLib.init(evt.detail.elt); }); ``` -------------------------------- ### Basic Form with Input Validation Source: https://htmx.org/docs This HTML demonstrates a form submission and an input validation request without synchronization. Without hx-sync, both requests can trigger in parallel, potentially leading to race conditions. ```html
``` -------------------------------- ### Initialize SortableJS with jQuery Source: https://htmx.org/docs This JavaScript snippet demonstrates how to initialize SortableJS on elements with the class 'sortable' using jQuery's document ready function. ```javascript $(document).ready(function() { var sortables = document.body.querySelectorAll(".sortable"); for (var i = 0; i < sortables.length; i++) { var sortable = sortables[i]; new Sortable(sortable, { animation: 150, ghostClass: 'blue-background-class' }); } }); ``` -------------------------------- ### Enable AJAX for Anchors and Forms with hx-boost Source: https://htmx.org/docs Use the 'hx-boost' attribute on a parent element to convert all descendant anchors and forms into AJAX requests. This provides a smoother user experience by default. ```html
Blog
``` -------------------------------- ### Original HTML Content Source: https://htmx.org/docs This is the initial state of a div element before being updated by htmx. ```html
Original Content
``` -------------------------------- ### Process Dynamically Loaded HTML with htmx Source: https://htmx.org/docs This JavaScript snippet demonstrates how to fetch HTML content and process it with htmx after setting it as innerHTML, ensuring any htmx attributes in the new content are initialized. ```javascript let myDiv = document.getElementById('my-div') fetch('http://example.com/movies.json') .then(response => response.text()) .then(data => { myDiv.innerHTML = data; htmx.process(myDiv); } ); ``` -------------------------------- ### htmx `hx-on` Attribute for Click Events Source: https://htmx.org/docs Shows how to use the `hx-on:click` attribute to respond to a click event, mirroring the functionality of the standard `onclick` attribute but within the htmx framework. ```html ``` -------------------------------- ### Custom Confirmation with SweetAlert2 Source: https://htmx.org/docs Implement asynchronous confirmation dialogs using the 'htmx:confirm' event and a library like SweetAlert2. This allows for more sophisticated user interactions. ```javascript document.body.addEventListener('htmx:confirm', function(evt) { if (evt.target.matches("[confirm-with-sweet-alert='true']")) { evt.preventDefault(); swal({ title: "Are you sure?", text: "Are you sure you are sure?", icon: "warning", buttons: true, dangerMode: true, }).then((confirmed) => { if (confirmed) { evt.detail.issueRequest(); } }); } }); ``` -------------------------------- ### Basic PUT Request Source: https://htmx.org/docs This snippet shows a basic button that issues a PUT request to '/messages' when clicked. ```html ``` -------------------------------- ### POST Request on Mouse Enter (Once) Source: https://htmx.org/docs This div triggers a POST request to '/mouse_entered' only once when the mouse enters it. ```html
[Here Mouse, Mouse!]
``` -------------------------------- ### Import htmx in Webpack Source: https://htmx.org/docs Imports the htmx library into a Webpack project's entry point. ```javascript import 'htmx.org'; ``` -------------------------------- ### Standard HTML Inline Scripting Source: https://htmx.org/docs Demonstrates the traditional HTML `onclick` attribute for embedding inline scripts directly within an element. This is useful for simple, element-specific JavaScript. ```html ``` -------------------------------- ### Log All HTMX Events Source: https://htmx.org/docs Call the `htmx.logAll()` method to log every event that HTMX triggers. This provides a comprehensive view of the library's actions for debugging purposes. ```javascript htmx.logAll(); ``` -------------------------------- ### Expose htmx to window scope in Webpack Source: https://htmx.org/docs Makes the htmx library globally accessible via the `window.htmx` variable in a Webpack project. ```javascript window.htmx = require('htmx.org'); ``` -------------------------------- ### Initialize TomSelect on New Content Source: https://htmx.org/docs This snippet initializes TomSelect on elements with the class 'tomselect' within newly loaded content. It's used to enhance select elements with rich user experiences. ```javascript htmx.onLoad(function (target) { // find all elements in the new content that should be // an editor and init w/ TomSelect var editors = target.querySelectorAll(".tomselect") .forEach(elt => new TomSelect(elt)) }); ``` -------------------------------- ### POST Request on Mouse Enter Source: https://htmx.org/docs This div triggers a POST request to '/mouse_entered' when the mouse enters it. ```html
[Here Mouse, Mouse!]
``` -------------------------------- ### Import htmx Extensions in Bundler Source: https://htmx.org/docs Import htmx.org and an extension (e.g., htmx-ext-extension-name) into your main JavaScript file when using a bundler like Webpack or Rollup. ```javascript import `htmx.org`; import `htmx-ext-extension-name`; // replace `extension-name` with the name of the extension ``` -------------------------------- ### Initialize SortableJS with htmx onLoad Source: https://htmx.org/docs This JavaScript snippet shows how to initialize SortableJS using htmx's `onLoad` function, ensuring that sortable elements are initialized only within newly loaded content. ```javascript htmx.onLoad(function(content) { var sortables = content.querySelectorAll(".sortable"); for (var i = 0; i < sortables.length; i++) { var sortable = sortables[i]; new Sortable(sortable, { animation: 150, ghostClass: 'blue-background-class' }); } }) ``` -------------------------------- ### Conditional Content Loading with AlpineJS and htmx Source: https://htmx.org/docs This HTML snippet uses AlpineJS to conditionally render content. It utilizes `$watch` to detect changes and `htmx.process` to initialize htmx attributes within the newly displayed content. ```html
``` -------------------------------- ### Configure htmx to Swap All Responses Source: https://htmx.org/docs This configuration ensures that all HTTP responses, regardless of their code, will be swapped by htmx. This is useful for scenarios where every response should update the DOM. ```html ``` -------------------------------- ### Handle HTMX Swap Events Source: https://htmx.org/docs Listen for the 'htmx:beforeSwap' event to modify swap behavior based on HTTP status codes. Useful for handling errors like 404, 422, or custom codes like 418. ```javascript document.body.addEventListener('htmx:beforeSwap', function(evt) { if(evt.detail.xhr.status === 404){ // alert the user when a 404 occurs (maybe use a nicer mechanism than alert()) alert("Error: Could Not Find Resource"); } else if(evt.detail.xhr.status === 422){ // allow 422 responses to swap as we are using this as a signal that // a form was submitted with bad data and want to rerender with the // errors // // set isError to false to avoid error logging in console evt.detail.shouldSwap = true; evt.detail.isError = false; } else if(evt.detail.xhr.status === 418){ // if the response code 418 (I'm a teapot) is returned, retarget the // content of the response to the element with the id `teapot` evt.detail.shouldSwap = true; evt.detail.target = htmx.find("#teapot"); } }); ``` -------------------------------- ### htmx with data- prefix Source: https://htmx.org/docs An alternative syntax for htmx attributes using the 'data-' prefix, functionally equivalent to standard htmx attributes. ```html Click Me! ``` -------------------------------- ### HTMX Request Indicator with Image Source: https://htmx.org/docs Shows how to display a loading indicator (e.g., a spinner GIF) while an AJAX request is in progress. The indicator is hidden by default and shown when the requesting element receives the 'htmx-request' class. ```html ``` -------------------------------- ### Enable htmx Extension Source: https://htmx.org/docs Enable an htmx extension by adding the `hx-ext` attribute to an HTML element, such as the body. This applies the extension to all child elements. ```html ...
... ``` -------------------------------- ### CSS Transition Definition Source: https://htmx.org/docs This CSS defines a transition for elements with the 'red' class, applying a color change over 1 second. When htmx swaps content, elements with stable IDs and new classes will animate smoothly. ```css .red { color: red; transition: all ease-in 1s ; } ``` -------------------------------- ### Basic Anchor Tag Source: https://htmx.org/docs A standard HTML anchor tag that instructs the browser to navigate to a URL upon click. ```html Blog ``` -------------------------------- ### Out-of-Band Swap with Direct ID Targeting Source: https://htmx.org/docs This HTML snippet demonstrates an out-of-band swap. The div with id 'message' will be swapped directly into the DOM, while 'Additional Content' is swapped normally. ```html
Swap me directly!
Additional Content ``` -------------------------------- ### Push URL to Browser History Source: https://htmx.org/docs Use the 'hx-push-url' attribute on an element to push its request URL into the browser's navigation bar and add the current page state to history. This allows users to navigate back to previous states using the browser's history controls. ```html Blog ``` -------------------------------- ### Progressive Enhancement for Active Search with Forms Source: https://htmx.org/docs Wrap htmx-enhanced inputs within a form element to ensure graceful degradation for users without JavaScript. This allows non-JavaScript clients to still perform searches. ```html
``` -------------------------------- ### Listen for htmx Events with addEventListener Source: https://htmx.org/docs Register an event listener for htmx events, such as 'htmx:load', on a specific DOM element like document.body. This can be used for initialization or logging. ```javascript document.body.addEventListener('htmx:load', function(evt) { myJavascriptLib.init(evt.detail.elt); }); ``` -------------------------------- ### htmx `hx-on` for Custom Event `htmx:config-request` Source: https://htmx.org/docs Illustrates using `hx-on:htmx:config-request` to modify request parameters before a POST request is sent. This is a powerful way to dynamically alter outgoing requests using htmx events. ```html ``` -------------------------------- ### New HTML Content with CSS Class Source: https://htmx.org/docs This represents the new content that htmx will swap in. It has the same ID as the original content but includes an additional 'red' class, enabling CSS transitions. ```html
New Content
``` -------------------------------- ### Set Custom HTMX Logger Source: https://htmx.org/docs Configure a custom logger function for HTMX to log all triggered events. This is helpful for debugging and understanding library activity. ```javascript htmx.logger = function(elt, event, data) { if(console) { console.log(event, elt, data); } } ``` -------------------------------- ### CSRF Token Header on HTML Element Source: https://htmx.org/docs Demonstrates how to add a CSRF token to outgoing requests using the 'hx-headers' attribute on the 'html' element. This ensures that all HTMX requests originating from this document include the specified CSRF token. ```html : ``` -------------------------------- ### Monitor Events on an Element Source: https://htmx.org/docs Use the `monitorEvents()` function in the browser console to observe all events occurring on a specific DOM element. This helps identify triggers for HTMX actions. ```javascript monitorEvents(htmx.find("#theElement")); ``` -------------------------------- ### Confirming a Delete Request Source: https://htmx.org/docs Use the hx-confirm attribute to display a JavaScript confirmation dialog before executing a request. This is useful for destructive actions. ```html ``` -------------------------------- ### Configure htmx Response Handling for Validation Errors Source: https://htmx.org/docs This configuration allows htmx to swap content for 2xx, 3xx, and specific 422 responses, while treating other 4xx and 5xx responses as errors. It also explicitly sets 204 No Content to not swap. ```html ``` -------------------------------- ### HTMX Explicit Request Indicator Targeting Source: https://htmx.org/docs Demonstrates how to explicitly specify which element should receive the 'htmx-request' class to control the visibility of a request indicator. This is done using the 'hx-indicator' attribute with a CSS selector. ```html
Loading...
``` -------------------------------- ### Configure Request with htmx Events Source: https://htmx.org/docs Handle the 'htmx:configRequest' event to modify outgoing AJAX requests. This allows adding custom headers or parameters before the request is sent. ```javascript document.body.addEventListener('htmx:configRequest', function(evt) { evt.detail.parameters['auth_token'] = getAuthToken(); // add a new parameter into the request evt.detail.headers['Authentication-Token'] = getAuthToken(); // add a new header into the request }); ``` -------------------------------- ### Set Default Swap Style with Meta Tag Source: https://htmx.org/docs Configure htmx to use 'outerHTML' as the default swap style by including a meta tag in your HTML. This setting affects how new content replaces existing content. ```html ``` -------------------------------- ### Disabling Attribute Inheritance Source: https://htmx.org/docs Shows how to disable attribute inheritance for specific elements using 'hx-confirm="unset"'. This prevents an inherited attribute from applying to a particular child element. ```html
``` -------------------------------- ### CSRF Token Header on Body Element Source: https://htmx.org/docs Shows how to apply CSRF protection by setting the 'hx-headers' attribute on the 'body' element. This method is useful for ensuring all HTMX requests include the CSRF token, especially when the 'html' element is not directly accessible or modifiable. ```html : ``` -------------------------------- ### Synchronized Form Input Validation with hx-sync Source: https://htmx.org/docs This HTML uses hx-sync="closest form:abort" on the input to abort its validation request if a form submission request is active. This ensures that the form submission takes precedence. ```html
``` -------------------------------- ### HTMX Request Indicator CSS Source: https://htmx.org/docs Provides CSS rules for managing the visibility of request indicators. It uses the 'htmx-indicator' class to hide elements by default and the 'htmx-request' class to show them during an active request. ```css .htmx-indicator{ display:none; } .htmx-request .htmx-indicator{ display:inline; } .htmx-request.htmx-indicator{ display:inline; } ``` -------------------------------- ### Clean TomSelect Mutations Before History Save Source: https://htmx.org/docs This event listener catches the 'htmx:beforeHistorySave' event to clean up DOM mutations made by TomSelect. It calls the 'destroy()' method on all TomSelect elements to revert the DOM for a clean history snapshot. ```javascript htmx.on('htmx:beforeHistorySave', function() { // find all TomSelect elements document.querySelectorAll('.tomSelect') .forEach(elt => elt.tomselect.destroy()) // and call destroy() on them }) ``` -------------------------------- ### htmx Swap with OuterHTML and IgnoreTitle Option Source: https://htmx.org/docs This snippet demonstrates how to use the `outerHTML` swap strategy combined with the `ignoreTitle:true` modifier. Use this when you want to replace the entire target element with new content and prevent htmx from updating the document's title with any title found in the response. ```html ``` -------------------------------- ### Validate URLs with htmx:validateUrl Event Source: https://htmx.org/docs Intercept and validate outgoing request URLs using the `htmx:validateUrl` event listener. This allows you to enforce custom rules, such as restricting requests to the same host or specific domains, by calling `preventDefault()` on invalid URLs. ```javascript document.body.addEventListener('htmx:validateUrl', function (evt) { // only allow requests to the current server as well as myserver.com if (!evt.detail.sameHost && evt.detail.url.hostname !== "myserver.com") { evt.preventDefault(); } }); ``` -------------------------------- ### SortableJS Integration with htmx Source: https://htmx.org/docs This HTML snippet shows a form with htmx attributes that can be used with SortableJS. The `hx-trigger='end'` attribute ensures htmx requests are sent after sorting is complete. ```html
Updating...
Item 1
Item 2
Item 3
``` -------------------------------- ### Disable htmx Processing with hx-disable Source: https://htmx.org/docs Use the `hx-disable` attribute on a container element to prevent htmx from processing any htmx-related attributes or features within that element and its children. This is useful when injecting untrusted raw HTML content. ```html
<%= raw(user_content) %>
``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.