### X-Up-Location and X-Up-Method header example
Source: https://unpoly.com/X-Up-Location
An example of setting the X-Up-Location and X-Up-Method headers in an HTTP response.
```http
X-Up-Location: /current-url
X-Up-Method: GET
```
--------------------------------
### Example X-Up-Reload-From-Time header
Source: https://unpoly.com/X-Up-Reload-From-Time
An example showing the X-Up-Target and X-Up-Reload-From-Time headers for a modification date of December 23rd, 1:40:18 PM UTC.
```http
X-Up-Target: .unread-count
X-Up-Reload-From-Time: 1608730818
```
--------------------------------
### HTML link examples with up-instant
Source: https://unpoly.com/up%3Aclick
Example showing two links, where the second link uses the up-instant attribute to trigger activation on mousedown.
```html
Link 1Link 2
```
--------------------------------
### X-Up-Fail-Target Header Example
Source: https://unpoly.com/X-Up-Fail-Target
Example of the X-Up-Fail-Target header usage, showing how to target a specific selector for failed updates.
```APIDOC
## X-Up-Fail-Target Header
### Description
This request header contains the target selector for a failed fragment update. A fragment update is considered failed if the server responds with a status code other than 2xx, but still renders HTML.
### Header Name
X-Up-Fail-Target
### Usage
Send this header with a request to indicate the selector that should be updated when the response is a failure (non-2xx).
### Example
```
X-Up-Target: .menu
X-Up-Fail-Target: body
```
```
--------------------------------
### Usage examples for up.util.wrapList
Source: https://unpoly.com/up.util.wrapList
Demonstrates how up.util.wrapList handles arrays, strings, and null/undefined values.
```javascript
up.util.wrapList([1, 2, 3]) [1, 2, 3]
up.util.wrapList('foo') ['foo']
up.util.wrapList(undefined) []
up.util.wrapList(null) []
```
--------------------------------
### Example of meta tags in
Source: https://unpoly.com/changes/3.5.0
This example shows the structure of meta tags and links in the that are synchronized during history updates.
```html
AcmeCorp
```
--------------------------------
### Navigate to a URL with up.visit
Source: https://unpoly.com/up.visit
This example demonstrates how to replace the current page content with the response from the /users endpoint.
```javascript
up.visit('/users')
```
--------------------------------
### up.render() error handling example
Source: https://unpoly.com/render-lifecycle
Example demonstrating how to handle various error cases when calling up.render(), including server errors, target not found, aborted requests, offline conditions, and compiler errors.
```APIDOC
## up.render() error handling
### Description
Demonstrates handling errors thrown by up.render() and up.render().finished, including server errors, target not found, aborted requests, offline conditions, and compiler errors.
### Method
up.render()
### Parameters
#### Options
- **url** (string) - Required - The URL to render.
- **target** (string) - Required - Selector to replace for 200 OK status.
- **failTarget** (string) - Optional - Selector to replace for non-200 status.
### Error Handling
- **up.RenderResult** - Thrown when server responds with non-200 HTTP status.
- **up.CannotMatch** - Thrown when target selector is not found.
- **up.Aborted** - Thrown when fragment update is aborted.
- **up.Offline** - Thrown on disconnect or timeout.
- **error event** - Emitted on window when a compiler throws an error.
### Example
```javascript
try {
window.addEventListener('error', function(event) {
console.log('Compiler threw error', event.error)
})
let result = await up.render({
url: '/path',
target: '.target', // selector to replace for 200 OK status
failTarget: '.errors' // selector to replace for non-200 status
})
} catch (error) {
if (error instanceof up.RenderResult) {
// Server sent HTML with a non-200 status code
console.log("Updated .errors with", error.fragments)
} else if (error instanceof up.CannotMatch) {
console.log("Could not find .target in current page or response")
} else if (error instanceof up.Aborted) {
console.log("Request to aborted")
} else if (error instanceof up.Offline) {
console.log("Connection loss or timeout")
} else {
console.log("Other error while rendering: ", error)
}
}
```
```
--------------------------------
### Example: Using up.layer.descendants
Source: https://unpoly.com/up.Layer.prototype.descendants
Shows how to access descendant layers after opening a modal. The example opens a layer, then checks the descendants of the current layer (empty) and the root layer (contains the modal).
```javascript
up.layer.open()
up.layer.current // returns up.Layer.Modal
up.layer.current.descendants // returns []
up.layer.root.descendants // returns [up.Layer.Modal]
```
--------------------------------
### Request headers for overlay mode
Source: https://unpoly.com/optimizing-responses
Example headers indicating an overlay mode and target.
```http
X-Up-Mode: drawer
X-Up-Target: main
```
--------------------------------
### Implementing up.util.copy.key protocol
Source: https://unpoly.com/up.util.copy.key
Example of a user-defined Account class implementing the up.util.copy.key protocol method to support up.util.copy().
```APIDOC
## up.util.copy.key
### Description
Defines a protocol method that user-defined classes may implement to hook into the up.util.copy() protocol. The method should return a copy of the instance.
### Value
- **key** (string) - The name of the method to implement.
### Example
```
class Account {
constructor(email) {
this.email = email
}
[up.util.copy.key]() {
return new Account(this.email)
}
}
```
### Usage with up.util.copy()
```
original = new User('foo@foo.com')
copy = up.util.copy(original)
console.log(copy.email) // prints 'foo@foo.com'
original.email = 'bar@bar.com' // change the original
console.log(copy.email) // still prints 'foo@foo.com'
```
```
--------------------------------
### Eagerly preload links with up.compiler
Source: https://unpoly.com/changes/3.0.0
Example of using up.compiler to preload links with the rel=next attribute.
```javascript
up.compiler('a[rel=next]', up.link.preload)
```
--------------------------------
### Expire cache by URL pattern
Source: https://unpoly.com/X-Up-Clear-Cache
Example of using the header to expire all responses to URLs starting with /notes/.
```http
X-Up-Clear-Cache: /notes/*
```
--------------------------------
### Evict cache entries by URL pattern
Source: https://unpoly.com/X-Up-Evict-Cache
Example of using the header to expire all responses to URLs starting with /notes/.
```http
X-Up-Evict-Cache: /notes/*
```
--------------------------------
### up.Preview methods - Prefer additive changes
Source: https://unpoly.com/previews
Demonstrates recommended patterns for previews: avoid detaching fragments, use hiding instead, and leverage up.Preview methods for automatic undo.
```APIDOC
## up.Preview methods - Prefer additive changes
### Description
While previews can change the DOM arbitrarily, it is recommended to not remove the targeted fragment from the DOM because a detached fragment cannot be aborted. Instead, hide the fragment or use up.Preview methods that automatically undo changes.
### Example: Detaching (not recommended)
```js
up.preview('spinner', function(preview) {
let spinner = up.element.createFromHTML('')
// ❌ Detached fragments cannot be aborted
preview.fragment.replaceWith(spinner)
return () => spinner.replaceWith(preview.fragment)
})
```
### Example: Hiding (recommended)
```js
up.preview('spinner', function(preview) {
let spinner = up.element.createFromHTML('')
preview.fragment.insertAdjacentElement('beforebegin', spinner)
// ✅ Hidden fragments can still be aborted
up.element.hide(preview.fragment)
return () => {
spinner.remove()
up.element.show()
}
})
```
### Example: Using up.Preview methods (shortened)
```js
up.preview('spinner', function(preview) {
preview.insert(preview.fragment, 'beforebegin', '')
preview.hide(preview.fragment)
})
```
```
--------------------------------
### Request with X-Up-Target header
Source: https://unpoly.com/Vary
An example of a GET request to /sitemap that includes the X-Up-Target header to request a specific fragment.
```http
GET /sitemap HTTP/1.1
X-Up-Target: .menu
```
--------------------------------
### up:layer:opened event listener
Source: https://unpoly.com/up%3Alayer%3Aopened
Example of listening to the up:layer:opened event to customize overlay elements before the opening animation starts.
```APIDOC
## up:layer:opened
### Description
This event is emitted after a new overlay was placed into the DOM, right before the opening animation starts. It can be used to customize overlay elements.
### Event Properties
- **event.origin** (Element) - Required - The link element that is opening the overlay.
- **event.layer** (up.Layer) - Required - The layer object that is opening.
### Example
```javascript
up.on('up:layer:opened', function(event) {
if (isChristmas()) {
up.element.affix(event.layer.element, '.santa-hat', text: 'Merry Christmas!')
}
})
```
```
--------------------------------
### Ambiguous selectors example
Source: https://unpoly.com/targeting-fragments
An example of multiple elements sharing the same class selector.
```html
...
...
...
```
--------------------------------
### Queueing a request with up.request()
Source: https://unpoly.com/up.Request
Demonstrates how to initiate a request and handle the response using the promise interface.
```javascript
let request = up.request('/foo')
console.log(request.url)
// A request object is also a promise for its response
let response = await request
console.log(response.text)
```
--------------------------------
### Method wrapping request example
Source: https://unpoly.com/up.protocol.config
Example of a POST request used by Unpoly to wrap a non-GET/POST method.
```http
POST /test HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
_method=PUT
```
--------------------------------
### X-Up-Open-Layer: Basic Example
Source: https://unpoly.com/X-Up-Open-Layer
Forces the response to open a new overlay with default modal mode, selecting the main element from the HTML payload.
```APIDOC
## X-Up-Open-Layer: Basic Example
### Description
Forces the response to open a new overlay with default modal mode, selecting the main element from the HTML payload.
### Header
X-Up-Open-Layer
### Header Value
{}
### Example
Content-Type: text/html
X-Up-Open-Layer: {}
Overlay content
```
--------------------------------
### Script element fragment example
Source: https://unpoly.com/changes/3.14.0
An example of a script element contained within a fragment, which is subject to the new up.script.config.scriptElementPolicy.
```html
```
--------------------------------
### up.navigate({ preview: (preview) => preview.run(name, options) })
Source: https://unpoly.com/previews
As an alternative, you can pass a function that calls `preview.run()` with a preview name and options. This makes it easier to pass option values that already exist in your scope.
```APIDOC
## up.navigate({ preview: (preview) => preview.run(name, options) })
### Description
As an alternative, you can pass a function that calls `preview.run()` with a preview name and options. This makes it easier to pass option values that already exist in your scope.
### Method
up.navigate
### Parameters
- **url** (string) - Required - The URL to navigate to.
- **preview** (function) - Required - A function that receives a preview object and calls `preview.run(name, options)`.
- **preview** (object) - The preview object.
- **name** (string) - The name of the preview.
- **options** (object) - The options object.
### Request Example
```js
let size = 100
up.navigate({
url: '/edit',
preview: (preview) => preview.run('link-spinner', { size })
})
```
### Response
No return value.
```
--------------------------------
### up.Preview.prototype.run(nameOrFn, options)
Source: https://unpoly.com/up.Preview
Runs another preview function. This is experimental.
```APIDOC
## up.Preview.prototype.run(nameOrFn, options)
### Description
Runs another preview function. This is experimental.
### Method
prototype method
### Parameters
- **nameOrFn** (string or function) - Required - The name of a registered preview function or a function to run.
- **options** (object) - Optional - Options to pass to the preview function.
### Returns
- **up.Preview** - The preview instance for chaining.
### Example
```js
preview.run('myPreview', { foo: 'bar' })
```
```
--------------------------------
### up.Preview.prototype.openLayer()
Source: https://unpoly.com/up.Preview
Opens a temporary overlay. This is experimental.
```APIDOC
## up.Preview.prototype.openLayer()
### Description
Opens a temporary overlay. This is experimental.
### Method
prototype method
### Returns
- **up.Preview** - The preview instance for chaining.
### Example
```js
preview.openLayer()
```
```
--------------------------------
### Customizing X-Up-Open-Layer options
Source: https://unpoly.com/X-Up-Open-Layer
Configures the overlay target, mode, and animation by passing a JSON string in the header.
```http
Content-Type: text/html
X-Up-Open-Layer: { target: '#menu', mode: 'drawer', animation: 'move-to-right' }
Overlay content
```
--------------------------------
### up.compiler() error handling example
Source: https://unpoly.com/render-lifecycle
Example showing that errors thrown in user code, such as compilers, do not interrupt Unpoly operations and instead emit an error event on window.
```APIDOC
## up.compiler() error handling
### Description
Demonstrates that errors thrown in user code (e.g., compilers) do not interrupt Unpoly operations. Instead, an error event is emitted on window and the operation succeeds.
### Method
up.compiler()
### Parameters
- **selector** (string) - Required - The selector for the compiler.
- **callback** (function) - Required - The compiler function that may throw an error.
### Error Handling
- **error event** - Emitted on window when a user-provided function throws an exception.
### Example
```javascript
up.compiler('.element', () => { throw new Error('broken compiler') })
let element = up.element.affix(document.body, '.element')
up.hello(element) // no error is thrown
```
```
--------------------------------
### Example of HTML nodes updated during history changes
Source: https://unpoly.com/updating-history
This example highlights the elements in the document head that are updated when history changes, such as the title, canonical link, meta tags, and JSON-LD annotations.
```html
AcmeCorp
...
```
--------------------------------
### Create and append an element to a layer
Source: https://unpoly.com/up.Layer.prototype.affix
This example demonstrates opening a layer and using the affix method to add an element with a specific class to it.
```javascript
layer = up.layer.open()
element = layer.affix(.klass')
element.parentElement // returns 'main'
element.className // returns 'klass'
```
--------------------------------
### up.preview('my-preview', callback)
Source: https://unpoly.com/up.Preview.prototype.layer
Example usage of the up.preview function to demonstrate accessing the layer property of the preview object.
```APIDOC
## up.preview('my-preview', callback)
### Description
Creates a preview and provides a callback that receives a preview object. The example shows how to access the layer property of the preview object.
### Method
up.preview
### Parameters
- **selector** (string) - Required - The selector for the preview.
- **callback** (function) - Required - A function that receives the preview object.
### Example
```javascript
up.preview('my-preview', function(preview) {
if (preview.layer === 'new') {
console.log("Opening a layer with mode", preview.renderOptions.mode)
} else {
console.log("Updating layer", preview.layer)
}
})
```
### Return Value
- **preview.layer** (up.Layer | string) - The layer that the previewed render pass is going to update. When opening a new overlay, this property has the value 'new'.
```
--------------------------------
### Hide element during preview with up.preview
Source: https://unpoly.com/up.Preview.prototype.hide
Use this example to hide an element with the selector '#nav' while a request is loading. The element will be shown again when the preview ends. The example uses the up.preview() function with the name 'hide-nav' and calls preview.hide('#nav') inside the callback.
```javascript
up.preview('hide-nav', function(preview) {
preview.hide('#nav')
})
```
--------------------------------
### up.link.followOptions(link)
Source: https://unpoly.com/up.link.followOptions
Parses the render options that would be used to follow the given link, but does not render. Returns an object of render options.
```APIDOC
## up.link.followOptions(link)
### Description
Parses the render options that would be used to follow the given link, but does not render. Returns an object of render options.
### Parameters
- **link** (Element | jQuery | string) - Required - The link from which to parse options.
### Return Value
- **Object** - An object of render options.
### Example
Given a link with some `[up-...]` attributes:
```html
...
```
We can parse the link's render options like this:
```javascript
let link = document.querySelector('a[href="/foo"]')
let options = up.link.followOptions(link)
// { url: '/foo', method: 'GET', target: '.content', layer: 'new', ... }
```
```
--------------------------------
### Matomo trackPageView implementation
Source: https://unpoly.com/analytics
Example implementation of the trackPageView function for Matomo.
```javascript
function trackPageView(url) {
_paq.push(['setCustomUrl', url])
_paq.push(['trackPageView'])
}
```
--------------------------------
### JavaScript: up.navigate() with multiple previews
Source: https://unpoly.com/previews
Shows how to pass multiple previews to the up.navigate() method using a comma-separated string, an array of names, or an array of anonymous functions.
```APIDOC
## [JavaScript] up.navigate()
### Description
Use the up.navigate() method to trigger a navigation with multiple previews. Previews can be specified as a comma-separated string, an array of preview names, or an array of anonymous preview functions.
### Method
up.navigate()
### Parameters
#### Options Object
- **url** (string) - Required - The URL to navigate to.
- **preview** (string | array) - Optional - Comma-separated string of preview names, an array of preview names, or an array of functions.
### Examples
up.navigate({ url: '/edit', preview: 'spinner form-placeholder' })
up.navigate({ url: '/edit', preview: ['spinner', 'form-placeholder'] })
let fn1 = (preview) => { ... }
let fn2 = (preview) => { ... }
up.navigate({ url: '/edit', preview: [fn1, fn2] })
```
--------------------------------
### Match URL with wildcard suffix
Source: https://unpoly.com/url-patterns
Matches any path starting with /users/.
```text
/users/*
```
--------------------------------
### Empty div elements
Source: https://unpoly.com/up.element.isEmpty
Examples of div elements that are considered empty by up.element.isEmpty.
```html
```
--------------------------------
### up.on('up:request:load', ...)
Source: https://unpoly.com/up%3Arequest%3Aload
Example of listening to the up:request:load event to modify request options before the request is sent.
```APIDOC
## up.on('up:request:load', ...)
### Description
Listens to the `up:request:load` event to inspect or mutate request options before the request is sent.
### Event
`up:request:load`
### Usage
```
up.on('up:request:load', (event) => {
if (event.request.url === '/stocks') {
event.request.headers['X-Client-Time'] = Date.now().toString()
event.request.timeout = 10_000
}
})
```
### Event Properties
- **event.request** (up.Request) - Required - The request that will be sent. Listeners can inspect or mutate request options before the request is sent.
- **event.layer** (up.Layer) - Optional - The layer this request is associated with. If this request is intended to update an existing fragment, this is that fragment's layer. If this request is intended to open an overlay, the associated layer is the future overlay's parent layer.
- **event.origin** (Element) - Optional - The link or form element that caused the request.
- **event.preventDefault()** - Required - Aborts the request before it is sent.
```
--------------------------------
### Simplified target selection with :origin
Source: https://unpoly.com/origin
Example demonstrating how to simplify target selectors by using the :origin placeholder to reference the clicked link.
```html
Show task 1
```
--------------------------------
### Search form HTML structure
Source: https://unpoly.com/up.autosubmit
An example of a search form that can be configured for automatic submission.
```html
```
--------------------------------
### Using up.layer.ask() for acceptance
Source: https://unpoly.com/closing-overlays
Demonstrates using up.layer.ask() to open an overlay and await the acceptance value returned by the promise.
```javascript
let user = await up.layer.ask({ url: '/users/new' })
console.log('Got user:', user)
```
--------------------------------
### HTML form structure
Source: https://unpoly.com/up.Params.fromForm
An example HTML form containing text and password inputs.
```html
```
--------------------------------
### Minimustache template definition
Source: https://unpoly.com/placeholders
Example of a template using the text/minimustache type for variable interpolation.
```html
```
--------------------------------
### Use render hooks in up.render
Source: https://unpoly.com/changes/3.0.0
Demonstrates the various callback functions available in up.render to intervene at different stages of the rendering lifecycle.
```javascript
up.render({
url: '/path',
onLoaded(event) { /* Content was loaded from cache or server */ },
focus(fragment, opts) { /* Set focus */ },
scroll(fragment, opts) { /* Set scroll positions */ },
onRendered(result) { /* Fragment was updated */ },
onFailRendered(result) { /* Fragment was updated from failed response */ },
onRevalidated(result) { /* Stale content was re-rendered */ },
onFinished(result) { /* All finished, including animation and revalidation */ }
onOffline(event) { /* Disconnection or timeout */ },
onError(error) { /* Any error */ }
})
```
--------------------------------
### Create and attach an element with up.element.affix
Source: https://unpoly.com/up.element.affix
Demonstrates creating a new element with a specific class and appending it to the document body.
```javascript
element = up.element.affix(document.body, '.klass')
element.parentElement // returns document.body
element.className // returns 'klass'
```
--------------------------------
### Original callback in HTML attribute
Source: https://unpoly.com/csp
Example of a callback that we want to replace with an event listener.
```HTML
Click me
```
--------------------------------
### up.layer.open([options])
Source: https://unpoly.com/up.layer
Opens a new overlay. This method is the core function for creating overlays with various options.
```APIDOC
## up.layer.open([options])
### Description
Opens a new overlay.
### Method
JS
### Endpoint
up.layer.open([options])
### Parameters
- **options** (object) - Optional - Options for the overlay, such as url, mode, etc.
### Response
Returns a promise or the layer object.
```
--------------------------------
### Example document with assets highlighted
Source: https://unpoly.com/handling-asset-changes
Shows an HTML document where remote script and stylesheet elements are considered assets by Unpoly. Inline scripts are not tracked by default.
```HTML
AcmeCorp
...
```
--------------------------------
### Evict all cache entries
Source: https://unpoly.com/X-Up-Evict-Cache
Example of using the wildcard character to evict all cached responses.
```http
X-Up-Evict-Cache: *
```
--------------------------------
### Get the nth layer
Source: https://unpoly.com/up.layer.get
Pass a number to retrieve the up.Layer object at that specific index.
```javascript
up.layer.get(0) // returns the root layer
up.layer.get(1) // returns the first overlay
```
--------------------------------
### up.modal.visit(url, options)
Source: https://unpoly.com/up.layer
Opens a modal overlay for the given URL.
```APIDOC
## up.modal.visit(url, options)
### Description
Opens a modal overlay for the given URL.
### Method
POST
### Endpoint
up.modal.visit
### Parameters
#### Request Body
- **url** (string) - Required - The URL to open.
- **options** (object) - Optional - Options for the modal.
### Request Example
```json
{
"url": "https://example.com",
"options": {}
}
```
### Response
#### Success Response (200)
- **status** (string) - Success status.
#### Response Example
```json
{
"status": "success"
}
```
```
--------------------------------
### Initial GET request for fragment
Source: https://unpoly.com/conditional-requests
The browser requests a fragment from the server with a target header.
```http
GET /messages HTTP/1.1
X-Up-Target: .messages
```
--------------------------------
### up.navigate({ preview: 'name { options }' })
Source: https://unpoly.com/previews
From JavaScript, you can pass a string containing the preview name and options to the `preview` option of `up.navigate()`. This allows you to specify the preview and its options in a single string.
```APIDOC
## up.navigate({ preview: 'name { options }' })
### Description
From JavaScript, you can pass a string containing the preview name and options to the `preview` option of `up.navigate()`. This allows you to specify the preview and its options in a single string.
### Method
up.navigate
### Parameters
- **url** (string) - Required - The URL to navigate to.
- **preview** (string) - Required - A string containing the preview name and options, e.g. `'link-spinner { size: 100 }'`.
### Request Example
```js
up.navigate({
url: '/edit',
preview: 'link-spinner { size: 100 }'
})
```
### Response
No return value.
```
--------------------------------
### Define a cross-fade transition
Source: https://unpoly.com/up.transition
An example of defining a custom 'cross-fade' transition using up.transition and up.animate.
```javascript
up.transition('cross-fade', function(oldElement, newElement, options) {
return Promise.all([
up.animate(oldElement, 'fade-out', options),
up.animate(newElement, 'fade-in', options)
])
})
```
--------------------------------
### Form element definition
Source: https://unpoly.com/up.form.submitOptions
An example of a form element configured with an action, method, and up-target attribute.
```html
```
--------------------------------
### Example fragment with multiple elements
Source: https://unpoly.com/up.compiler
A fragment containing three .card elements that will be processed by a compiler.
```html
...
...
...
```
--------------------------------
### Basic X-Up-Open-Layer usage
Source: https://unpoly.com/X-Up-Open-Layer
Opens a modal overlay by selecting the main element from the HTML payload.
```http
Content-Type: text/html
X-Up-Open-Layer: {}
Overlay content
```
--------------------------------
### Define link with [require-session] attribute
Source: https://unpoly.com/render-lifecycle
An example of an HTML link element that requires a session to be accessed.
```html
My projects
```