### Initialize Turbo Library
Source: https://context7.com/hotwired/turbo/llms.txt
Demonstrates how to install and initialize the Turbo library. While importing the library automatically starts Turbo, manual control is available via the start method and event listeners.
```javascript
import * as Turbo from "@hotwired/turbo";
// Turbo is started automatically, but you can restart if needed
Turbo.start();
// Check if a navigation would be handled by Turbo
document.addEventListener("turbo:click", (event) => {
console.log("Turbo will navigate to:", event.detail.url);
});
```
--------------------------------
### Turbo Rendering Examples
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/rendering.html
This section lists various examples of how Turbo handles rendering different types of links and assets. It includes examples for same-origin links, tracked asset changes, nonces, additional scripts and assets, body noscript tags, head scripts, and conditional script evaluation.
```html
[Same-origin link](/src/tests/fixtures/one.html)
[Tracked asset change](/src/tests/fixtures/tracked_asset_change.html)
Submit
[Tracked nonce tag](/src/tests/fixtures/tracked_nonce_tag.html)
[Additional assets](/src/tests/fixtures/additional_assets.html)
[Additional script](/src/tests/fixtures/additional_script.html)
[Body noscript](/src/tests/fixtures/body_noscript.html)
[Body noscript with content](/src/tests/fixtures/body_noscript_with_content.html)
[Head script](/src/tests/fixtures/head_script.html)
[Body script](/src/tests/fixtures/body_script.html)
[data-turbo-eval=false script](/src/tests/fixtures/eval_false_script.html)
[Nonexistent link](/nonexistent)
[Visit control: reload](/src/tests/fixtures/visit_control_reload.html)
[Permanent element](/src/tests/fixtures/permanent_element.html)
[Permanent element in frame](/src/tests/fixtures/permanent_element.html)
[Delayed link](/__turbo/delayed_response)
[Redirect link](/__turbo/redirect)
[Change html[lang]](/src/tests/fixtures/es_locale.html)
[Change html[dir]](/src/tests/fixtures/dir_rtl.html)
```
--------------------------------
### Perform HTTP Requests with FetchRequest
Source: https://context7.com/hotwired/turbo/llms.txt
Demonstrates how to use FetchRequest to execute GET and POST requests with custom delegates. It covers handling responses, managing FormData, and cancelling active requests.
```javascript
import { FetchRequest, FetchResponse, FetchMethod, FetchEnctype } from "@hotwired/turbo"
const delegate = {
prepareRequest(request) {
request.headers["X-Custom-Header"] = "value"
},
requestStarted(request) {
console.log("Request started:", request.url.href)
},
requestSucceededWithResponse(request, response) {
console.log("Success:", response.statusCode)
},
requestFailedWithResponse(request, response) {
console.error("Failed:", response.statusCode)
},
requestErrored(request, error) {
console.error("Network error:", error)
},
requestFinished(request) {
console.log("Request finished")
},
requestPreventedHandlingResponse(request, response) {
console.log("Response handling was prevented")
}
}
const getRequest = new FetchRequest(delegate, FetchMethod.get, "/api/users")
const response = await getRequest.perform()
const formData = new FormData()
formData.append("name", "John")
formData.append("email", "john@example.com")
const postRequest = new FetchRequest(
delegate,
FetchMethod.post,
"/api/users",
formData,
document.body,
FetchEnctype.multipart
)
await postRequest.perform()
if (response.succeeded) {
const html = await response.responseHTML
console.log("Response HTML:", html)
}
getRequest.cancel()
```
--------------------------------
### Listen to Turbo Lifecycle Events
Source: https://context7.com/hotwired/turbo/llms.txt
Provides examples of subscribing to various Turbo events to hook into navigation, rendering, and frame updates. These events allow for custom transitions, validation, and cleanup logic.
```javascript
document.addEventListener("turbo:click", (event) => {
console.log("Clicked:", event.detail.url)
})
document.addEventListener("turbo:before-visit", (event) => {
if (!confirm("Leave this page?")) {
event.preventDefault()
}
})
document.addEventListener("turbo:before-cache", () => {
document.querySelectorAll(".modal").forEach(m => m.remove())
})
document.addEventListener("turbo:before-render", (event) => {
event.detail.render = async (currentBody, newBody) => {
await customTransition(currentBody, newBody)
}
})
document.addEventListener("turbo:load", (event) => {
console.log("Page loaded:", event.detail.url)
})
document.addEventListener("turbo:before-fetch-request", (event) => {
event.detail.fetchOptions.headers["X-Custom"] = "value"
event.preventDefault()
setTimeout(() => event.detail.resume(), 1000)
})
```
--------------------------------
### Initialize Rails UJS
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/ujs.html
Imports and starts the Rails UJS library to handle unobtrusive JavaScript features in a Rails environment.
```javascript
import Rails from "https://ga.jspm.io/npm:@rails/ujs@7.0.1/lib/assets/compiled/rails-ujs.js";
Rails.start();
```
--------------------------------
### Implement Server-Side Turbo Stream Responses
Source: https://context7.com/hotwired/turbo/llms.txt
Handle Turbo Stream requests on the server to perform partial page updates. This example demonstrates how to check for the correct content type and return Turbo Stream XML fragments in an Express.js application.
```javascript
app.post("/messages", (req, res) => {
const message = createMessage(req.body)
if (req.accepts("text/vnd.turbo-stream.html")) {
res.type("text/vnd.turbo-stream.html")
res.send(`
${message.body}
${messageCount}
`)
} else {
res.redirect("/messages")
}
})
app.post("/users", (req, res) => {
const errors = validateUser(req.body)
if (errors.length > 0) {
res.status(422)
res.type("text/vnd.turbo-stream.html")
res.send(`
`)
}
})
```
--------------------------------
### Programmatic Navigation with Turbo.visit
Source: https://context7.com/hotwired/turbo/llms.txt
Explains how to perform programmatic navigation using Turbo Drive. This includes options for history management, frame targeting, and handling custom responses.
```javascript
import { visit } from "@hotwired/turbo";
// Basic navigation
visit("/dashboard");
// Replace current history entry
visit("/settings", { action: "replace" });
// Navigate within a specific turbo-frame
visit("/messages/1", { frame: "message-detail" });
// Visit with stream response support
visit("/notifications", { acceptsStreamResponse: true });
```
--------------------------------
### Turbo.visit(location, options)
Source: https://context7.com/hotwired/turbo/llms.txt
Programmatically navigates to a URL using Turbo Drive, supporting history actions, frames, and custom response handling.
```APIDOC
## POST Turbo.visit(location, options)
### Description
Navigates the application to a new location using Turbo Drive, enabling seamless transitions without full page reloads.
### Method
JavaScript Method Call
### Parameters
#### Path Parameters
- **location** (string) - Required - The URL path to navigate to.
#### Options
- **action** (string) - Optional - Navigation action: 'advance', 'replace', or 'restore'.
- **frame** (string) - Optional - The ID of the turbo-frame to target.
- **response** (Response) - Optional - A pre-fetched fetch response object.
- **acceptsStreamResponse** (boolean) - Optional - Whether to accept Turbo Stream responses.
### Request Example
visit("/dashboard", { action: "replace", frame: "main-content" })
### Response
#### Success Response
- **Navigation** (void) - Triggers a Turbo navigation event and updates the DOM.
```
--------------------------------
### Connect Real-time Stream Sources
Source: https://context7.com/hotwired/turbo/llms.txt
Shows how to use the turbo-stream-source element and the Turbo API to connect WebSockets or EventSources for receiving stream updates.
```html
```
```javascript
import { connectStreamSource, disconnectStreamSource } from "@hotwired/turbo"
const socket = new WebSocket("wss://example.com/cable")
connectStreamSource(socket)
const eventSource = new EventSource("/streams")
connectStreamSource(eventSource)
disconnectStreamSource(socket)
socket.close()
```
--------------------------------
### Initialize Stimulus Application and Event Listeners
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/page_refresh.html
Initializes the Stimulus application and sets up event listeners for Turbo's morphing process. It handles focus events to manage 'data-turbo-permanent' attributes and listens for 'turbo:morph-element' and 'turbo:before-morph-attribute' events to re-connect Stimulus controllers.
```javascript
import { Application, Controller } from "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js"
const application = Application.start()
addEventListener("focusin", ({ target }) => {
if (target instanceof HTMLInputElement && !target.hasAttribute("data-turbo-permanent")) {
target.toggleAttribute("data-turbo-permanent", true)
target.addEventListener("focusout", () => target.toggleAttribute("data-turbo-permanent", false), { once: true })
}
})
addEventListener("turbo:morph-element", ({ target }) => {
for (const { element, context } of application.controllers) {
if (element === target) {
context.disconnect()
context.connect()
}
}
})
addEventListener("turbo:before-morph-attribute", (event) => {
const { target, detail: { attributeName, mutationType } } = event
for (const { element, context } of application.controllers) {
const pattern = new RegExp(`data-${context.identifier}-\\w+-value`)
if (element === target) {
event.preventDefault()
}
}
})
```
--------------------------------
### Configure Turbo Settings
Source: https://context7.com/hotwired/turbo/llms.txt
Details the global configuration object for Turbo Drive and form behaviors, including progress bar delays and custom confirmation dialogs.
```javascript
import { config } from "@hotwired/turbo";
// Enable or disable Turbo Drive globally
config.drive.enabled = true;
// Set progress bar delay (default 500ms)
config.drive.progressBarDelay = 200;
// Custom confirmation method for data-turbo-confirm
config.forms.confirm = async (message, element) => {
const dialog = document.getElementById("confirm-dialog");
dialog.querySelector(".message").textContent = message;
dialog.showModal();
return new Promise((resolve) => {
dialog.querySelector(".confirm").onclick = () => resolve(true);
dialog.querySelector(".cancel").onclick = () => resolve(false);
});
};
```
--------------------------------
### Programmatically Control turbo-frame
Source: https://context7.com/hotwired/turbo/llms.txt
Demonstrates how to manipulate turbo-frame elements using JavaScript to update sources, reload content, and check loading status.
```javascript
const frame = document.getElementById("messages")
frame.src = "/messages?filter=unread"
await frame.reload()
if (frame.complete) {
console.log("Frame finished loading")
}
await frame.loaded
```
--------------------------------
### Turbo.config
Source: https://context7.com/hotwired/turbo/llms.txt
Global configuration object for customizing Turbo Drive behavior, progress bars, and form submission handling.
```APIDOC
## PUT Turbo.config
### Description
Configures global settings for Turbo Drive, including progress bar delays and custom confirmation dialogs.
### Configuration Fields
- **drive.enabled** (boolean) - Global toggle for Turbo Drive.
- **drive.progressBarDelay** (number) - Delay in ms before showing the progress bar.
- **forms.mode** (string) - Form handling mode: 'on', 'off', or 'optin'.
- **forms.confirm** (function) - Custom async function for handling data-turbo-confirm events.
### Request Example
config.drive.progressBarDelay = 200;
```
--------------------------------
### Turbo.registerAdapter()
Source: https://context7.com/hotwired/turbo/llms.txt
Register a custom adapter for Turbo Native integration or custom navigation handling.
```APIDOC
## Turbo.registerAdapter(adapter)
### Description
Registers an adapter object to hook into the Turbo lifecycle, such as visit proposals, request status, and rendering events. Essential for building native wrappers (iOS/Android).
### Parameters
- **adapter** (object) - Required - An object implementing lifecycle methods like `visitStarted`, `visitCompleted`, and `visitFailed`.
```
--------------------------------
### Turbo Declarative Configuration
Source: https://context7.com/hotwired/turbo/llms.txt
Configuring Turbo behavior using HTML data attributes to control navigation, frames, and form submission.
```APIDOC
## HTML Data Attributes
### Description
Turbo behavior can be controlled declaratively by adding specific data attributes to HTML elements.
### Parameters
- **data-turbo** (boolean) - Optional - Enable or disable Turbo navigation for links or forms.
- **data-turbo-action** (string) - Optional - Specify history action (e.g., 'replace', 'advance').
- **data-turbo-frame** (string) - Optional - Target a specific ID or '_top' to break out.
- **data-turbo-confirm** (string) - Optional - Display a browser confirmation dialog before submission.
- **data-turbo-method** (string) - Optional - Force a link to use a specific HTTP method (post, put, delete).
- **data-turbo-stream** (boolean) - Optional - Request a Turbo Stream response instead of a standard page load.
- **data-turbo-prefetch** (boolean) - Optional - Preload the link target on hover.
- **data-turbo-permanent** (boolean) - Optional - Preserve element state across page morphs.
```
--------------------------------
### Turbo.cache Management
Source: https://context7.com/hotwired/turbo/llms.txt
Methods to manage the page snapshot cache for instant back/forward navigation and preview rendering.
```APIDOC
## GET Turbo.cache
### Description
Provides control over the page snapshot cache, allowing developers to clear or exempt pages from caching behavior.
### Methods
- **cache.clear()**: Clears all cached snapshots.
- **cache.exemptPageFromCache()**: Prevents the current page from being cached.
- **cache.exemptPageFromPreview()**: Allows caching but prevents the page from being used as a preview.
### Response
#### Success Response
- **Status** (void) - Updates internal cache state.
```
--------------------------------
### Navigate Turbo Frame
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/ujs.html
Demonstrates the programmatic navigation of a Turbo Frame element to a specific URL source.
```javascript
const frame = document.querySelector("#frame");
frame.src = "/src/tests/fixtures/frames/frame.html";
```
--------------------------------
### Configure Smooth Scrolling and Layout Spacing
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/scroll/one.html
Sets the global scroll behavior to smooth and provides a utility class to push elements below the initial viewport height.
```css
html {
scroll-behavior: smooth;
}
.push-below-fold {
margin-top: 100vh;
}
```
--------------------------------
### Asynchronously Load Turbo Library
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/async_script.html
This snippet demonstrates how to inject the Turbo library script into the document head after the DOM content has fully loaded. It uses a small timeout to ensure non-blocking execution.
```javascript
addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
var script = document.createElement("script");
script.src = "/dist/turbo.es2017-umd.js";
script.setAttribute("async", "");
document.head.appendChild(script);
}, 1);
});
```
--------------------------------
### Dynamically Add a Stylesheet
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/page_refresh.html
Adds a new stylesheet to the document's head when a button with the ID 'add-new-assets' is clicked. This demonstrates dynamic asset loading and management using JavaScript.
```javascript
document.getElementById("add-new-assets").addEventListener("click", () => {
const stylesheet = document.createElement("link")
stylesheet.id = "new-stylesheet"
stylesheet.rel = "stylesheet"
stylesheet.href = "/src/tests/fixtures/stylesheets/common.css"
stylesheet.dataset.turboTrack = "reload"
document.head.appendChild(stylesheet)
})
```
--------------------------------
### Implement Turbo Frame Navigation with data-turbo-action
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/frame_navigation.html
This snippet demonstrates how to trigger a frame-specific navigation that updates the browser history using the data-turbo-action attribute. It ensures that only the target frame is replaced while maintaining the surrounding page structure.
```html
About
```
--------------------------------
### Define and Register a Stimulus Controller
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/page_refresh.html
Defines a Stimulus controller named 'test' with targets and values. It includes methods for capturing input values and handling target connections, demonstrating basic Stimulus controller functionality.
```javascript
application.register("test", class extends Controller {
static targets = ["output"]
static values = { state: String }
capture({ target }) {
this.stateValue = target.value
}
outputTargetConnected(target) {
target.textContent = "connected"
}
})
```
--------------------------------
### StreamActions
Source: https://context7.com/hotwired/turbo/llms.txt
Extend Turbo Streams with custom actions to handle unique UI behaviors.
```APIDOC
## StreamActions
### Description
An object used to register custom Turbo Stream actions. Adding a property to this object allows you to define custom behavior for `` elements.
### Usage
- Define a function on the `StreamActions` object.
- The function context (`this`) provides access to the element's template content and target elements.
### Example
```javascript
import { StreamActions } from "@hotwired/turbo"
StreamActions.log = function() {
console.log(this.templateContent.textContent)
}
```
```
--------------------------------
### Morphing APIs
Source: https://context7.com/hotwired/turbo/llms.txt
Smooth DOM updates that preserve element state using the Idiomorph library.
```APIDOC
## Morphing APIs
### Description
Provides methods to perform intelligent DOM updates that preserve existing element state (like focus or scroll position) instead of simple innerHTML replacement.
### Methods
- **morphElements(current, new)**: Morph one element into another.
- **morphChildren(container, newContent)**: Morph children of a container.
- **morphBodyElements(currentBody, newBody)**: Morph entire body content.
- **morphTurboFrameElements(current, new)**: Morph specific turbo-frame elements.
```
--------------------------------
### Manage Turbo Cache
Source: https://context7.com/hotwired/turbo/llms.txt
Covers the management of page snapshots for instant navigation. Developers can clear the cache or exempt specific pages from caching or preview rendering.
```javascript
import { cache } from "@hotwired/turbo";
// Clear all cached snapshots
cache.clear();
// Exempt current page from being cached
cache.exemptPageFromCache();
// Allow caching but prevent preview rendering
cache.exemptPageFromPreview();
```
--------------------------------
### Configure Turbo Form Mode via URL Parameters
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/form_mode.html
This JavaScript snippet reads the 'formMode' query parameter from the browser's URL and updates the Turbo configuration accordingly. It ensures that the application state matches the requested form behavior upon page load.
```javascript
const params = new URLSearchParams(window.location.search);
if (params.has("formMode")) {
window.Turbo.setFormMode(params.get("formMode"));
}
```
--------------------------------
### Implement turbo-stream Actions
Source: https://context7.com/hotwired/turbo/llms.txt
Defines various turbo-stream actions for DOM manipulation such as append, prepend, replace, update, and remove. These are used for real-time UI updates.
```html
New message content
Updated user card
5
```
--------------------------------
### Handle Permanent Video Element with Turbo.js
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/rendering.html
This JavaScript code snippet utilizes Turbo.js to manage a permanent video element. It listens for the DOMContentLoaded event to ensure the video element is available, then sets up an event listener for the 'canplaythrough' event to resolve a promise when the video is ready. It also handles a click event on a button to play the video and pause it after the first time update.
```javascript
const permanentVideoElementLoaded = new Promise(resolve => {
addEventListener("DOMContentLoaded", () => {
const element = document.getElementById("permanent-video")
element.addEventListener("canplaythrough", () => resolve(element), { once: true })
})
})
addEventListener("click", async event => {
if (event.target.id == "permanent-video-button") {
const element = await permanentVideoElementLoaded
element.addEventListener("timeupdate", () => element.pause(), { once: true })
element.play()
}
})
```
--------------------------------
### Intercepting Turbo Fetch Requests
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/pausable_requests.html
This snippet demonstrates how to listen for the turbo:before-fetch-request event. It prevents the default request behavior, prompts the user for confirmation, and resumes the request if confirmed.
```javascript
addEventListener('turbo:before-fetch-request', function(event) {
event.preventDefault();
if (confirm('Continue request?')) {
event.detail.resume();
} else {
alert('Request aborted');
}
});
```
--------------------------------
### Register Custom Turbo Adapters
Source: https://context7.com/hotwired/turbo/llms.txt
Registers a custom adapter to intercept and handle navigation events, useful for integrating Turbo with native mobile applications or custom navigation logic.
```javascript
import { registerAdapter } from "@hotwired/turbo"
const customAdapter = {
visitProposedToLocation(location, options) {
console.log("Proposing visit to:", location.href)
},
visitStarted(visit) {
console.log("Visit started:", visit.location.href)
},
visitCompleted(visit) {
console.log("Visit completed")
},
visitFailed(visit) {
console.error("Visit failed")
},
pageInvalidated(reason) {
window.location.reload()
}
}
registerAdapter(customAdapter)
```
--------------------------------
### FetchRequest API
Source: https://context7.com/hotwired/turbo/llms.txt
The FetchRequest class provides a way to perform Turbo-aware HTTP requests with customizable delegates for lifecycle hooks.
```APIDOC
## [POST/GET] /api/requests
### Description
Performs an HTTP request using Turbo's fetch infrastructure, allowing for custom headers and lifecycle callbacks via a delegate object.
### Method
GET or POST
### Endpoint
/api/users
### Parameters
#### Path Parameters
- **delegate** (Object) - Required - Object containing lifecycle methods like prepareRequest, requestStarted, and requestSucceededWithResponse.
#### Request Body
- **formData** (FormData) - Optional - Form data to be sent with POST requests.
- **enctype** (FetchEnctype) - Optional - Encoding type (e.g., multipart).
### Request Example
const request = new FetchRequest(delegate, FetchMethod.post, "/api/users", formData);
await request.perform();
### Response
#### Success Response (200)
- **response** (FetchResponse) - Object containing response status, headers, and HTML content.
#### Response Example
{
"status": 200,
"succeeded": true,
"responseHTML": "
...
"
}
```
--------------------------------
### Turbo.renderStreamMessage()
Source: https://context7.com/hotwired/turbo/llms.txt
Manually render a Turbo Stream message string to update the page dynamically.
```APIDOC
## Turbo.renderStreamMessage(message)
### Description
Manually render a Turbo Stream message string to update the page. This is useful for processing stream messages received outside of standard fetch requests.
### Parameters
- **message** (string) - Required - A string containing one or more `` elements.
### Request Example
```javascript
import { renderStreamMessage } from "@hotwired/turbo"
renderStreamMessage('
New!
')
```
```
--------------------------------
### Turbo.connectStreamSource() / disconnectStreamSource()
Source: https://context7.com/hotwired/turbo/llms.txt
Programmatically connect or disconnect WebSocket or EventSource instances to receive Turbo Stream messages.
```APIDOC
## Turbo.connectStreamSource() / disconnectStreamSource()
Manually connect WebSocket or EventSource instances to receive Turbo Stream messages.
### JavaScript API
```javascript
import { connectStreamSource, disconnectStreamSource } from "@hotwired/turbo"
// Connect a WebSocket
const socket = new WebSocket("wss://example.com/cable")
connectStreamSource(socket)
// Connect Server-Sent Events
const eventSource = new EventSource("/streams")
connectStreamSource(eventSource)
// Handle incoming streams
socket.onmessage = (event) => {
// Turbo automatically processes turbo-stream HTML
// No additional handling needed
}
// Disconnect when done
disconnectStreamSource(socket)
socket.close()
```
```
--------------------------------
### Disable Turbo Drive and Handle Manual Form Submission
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/drive_disabled.html
This snippet demonstrates how to disable Turbo Drive globally using the configuration object and how to intercept click events to trigger a form submission manually using the requestSubmit API.
```javascript
addEventListener("click", event => {
if (event.target.id == "requestSubmit") {
event.preventDefault()
const form = event.target.closest('form')
form.requestSubmit()
}
})
Turbo.config.drive.enabled = false
```
--------------------------------
### Configure Turbo Behavior with HTML Data Attributes
Source: https://context7.com/hotwired/turbo/llms.txt
Use data attributes to control Turbo's navigation, frame targeting, and element persistence. These attributes allow developers to declaratively define how links and forms interact with the Turbo engine.
```html
Regular navigationSettingsOpen ModalDashboardLogoutMark All ReadPreloaded on hover
```
--------------------------------
### Configure turbo-frame for Scoped Navigation
Source: https://context7.com/hotwired/turbo/llms.txt
Defines various turbo-frame implementations including lazy loading, morphing, and navigation targeting. These elements scope links and forms to specific page regions.
```html
Show all messages
Loading sidebar...
This link navigates normallyLoad ProfileGo to Dashboard
```
--------------------------------
### Turbo Lifecycle Events
Source: https://context7.com/hotwired/turbo/llms.txt
Turbo emits various events throughout the page navigation and rendering lifecycle, allowing developers to hook into and modify behavior.
```APIDOC
## [EVENT] Turbo Lifecycle Hooks
### Description
Listen to global document events to customize Turbo's behavior during navigation, rendering, and caching.
### Key Events
- **turbo:before-visit** - Triggered before a navigation visit starts. Use event.preventDefault() to cancel.
- **turbo:before-render** - Triggered before new content is injected into the DOM. Allows custom rendering logic via event.detail.render.
- **turbo:load** - Triggered after the page has fully loaded.
- **turbo:before-fetch-request** - Intercept outgoing fetch requests to modify headers or perform async tasks.
- **turbo:before-fetch-response** - Intercept incoming fetch responses to handle errors like 401 Unauthorized.
### Usage Example
document.addEventListener("turbo:before-visit", (event) => {
if (!confirm("Leave this page?")) {
event.preventDefault();
}
});
```
--------------------------------
### POST /turbo-stream
Source: https://context7.com/hotwired/turbo/llms.txt
Handling server-side responses using the text/vnd.turbo-stream.html content type to update the DOM dynamically.
```APIDOC
## POST /turbo-stream
### Description
Servers can respond to requests with Turbo Stream fragments to perform partial page updates, such as appending content or replacing forms after validation errors.
### Method
POST
### Request Body
- **Content-Type** (header) - Required - Must be 'text/vnd.turbo-stream.html' to trigger Turbo processing.
### Response
#### Success Response (200)
- **Body** (text/vnd.turbo-stream.html) - A series of elements defining actions (append, update, replace, remove).
### Response Example
New message content
```
--------------------------------
### CSS for Scrollable Page
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/page_refresh_replace.html
This CSS snippet ensures the page is large enough to enable scrolling, which is often necessary for observing Turbo's behavior on dynamic content updates. It sets a minimum width and height to the body element.
```css
body {
margin: 0;
padding: 0;
/* Ensure the page is large enough to scroll */
width: 150vw;
height: 150vh;
}
```
--------------------------------
### CSS Styling for Right Square Transition
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/transitions/right.html
Defines the visual appearance and layout for a square element intended for a 'right' transition. It sets dimensions, color, border-radius, and a view transition name. The '.right' class modifies its margin for positioning.
```CSS
.square {
display: block;
width: 100px;
height: 100px;
border-radius: 6px;
background-color: blue;
view-transition-name: square;
}
.square.right {
margin-left: auto;
}
```
--------------------------------
### Perform DOM Morphing with Turbo
Source: https://context7.com/hotwired/turbo/llms.txt
Utilizes morphing APIs to perform smooth DOM updates that preserve element state. This includes morphing individual elements, children, body content, or specific turbo-frames.
```javascript
import { morphElements, morphChildren, morphBodyElements, morphTurboFrameElements } from "@hotwired/turbo"
// Morph one element into another
const currentElement = document.getElementById("user-card")
const newElement = document.createElement("div")
newElement.innerHTML = `
New content
`
morphElements(currentElement, newElement.firstElementChild)
// Morph only children
const container = document.getElementById("list")
const newContent = document.createElement("div")
newContent.innerHTML = `
Item 1 (updated)
Item 2 (new)
`
morphChildren(container, newContent)
// Morph body elements
morphBodyElements(document.body, document.body)
// Morph turbo-frame elements
morphTurboFrameElements(document.getElementById("my-frame"), document.createElement("turbo-frame"))
```
--------------------------------
### Define Square Element Styles for View Transitions
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/transitions/right_legacy.html
This CSS snippet defines the visual properties of a square element and assigns a view-transition-name for use with the View Transitions API. It ensures the element has a fixed size, rounded corners, and a specific transition identifier.
```css
.square { display: block; width: 100px; height: 100px; border-radius: 6px; background-color: blue; view-transition-name: square; }
.square.right { margin-left: auto; }
```
--------------------------------
### HTML/CSS: Styling for Off-Screen Frames
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/frames.html
This CSS rule defines a style for elements with the class 'push-off-screen', setting a large margin-top to visually push the element off the top of the screen. This is often used for animations or transitions involving frames.
```css
.push-off-screen {
margin-top: 1000px;
}
```
--------------------------------
### Extend Turbo Streams with Custom Actions
Source: https://context7.com/hotwired/turbo/llms.txt
Extends the StreamActions object to define custom behaviors for Turbo Streams. These actions can be triggered via HTML tags in the DOM.
```javascript
import { StreamActions } from "@hotwired/turbo"
// Add custom "log" action
StreamActions.log = function() {
const message = this.templateContent.textContent
console.log(`[Turbo Stream] ${message}`)
}
// Add custom "redirect" action
StreamActions.redirect = function() {
const url = this.getAttribute("url")
Turbo.visit(url)
}
// Add custom "scroll-to" action
StreamActions["scroll-to"] = function() {
this.targetElements.forEach((element) => {
element.scrollIntoView({ behavior: "smooth" })
})
}
```
--------------------------------
### turbo-stream-source Custom Element
Source: https://context7.com/hotwired/turbo/llms.txt
The turbo-stream-source custom element connects to a WebSocket or EventSource to receive Turbo Streams for real-time updates.
```APIDOC
## turbo-stream-source Custom Element
Connects a WebSocket or EventSource to receive Turbo Streams for real-time updates.
### HTML Examples
```html
```
### Server Response Example
```javascript
// Server sends turbo-stream HTML over the connection:
//
//
New message!
//
```
```
--------------------------------
### Track Script Evaluation in Turbo Frames (JavaScript)
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/frames/body_script_2.html
This JavaScript code tracks the number of times scripts within Turbo Frames are evaluated. It increments a counter on the window object or initializes it if it doesn't exist. This is crucial for managing script execution during frame updates to prevent unintended side effects or duplicate processing.
```javascript
if ("frameScriptEvaluationCount" in window) { window.frameScriptEvaluationCount++ } else { window.frameScriptEvaluationCount = 1 }
```
--------------------------------
### Apply right margin CSS
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/stylesheets/right.html
Defines CSS rules to add a 20px margin to the right side of the document body and any element with the class 'right'. This is typically used in layout testing for Turbo.
```css
body { margin-right: 20px; }
.right { margin-right: 20px; }
```
--------------------------------
### Manually Render Turbo Stream Messages
Source: https://context7.com/hotwired/turbo/llms.txt
Uses the renderStreamMessage function to programmatically apply Turbo Stream updates to the DOM. It accepts a string containing one or more elements.
```javascript
import { renderStreamMessage } from "@hotwired/turbo"
// Render stream from string
const streamHTML = `
Hello from JavaScript!
`
renderStreamMessage(streamHTML)
// Multiple actions in one message
renderStreamMessage(`
0
`)
```
--------------------------------
### turbo-stream Custom Element
Source: https://context7.com/hotwired/turbo/llms.txt
The turbo-stream custom element delivers page changes using CRUD-like actions. Streams can be delivered via WebSocket, SSE, or as HTTP responses.
```APIDOC
## turbo-stream Custom Element
Delivers page changes using CRUD-like actions. Streams can be delivered via WebSocket, SSE, or as HTTP responses with `Content-Type: text/vnd.turbo-stream.html`.
### HTML Examples
```html
New message content
You have a new notification
Updated user card
42
Now I'm first
Now I'm last
5
```
```
--------------------------------
### Track Script Execution Count with JavaScript
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/eval_false_script.html
This JavaScript code increments a counter in the window object each time a script is evaluated. This can be useful for debugging or understanding script execution flow, especially when dealing with dynamic content loading.
```javascript
if ("bodyScriptEvaluationCount" in window) { window.bodyScriptEvaluationCount++ } else { window.bodyScriptEvaluationCount = 1 }
```
--------------------------------
### Add CSS Link to Head with JavaScript
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/stylesheets/left.html
This JavaScript code snippet adds a link element to the document's head to load an external CSS file. It utilizes insertAdjacentHTML for appending the link tag. The link is given an ID 'added-link' for potential future manipulation.
```javascript
document.head.insertAdjacentHTML("beforeend", ` `)
```
--------------------------------
### Prevent Turbo Render Confirmation with JavaScript
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/pausable_rendering.html
This JavaScript code intercepts Turbo's render events and prompts the user for confirmation before proceeding. It prevents default rendering and allows resuming if confirmed. This is useful for critical navigation or form submissions.
```javascript
for (const event of ["turbo:before-render", "turbo:before-frame-render"]) {
addEventListener(event, function(event) {
event.preventDefault()
if (confirm("Continue rendering?")) {
event.detail.resume()
}
})
}
```
--------------------------------
### JavaScript: Manipulating Turbo Frames with Event Listeners
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/frames.html
This JavaScript code snippet listens for click events on elements within a Turbo Frame. It dynamically modifies frame attributes like 'data-turbo-action', 'refresh', and 'src' based on the clicked element's ID. It also handles removing the 'target' attribute from an element.
```javascript
document.addEventListener("click", ({ target }) => {
if (target.id == "add-turbo-action-to-frame") {
target.closest("turbo-frame")?.setAttribute("data-turbo-action", "advance")
} else if (target.id == "remove-target-from-hello") {
document.getElementById("hello").removeAttribute("target")
} else if (target.id == "add-refresh-reload-to-frame") {
target.closest("turbo-frame")?.setAttribute("refresh", "reload")
} else if (target.id == "add-refresh-morph-to-frame") {
target.closest("turbo-frame")?.setAttribute("refresh", "morph")
} else if (target.id == "add-src-to-frame") {
target.closest("turbo-frame")?.setAttribute("src", "/src/tests/fixtures/frames.html")
} else if (target.id == "change-frame-id-to-different-nested-child") {
target.closest("turbo-frame")?.setAttribute("id", "different-nested-child")
}
})
```
--------------------------------
### Add CSS Style to Head with JavaScript
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/stylesheets/left.html
This JavaScript code snippet adds a style element with inline CSS to the document's head. It uses insertAdjacentHTML to append the new style tag. If the style tag with the ID 'added-style' already exists, it will be replaced.
```javascript
document.head.insertAdjacentHTML("beforeend", ` `)
```
--------------------------------
### turbo-frame Custom Element
Source: https://context7.com/hotwired/turbo/llms.txt
The turbo-frame custom element scopes navigation within a specific region of the page. Links and forms inside a frame update only that frame's content, enabling partial page updates.
```APIDOC
## turbo-frame Custom Element
A custom element that scopes navigation within a specific region of the page. Links and forms inside a frame update only that frame's content.
### HTML Examples
```html
Show all messages
Loading sidebar...
This link navigates normallyLoad ProfileGo to Dashboard
```
### JavaScript API
```javascript
const frame = document.getElementById("messages");
// Update frame source
frame.src = "/messages?filter=unread";
// Reload the frame
await frame.reload();
// Check loading state
if (frame.complete) {
console.log("Frame finished loading");
}
// Wait for frame to load
await frame.loaded;
```
```
--------------------------------
### Smooth Scroll CSS
Source: https://github.com/hotwired/turbo/blob/main/src/tests/fixtures/scroll/two.html
This CSS snippet enables smooth scrolling behavior for elements. It relies on the 'scroll-behavior: smooth;' property, which is widely supported by modern browsers. This can be applied globally or to specific elements to control scroll animation.
```css
.scroll-container {
scroll-behavior: smooth;
}
```
```css
.push-below-fold {
margin-top: 100vh;
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.