### Mock Server Setup for HTMX Scrolling Tests
Source: https://github.com/bigskysoftware/htmx/blob/master/www/static/test/manual/intersect-test-eventHandler.html
Sets up a mock server to respond to GET requests for '/more_content' with specific HTML. This is used to simulate remote content loading triggered by scrolling events in HTMX.
```javascript
var server = makeServer(); server.autoRespond = true; server.respondWith("GET", "/more_content", "Here is more content for this page, loaded 'remotely'.");
```
--------------------------------
### Mock Server Setup and Response for HTMX
Source: https://github.com/bigskysoftware/htmx/blob/master/www/static/test/manual/poll-condition-test.html
This snippet demonstrates setting up a mock server to intercept GET requests to '/more_divs' and respond with HTML content. It's useful for testing HTMX interactions without a live backend.
```javascript
var server = makeServer();
server.autoRespond = true;
server.respondWith("GET", "/more_divs", "
More Content
");
```
--------------------------------
### Basic hx-put Example
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/docs.md
This example demonstrates how to issue a PUT request to a URL when a button is clicked, loading the response into the button itself.
```html
```
--------------------------------
### Mock Server Setup for HTMX Scroll Testing
Source: https://github.com/bigskysoftware/htmx/blob/master/test/manual/intersect-test-eventHandler.html
Configures a mock server to respond to GET requests for remote content loading. This is essential for simulating asynchronous data fetching during scroll events.
```javascript
const server = makeServer();
server.autoRespond = true;
server.respondWith("GET", "/more_content", "Here is more content for this page, loaded 'remotely'.");
```
--------------------------------
### Install Dependencies and Run Tests (Bash)
Source: https://github.com/bigskysoftware/htmx/blob/master/TESTING.md
Installs project dependencies and runs the test suite. Playwright is automatically installed during test runs.
```bash
npm install
npm run test
```
--------------------------------
### Install Development Dependencies
Source: https://github.com/bigskysoftware/htmx/blob/master/README.md
Install the necessary development dependencies for working on the htmx library locally using npm.
```bash
npm install
```
--------------------------------
### HTML Button with htmx and View Transition Attribute
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/essays/view-transitions.md
An HTML example showing a div with the 'sample-transition' class and a button that triggers an htmx GET request. The `hx-swap` attribute includes `transition:true` to enable View Transitions.
```html
Initial Content
```
--------------------------------
### Demo Example with Mock Responses
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/docs.md
This example demonstrates using the demo script to create a button that increments a counter, with mock responses for the '/foo' URL delayed by 500ms. The response content is dynamically generated using a template tag and a JavaScript variable.
```html
${globalInt++}
```
--------------------------------
### HTML for CSS Transition Example
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/docs.md
This is the initial HTML content that will be replaced.
```html
Original Content
```
--------------------------------
### HTMX Server Response Setup
Source: https://github.com/bigskysoftware/htmx/blob/master/www/static/test/scratch/scratch.html
Configures the server to respond to specific GET requests. It allows defining custom responses, including dynamic content generation with request counts and random strings. This is useful for simulating API endpoints during development or testing.
```javascript
this.server.respondWith("GET", "/test", function(xhr){
xhr.respond(200, {}, "Clicked!");
});
this.server.respondWith("GET", "/demo", function(xhr){
let randomStr = (Math.random() + 1).toString(36).substring(7);
xhr.respond(200, {}, "Request #" + requestCount++ + " : " + randomStr);
});
this.server.respondWith("GET", "/new-content", function(xhr){
xhr.respond(200, {}, "
Initial Content
");
});
this.server.respondWith("GET", "/original-content", function(xhr){
xhr.respond(200, {}, originalContent);
});
```
--------------------------------
### Install htmx-1-compat via npm
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/htmx-1-compat.md
Install the htmx-1-compat package using npm. Bundle the extension with htmx core and project code.
```Shell
npm install htmx-ext-htmx-1-compat
```
--------------------------------
### Client Request with Cookie
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/essays/web-security-basics-with-htmx.md
Shows an example of an HTTP GET request from a client to a server, including the 'Cookie' header. This demonstrates how the browser automatically sends previously set cookies back to the originating domain.
```http
GET /users HTTP/1.1
Host: yourdomain.com
Cookie: token=asd8234nsdfp982
```
--------------------------------
### Install htmx using npm
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/docs.md
Install the htmx.org package using npm for use in npm-style build systems.
```sh
npm install htmx.org@2.0.10
```
--------------------------------
### Install Workbox CLI
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/essays/you-cant.md
Installs the Workbox command-line interface globally, which is used to automate the generation of service workers and their configurations.
```bash
npm install workbox-cli --global
```
--------------------------------
### Install htmx Response Targets Extension via npm
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/response-targets.md
Install the extension using npm. This is suitable for projects using module bundlers like Webpack or Rollup.
```shell
npm install htmx-ext-response-targets
```
--------------------------------
### Install WebSocket Extension
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/ws.md
Use the `hx-ext="ws"` attribute to install the WebSockets extension into any HTML element. This enables WebSocket functionality for that element and its children.
```html
...
```
--------------------------------
### Install Idiomorph via npm
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/idiomorph.md
Install the idiomorph package using npm. You will need to use a bundler to include the extension in your project.
```shell
npm install idiomorph
```
--------------------------------
### Install htmx Head Support Extension via npm
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/head-support.md
Install the extension using npm and then import both htmx and the extension in your JavaScript entry point for use with bundlers like Webpack or Rollup.
```shell
npm install htmx-ext-head-support
```
```javascript
import `htmx.org`;
import `htmx-ext-head-support`;
```
--------------------------------
### HTTP GET Request for Bank Account Resource
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/essays/hateoas.md
A simple HTTP GET request to fetch a bank account resource. This is a foundational request in the example, demonstrating how a client might initiate interaction with a REST endpoint.
```txt
GET /accounts/12345 HTTP/1.1
Host: bank.example.com
```
--------------------------------
### Server Respond with Dynamic Content
Source: https://github.com/bigskysoftware/htmx/blob/master/test/scratch/scratch.html
Sets up a server response for a GET request to '/demo'. Each response includes a unique request count and a random string, demonstrating dynamic content generation.
```javascript
let requestCount = 0;
this.server.respondWith("GET", "/demo", function(xhr){
let randomStr = (Math.random() + 1).toString(36).substring(7);
xhr.respond(200, {}, "Request #" + requestCount++ + " : " + randomStr)
});
```
--------------------------------
### Boosted Links Example - HTML
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/attributes/hx-boost.md
This example demonstrates how to use the hx-boost attribute on a parent div to enable AJAX requests for all anchor tags within it. Clicking these links will issue a GET request to the specified URL and replace the body's inner content.
```html
```
--------------------------------
### Run All Tests Across All Browsers Headless (Bash)
Source: https://github.com/bigskysoftware/htmx/blob/master/TESTING.md
Runs all tests headlessly across Chrome, Firefox, and WebKit using Playwright's setup.
```bash
npm run test:all
```
--------------------------------
### HTML Structure with htmx
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/essays/view-transitions.md
Sets up the initial HTML content with a div having the class 'sample-transition' to enable the view transition. It includes a button that triggers an htmx GET request to '/new-content' on click, swapping the innerHTML of the closest div and enabling transitions.
```html
Initial Content
```
--------------------------------
### Install htmx-1-compat via CDN
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/htmx-1-compat.md
Include the core htmx library and the htmx-1-compat extension via CDN. Enable the extension on the body tag.
```HTML
...
```
--------------------------------
### Trigger Server Callbacks with SSE Events
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/sse.md
Use `hx-trigger` with the `sse:` syntax to trigger HTMX requests when specific SSE events are received. This example triggers a GET request to `/chatroom` when the `chatter` event occurs.
```html
...
```
--------------------------------
### Install htmx and SSE Extension via CDN
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/sse.md
Include the core htmx library and the SSE extension script from a CDN in the `` section. Enable the extension globally by adding `hx-ext="sse"` to the `` tag.
```HTML
```
--------------------------------
### Run Tests in Headed Mode with Debugging (Bash)
Source: https://github.com/bigskysoftware/htmx/blob/master/TESTING.md
Starts the web-test-runner server and opens the test runner in a browser in headed mode, allowing for debugging. Test logs will appear in the browser's developer tools console.
```bash
npm run test:debug
```
--------------------------------
### Setup HTMX Scroll Behavior Test
Source: https://github.com/bigskysoftware/htmx/blob/master/www/static/test/manual/poll-clears-on-reinit-test.html
Initializes a mock server and configures a response for the scroll behavior test.
```javascript
server = makeServer(); server.autoRespond = true; server.respondWith("GET", "/more_divs", "
More Content
");
```
--------------------------------
### Basic WebSocket Chatroom Setup
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/ws.md
Establish a WebSocket connection to '/chatroom' using ws-connect. Messages sent from the form with ws-send will be serialized as JSON and sent to the WebSocket. Content received from the WebSocket will be parsed as HTML and swapped.
```html
...
```
--------------------------------
### HTMX View Transitions API Demo Script
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/examples/animations.md
A JavaScript snippet demonstrating the server-side responses for the View Transitions API example. It uses `this.server.respondWith` to mock GET requests for '/new-content' and '/original-content', returning HTML that facilitates the content swap and transition.
```javascript
var originalContent = htmx.find(".slide-it").innerHTML;
this.server.respondWith("GET", "/new-content", function(xhr){
xhr.respond(200, {}, "
New Content
")
});
this.server.respondWith("GET", "/original-content", function(xhr){
xhr.respond(200, {}, originalContent)
});
```
--------------------------------
### Install htmx and Head Support Extension via CDN
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/head-support.md
Include both the core htmx library and the head-support extension script in the `` of your HTML document. Enable the extension by adding `hx-ext="head-support"` to the `` tag.
```html
...
```
--------------------------------
### JavaScript Fake Server-Side Code
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/examples/edit-row.md
Simulates server-side logic for handling HTMX requests. It includes functions to initialize routes, handle GET requests for contacts (display or edit views), and uses template functions to generate HTML responses.
```javascript
//=========================================================================
// Fake Server Side Code
//=========================================================================
// data
var contacts = [
{
name: "Joe Smith",
email: "joe@smith.org",
status: "Active",
id: 0
},
{
name: "Angie MacDowell",
email: "angie@macdowell.org",
status: "Active",
id: 1
},
{
name: "Fuqua Tarkenton",
email: "fuqua@tarkenton.org",
status: "Active",
id: 2
},
{
name: "Kim Yee",
email: "kim@yee.org",
status: "Inactive",
id: 3
},
];
// routes
init("/demo", function(request, params){
return tableTemplate(contacts);
});
onGet(//contact/d+/, function(request, params){
var id = parseInt(request.url.split("/")[2]); // get the contact
var contact = contacts[id];
console.log(request, id, contact)
if(request.url.endsWith("/edit")) {
return editTemplate(contacts[id])
} else {
return rowTemplate(contacts[id])
}
});
```
--------------------------------
### Serve htmx Locally
Source: https://github.com/bigskysoftware/htmx/blob/master/README.md
Start a local web server in the root directory of the htmx project using npx serve to facilitate local development and testing.
```bash
npx serve
```
--------------------------------
### Serve HTMX Website Locally with Zola
Source: https://github.com/bigskysoftware/htmx/blob/master/www/README.md
This snippet demonstrates the command-line steps to serve the htmx.org website locally. It assumes Zola is installed and the user is in the root of the repository. The command navigates to the 'www' directory and starts the Zola development server.
```shell
cd www
zola serve
```
--------------------------------
### HTML Row for Display and Edit Trigger
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/examples/edit-row.md
Represents a single table row in its display state. It includes an 'Edit' button that triggers an HTMX GET request to fetch the editable version of the row. JavaScript is used to ensure only one row can be edited at a time.
```html
${contact.name}
${contact.email}
```
--------------------------------
### Initial UI Setup with htmx Form
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/examples/update-other-content.md
Sets up a basic HTML structure with a contacts table and a form to add new contacts. The form uses hx-post to submit data to the /contacts endpoint. This snippet serves as the starting point for demonstrating content update techniques.
```html
Contacts
Name
Email
...
Add A Contact
```
--------------------------------
### Configure Preload on Mouse Over
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/preload.md
Configure the preload extension to trigger resource loading when the user's mouse hovers over a link, with a 100ms delay. This offers more aggressive preloading but can increase server load.
```html
This will be preloaded when the user's mouse remains over it for more than
100ms.
```
--------------------------------
### HTML Structure for Cascading Selects with HTMX
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/examples/value-select.md
Defines the HTML for two select elements, 'Make' and 'Model'. The 'Make' select uses HTMX attributes to trigger a GET request to '/models' upon change, targeting the '#models' element to update its options. Includes an HTMX indicator for visual feedback during requests.
```html
```
--------------------------------
### Trigger htmx Event with hyperscript
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/migration-guide-hotwire-turbo.md
This example uses hyperscript to handle a 'submit' event, halt the event, perform an action, and then trigger a 'ready' event. This approach allows for more complex client-side logic and can resolve asynchronous calls, providing a powerful alternative to traditional JavaScript event handling.
```hyperscript
_='on submit halt the event action(target) trigger ready'
```
--------------------------------
### Install htmx as a Node Package
Source: https://github.com/bigskysoftware/htmx/blob/master/README.md
Install the htmx library using npm for use in Node.js projects. Ensure you install `htmx.org` and not the old `htmx` package.
```bash
npm install htmx.org --save
```
--------------------------------
### Install htmx and Preload Extension via CDN
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/preload.md
Include the core htmx library and the preload extension script from a CDN in your HTML head. Enable the extension on the body element using `hx-ext="preload"`.
```HTML
...
```
--------------------------------
### JavaScript: Fake Server-Side Logic for Progress Bar
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/examples/progress-bar.md
This JavaScript code simulates server-side logic for the progress bar example. It includes functions to initialize routes, handle POST requests to '/start', GET requests to '/job' and '/job/progress', and template functions to generate HTML for different states of the progress bar. The '/job/progress' route triggers a 'done' event when the job is complete.
```javascript
//=========================================================================
// Fake Server Side Code
//=========================================================================
// routes
init("/demo", function(request, params){
return startButton("Start Progress");
});
onPost("/start", function(request, params){
var job = jobManager.start();
return jobStatusTemplate(job);
});
onGet("/job", function(request, params){
var job = jobManager.currentProcess();
return jobStatusTemplate(job);
});
onGet("/job/progress", function(request, params, responseHeaders){
var job = jobManager.currentProcess();
if (job.complete) {
responseHeaders["HX-Trigger"] = "done";
}
return jobProgressTemplate(job);
});
// templates
function startButton(message) {
return `
${message}
`;
}
function jobProgressTemplate(job) {
```
--------------------------------
### Mock Server Setup for HTMX Prompt and Confirm
Source: https://github.com/bigskysoftware/htmx/blob/master/test/manual/confirm-and-prompt.html
Configures a mock server to intercept HTMX requests. It handles the HX-Prompt header for prompt interactions and provides a standard response for confirm actions.
```javascript
const server = makeServer();
server.autoRespond = true;
server.respondWith("GET", "/prompt", function(xhr) {
xhr.respond(200, {}, "You entered: " + xhr.requestHeaders["HX-Prompt"]);
});
server.respondWith("GET", "/confirm", function(xhr) {
xhr.respond(200, {}, "Confirmed");
});
```
--------------------------------
### HTML Example of RESTful Resource Representation
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/essays/rest-explained.md
This HTML snippet demonstrates how a resource (a contact) can be represented with its data and links to related actions. It serves as a simple illustration of the Uniform Interface principle in REST, showing how resources are identified and manipulated through representations.
```html
```
--------------------------------
### SSE Connection Setup Event
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/sse.md
Details about the event dispatched when an SSE connection is set up on an element.
```APIDOC
## htmx:sseConnect Event
### Description
This event is dispatched when an SSE connection is set up.
### Details
* `detail.elt` - The element on which the SSE connection was setup. This is the element which has the `sse-connect` attribute.
* `detail.source` - The [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) object.
```
--------------------------------
### Dynamic Content Fetching with HTMX and CSS Toggling
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/essays/you-cant.md
This example combines the CSS-based content toggling with HTMX to fetch content dynamically. When the element with the `hx-trigger="intersect once"` attribute becomes visible (due to the `peer-checked:block` class), HTMX makes a GET request to the specified endpoint (`/log-item`). This allows for lazy loading of content when a user interacts with the toggle.
```html
Shell/Loading text etc
```
--------------------------------
### Out-of-Band Swap Examples for WebSocket Messages
Source: https://github.com/bigskysoftware/htmx/blob/master/www/content/extensions/ws.md
Demonstrates how to specify swapping methods for incoming WebSocket messages. Content can be marked for out-of-band swapping using hx-swap-oob, with options for default behavior, appending, or using custom swap methods like 'morphdom'.
```html