### Install Swup Documentation Locally Source: https://github.com/swup/docs/blob/main/README.md Clone the repository, navigate to the directory, and install dependencies using npm. ```sh git clone git@github.com:swup/docs.git cd ./docs npm install ``` -------------------------------- ### Install Swup with npm Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/installation.md Use this command to install Swup via npm if you are using a bundler in your project. ```shell npm install swup ``` -------------------------------- ### Initialize Swup with a Bundler Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/installation.md After installing Swup with a bundler, import it and create a new instance in your application. ```javascript import Swup from 'swup'; const swup = new Swup(); ``` -------------------------------- ### Basic Swup Animation Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Demonstrates default swup installation with two containers and a fade animation between pages. ```html https://swup-demos.onrender.com/basic/ Swup Demo: Basic ``` -------------------------------- ### Complete Basic Swup Setup Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/example.md Combines HTML structure, CSS transitions, and swup initialization for a functional fade animation. ```html Swup Example

Welcome

Lorem ipsum dolor sit amet.

``` -------------------------------- ### Include Swup from CDN and Initialize Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/installation.md For quick setup without a bundler, include the minified production file from a CDN and initialize Swup in your main script. ```html ``` -------------------------------- ### Install Scroll Plugin via npm Source: https://github.com/swup/docs/blob/main/src/docs/plugins/plugins.md Install the scroll plugin using npm. This is the first step before importing and enabling it. ```shell npm install @swup/scroll-plugin ``` -------------------------------- ### Install Latest swup Version Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Install the latest version of swup using npm. This command updates swup to the most recent release. ```shell npm install swup@latest ``` -------------------------------- ### delegateEvent Source: https://github.com/swup/docs/blob/main/src/docs/api/helpers.md Install a delegated event listener on the document using [delegate-it](https://github.com/fregante/delegate-it). ```APIDOC ## delegateEvent ### Description Install a delegated event listener on the document using [delegate-it](https://github.com/fregante/delegate-it). ### Parameters - **selector** (string) - The selector for the elements to delegate events on. - **event** (string) - The event to listen for. - **handler** (function) - The event handler function. ### Returns An object with a `destroy` method to stop listening for events. ### Example ```javascript const delegation = delegateEvent('form', 'submit', (event) => { console.log('Form submitted'); }); // To stop listening for events: delegation.destroy(); ``` ``` -------------------------------- ### Visit object structure example Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md An example of the visit object's structure, detailing properties like `id`, `from`, `to`, `containers`, `animation`, `trigger`, `cache`, `history`, and `scroll`. This object is available in all hook handlers. ```javascript { id: 1042739, /* A unique ID to identify this visit */ from: { url: '/home', hash: '' }, to: { url: '/about', hash: '#anchor', html: undefined, /* The HTML string of /about, when it's loaded */, document: undefined /* The parsed document of /about, when it's loaded */, }, containers: [ '#swup' ], animation: { animate: true, name: 'fade' }, trigger: { el: /* element */, event: /* MouseEvent */ }, cache: { read: true, write: true }, history: { action: 'push', popstate: false, direction: undefined }, scroll: { reset: true, target: '#anchor' }, meta: {} } ``` -------------------------------- ### Initialize Swup and Alpine.js Source: https://github.com/swup/docs/blob/main/src/docs/integrations/alpine.md Import and initialize both Swup for page transitions and Alpine.js for component management. This is the basic setup for using them together. ```javascript import Swup from 'swup'; import Alpine from 'alpinejs'; const swup = new Swup(); Alpine.start(); ``` -------------------------------- ### Registering Hook Handlers Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md An object containing hook handlers to register with Swup. This example shows how to log messages at the start and end of a visit. ```javascript { hooks: { 'visit:start': () => console.log('start'), 'visit:end': () => console.log('end') } } ``` -------------------------------- ### Run swup tests locally Source: https://github.com/swup/docs/blob/main/src/docs/other/contributions.md Execute this command to install dependencies and run the test suite locally before submitting a pull request. ```shell npm install && npm run test ``` -------------------------------- ### Develop and Preview Swup Documentation Source: https://github.com/swup/docs/blob/main/README.md Start watch modes for Eleventy and WebPack to develop and preview the documentation site locally. The localhost URL will be printed in the terminal. ```sh npm run watch ``` -------------------------------- ### CSS for custom slide transition Source: https://github.com/swup/docs/blob/main/src/docs/api/markup.md Example CSS demonstrating how to style a custom slide transition using the classes added by swup during page changes. ```css html.is-changing .transition-page { /* normal transition styles */ } html.is-changing.to-slide .transition-page { /* slide transition styles */ } ``` -------------------------------- ### HTML with Route Name Plugin Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Example of the `` tag with `from-*` and `to-*` classes when the Route Name Plugin is enabled. ```html ``` -------------------------------- ### Swup Transition Fade Animation Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/common-issues.md Example HTML structure and CSS for a fade transition animation used with Swup. ```html
``` ```css html.is-changing .swup-transition-fade { transition: 0.4s; opacity: 1; } html.is-animating .swup-transition-fade { opacity: 0; } ``` -------------------------------- ### HTML with Local Animation Scope Source: https://github.com/swup/docs/blob/main/src/docs/announcements/swup-4.md Example of a content container with animation classes when `animationScope` is set to 'containers'. ```html
Content
``` -------------------------------- ### Slideshow Animation Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md An example of animating between pages as a horizontal slideshow, utilizing the Parallel and Preload Plugins. ```html https://swup-demos.onrender.com/slideshow/ Swup Demo: Slideshow ``` -------------------------------- ### Import Swup as ESM Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/installation.md Import Swup as a native ES module for modern browsers. This example shows how to include the ES module with a fallback to UMD for older browsers. ```html ``` -------------------------------- ### HTML with Animation Classes (HTML Scope) Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Example of HTML structure when animationScope is set to 'html', showing animation classes applied to the html tag. ```html ``` -------------------------------- ### Display Loading Indicator During Transitions Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Show a loading indicator when the outgoing animation starts and hide it when the incoming animation ends using 'animation:out:start' and 'animation:in:end' hooks. ```javascript swup.hooks.on('animation:out:start', () => { document.querySelector('#loader').hidden = false; }); swup.hooks.on('animation:in:end', () => { document.querySelector('#loader').hidden = true; }); ``` -------------------------------- ### Limit Cache Entries Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Implement a page limit for the cache by hooking into the `cache:set` event. This example prunes entries exceeding a defined maximum, keeping the most recent ones. ```javascript const maxCacheEntries = 20; swup.hooks.on('cache:set', () => { const prune = [...swup.cache.all.keys()].reverse().slice(maxCacheEntries); swup.cache.prune((url) => prune.includes(url)); }); ``` -------------------------------- ### Enable Scroll Plugin during Swup Initialization Source: https://github.com/swup/docs/blob/main/src/docs/plugins/plugins.md Enable the scroll plugin by including it in the plugins array when initializing Swup. This ensures the plugin is active from the start. ```javascript const swup = new Swup({ plugins: [new SwupScrollPlugin()] }); ``` -------------------------------- ### Basic Alpine.js Component within Swup Container Source: https://github.com/swup/docs/blob/main/src/docs/integrations/alpine.md An example of an Alpine.js component initialized within the main swup container. The component's data and initialization logic are defined using Alpine's directives. ```html
My Component
``` -------------------------------- ### Independent Animation Styling Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/common-issues.md Example CSS for styling independent animations like a logo, without relying on Swup's default transition classes for timing. ```css /* Note: no transition-* prefix */ html.is-changing .logo { transition: 0.4s; opacity: 1; } html.is-animating .logo { opacity: 0; } ``` -------------------------------- ### Accessing Custom Metadata in Hooks Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Store custom data in the `visit.meta` object during 'visit:start' and access it in subsequent hooks like 'page:view'. ```javascript swup.hooks.on('visit:start', (visit) => { visit.meta.lorem = 'ipsum'; }); swup.hooks.on('page:view', (visit) => { console.log(visit.meta.lorem); // 'ipsum' }); ``` -------------------------------- ### CSS Custom Properties for Theme Configuration Source: https://github.com/swup/docs/blob/main/src/docs/themes/create-theme.md Use CSS custom properties, namespaced with the theme name, to allow users to configure theme behavior and appearance. This example shows how to set duration and color properties. ```css html { --swup-custom-theme-duration: .6s; --swup-custom-theme-color: red; } ``` -------------------------------- ### Replacing the current history entry Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Modify the `visit.history.action` to 'replace' within the `visit:start` hook to instruct swup to replace the current history entry instead of creating a new one. ```javascript swup.hooks.on('visit:start', (visit) => { visit.history.action = 'replace'; }); ``` -------------------------------- ### Disabling cache read or write Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Control swup's caching behavior by setting `visit.cache.read` or `visit.cache.write` to `false` in the `visit:start` hook. This overrides the global cache option settings. ```javascript swup.hooks.on('visit:start', (visit) => { visit.cache.read = false; }); ``` -------------------------------- ### Build Swup Documentation Source: https://github.com/swup/docs/blob/main/README.md Build the documentation site for deployment. ```sh npm run build ``` -------------------------------- ### Get Cache Record Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Retrieve a cached page object using its URL with the `get` method. Returns `undefined` if the URL is not found in the cache. ```javascript const page = swup.cache.get('/about'); ``` -------------------------------- ### Disable scroll reset on visit start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Maintain the current scroll position after a page load by setting `visit.scroll.reset` to `false` in the `visit:start` hook. This overrides the default behavior of resetting scroll to the top. ```javascript swup.hooks.on('visit:start', (visit) => { visit.scroll.reset = false; }); ``` -------------------------------- ### Initialize Swup Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/example.md Loads and initializes the swup library with default options. ```javascript import Swup from 'https://unpkg.com/swup@4?module'; const swup = new Swup(); ``` -------------------------------- ### Swup Initialization with Default Options Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Initializes Swup with all default options. This provides a baseline configuration for most projects. ```javascript const swup = new Swup({ animateHistoryBrowsing: false, animationSelector: '[class*="transition-"]', animationScope: 'html', cache: true, containers: ['#swup'], hooks: {}, ignoreVisit: (url, { el } = {}) => el?.closest('[data-no-swup]'), linkSelector: 'a[href]', linkToSelf: 'scroll', native: false, plugins: [], resolveUrl: (url) => url, requestHeaders: { 'X-Requested-With': 'swup', 'Accept': 'text/html, application/xhtml+xml' }, skipPopStateHandling: (event) => event.state?.source !== 'swup', timeout: 0 }); ``` -------------------------------- ### Overlay Animation Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Demonstrates covering content while loading the new page with swup. ```html https://swup-demos.onrender.com/overlay/ Swup Demo: Overlay ``` -------------------------------- ### Use Delegate Event Helper Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Utilize the bundled `delegateEvent` helper on the swup instance instead of external libraries like `delegate-it`. ```diff - import delegate from 'delegate-it'; - this.swup.delegatedListeners.formSubmit = delegate( - document, - this.options.formSelector, - 'submit', - this.onFormSubmit.bind(this) - ); + this.swup.delegatedListeners.formSubmit = this.swup.delegateEvent( + this.options.formSelector, + 'submit', + this.onFormSubmit.bind(this) + ); ``` -------------------------------- ### Get Cache Size Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Access the `size` property of the `swup.cache` object to retrieve the current number of entries stored in the cache. ```javascript swup.cache.size; // 13 ``` -------------------------------- ### Fragment Support: Modal Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Shows how to load sub-pages as modals using the Fragment Plugin to select containers based on route. ```html https://swup-demos.onrender.com/fragment-modal/ Swup Fragment Demo: Modal ``` -------------------------------- ### Swup Initialization with Event Handlers Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/reloading-javascript.md Sets up Swup and registers event handlers to run the 'init' function on initial page load (using DOMContentLoaded) and after every subsequent page view via Swup's hooks. ```javascript const swup = new Swup(); // Run once when page loads if (document.readyState === 'complete') { init(); } else { document.addEventListener('DOMContentLoaded', () => init()); } // Run after every additional navigation by swup swup.hooks.on('page:view', () => init()); ``` -------------------------------- ### Execute Hook Once Source: https://github.com/swup/docs/blob/main/src/docs/announcements/swup-4.md Register a hook handler that executes only on the next specified event and then automatically removes itself. Ideal for one-time setup or logging. ```javascript swup.hooks.once('page:view', () => { // Execute on next page view, then remove the handler }); ``` -------------------------------- ### Shortcut for 'before' option Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Use the 'swup.hooks.before()' shortcut for registering a handler that should execute before the default handler. ```javascript swup.hooks.before('content:replace', () => {}); // before: true ``` -------------------------------- ### Fragment Support: List Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Illustrates using the Fragment Plugin to replace only list items when applying filters. ```html https://swup-demos.onrender.com/fragment-list/ Swup Fragment Demo: List ``` -------------------------------- ### Import Swup and Scroll Plugin Source: https://github.com/swup/docs/blob/main/src/docs/plugins/plugins.md Import the Swup library and the Scroll Plugin. These are necessary to use the plugin's functionality. ```javascript import Swup from 'swup'; import SwupScrollPlugin from '@swup/scroll-plugin'; ``` -------------------------------- ### Accessing the trigger event Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Inspect the DOM event that triggered the visit using `visit.trigger.event` in the `visit:start` hook. This is commonly a `MouseEvent` for link clicks. ```javascript swup.hooks.on('visit:start', (visit) => { console.log('Click event', visit.trigger.event); // MouseEvent }); ``` -------------------------------- ### Import Core Helpers Source: https://github.com/swup/docs/blob/main/src/docs/api/helpers.md Import essential helper functions from the swup library. ```javascript import { getCurrentUrl, updateHistoryRecord } from 'swup'; ``` -------------------------------- ### Delay Page Transition with Promise Source: https://github.com/swup/docs/blob/main/src/docs/announcements/swup-4.md Pause the start of a page transition until a custom asynchronous function resolves. Useful for custom loading states or animations. ```javascript swup.hooks.on('visit:start', async () => { // Delay the start of the page transition until a Promise resolves await myCustomFunction(); }); ``` -------------------------------- ### Create Custom Hooks Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Custom hooks are now created using `this.swup.hooks.create()` instead of initializing an empty array. ```javascript this.swup._handlers.formSubmit = []; ``` ```javascript this.swup.hooks.create('form:submit'); ``` -------------------------------- ### Switch from Events to Hooks Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Plugin authors should switch from using Swup events to the new hook system. Use `this.swup.hooks.on()` instead of `this.swup.on()`. ```javascript this.swup.on('contentReplaced', () => {}); ``` ```javascript this.swup.hooks.on('content:replace', () => {}); ``` -------------------------------- ### Reveal Animation Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Demonstrates revealing the next page using masks and gradients, employing the Parallel Plugin. ```html https://swup-demos.onrender.com/reveal/ Swup Demo: Reveal ``` -------------------------------- ### CSS for Native Crossfade Animation Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/animations.md Define CSS rules for a crossfade animation using the View Transitions API. This example uses `view-transition-name` and keyframe animations. ```css html.is-changing .transition-fade { view-transition-name: main; } ::view-transition-old(main) { animation: fade 0.5s ease-in-out both; } ::view-transition-new(main) { animation: fade 0.5s ease-in-out both reverse; } @keyframes fade { from { opacity: 1; } to { opacity: 0; } } ``` -------------------------------- ### Multiple Animations Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Illustrates using swup's animation classes for elements other than the main content containers. ```html https://swup-demos.onrender.com/multiple/ Swup Demo: Multiple animations ``` -------------------------------- ### createHistoryRecord Source: https://github.com/swup/docs/blob/main/src/docs/api/helpers.md Create a new history record via `history.pushState`, appending custom data as well as internal metadata that swup will recognize as its own. ```APIDOC ## createHistoryRecord ### Description Create a new history record via `history.pushState`, appending custom data as well as internal metadata that swup will recognize as its own. ### Parameters - **url** (string) - The URL to push. - **data** (object) - Custom data to append to the history record. ### Example ```javascript createHistoryRecord('/new-page', { custom: 'data' }); ``` ``` -------------------------------- ### Update Helper Import Path Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Change import paths for swup helpers and utils from `swup/lib/helpers` to `swup`. ```diff - import { getPageData } from 'swup/lib/helpers'; + import { getPageData } from 'swup'; ``` -------------------------------- ### Accessing the trigger element Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Retrieve the DOM element that initiated the current visit using `visit.trigger.el` within the `visit:start` hook. This is typically an anchor element for link clicks. ```javascript swup.hooks.on('visit:start', (visit) => { console.log('Clicked link', visit.trigger.el); // HTMLAnchorElement }); ``` -------------------------------- ### Replace Custom Hook with Custom Handler Source: https://github.com/swup/docs/blob/main/src/docs/plugins/create-plugin.md Consumers can replace a custom hook's default handler with their own implementation, for example, using a different HTTP client like axios. ```javascript swup.hooks.replace('form:submit', (visit, { action, data }) => { return axios.get(action, { params: data }).then(/* */); }); ``` -------------------------------- ### Configure Astro Integration Source: https://github.com/swup/docs/blob/main/src/docs/integrations/astro.md Add the swup integration to your Astro configuration file. ```javascript // astro.config.mjs import { defineConfig } from 'astro/config'; import swup from '@swup/astro'; export default defineConfig({ integrations: [swup()] }); ``` -------------------------------- ### Swup Hooks for Page View and Initialization Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/reloading-javascript.md Combines the initial DOMContentLoaded event with Swup's 'page:view' hook to reliably run initialization code on both initial load and after every page change. ```javascript document.addEventListener('DOMContentLoaded', () => { // This runs on initial load }); swup.hooks.on('page:view', () => { // This runs after every page change by swup }); ``` -------------------------------- ### Execute handler before default Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Use the 'before: true' option to run a handler before swup's internal default handler for a specific hook. ```javascript swup.hooks.on('content:replace', () => {}, { before: true }); ``` -------------------------------- ### Set custom animation name Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Apply a custom animation to the page transition by setting the `visit.animation.name` property in the `visit:start` hook. This allows for CSS targeting via classes like `.to-{name}`. ```javascript swup.hooks.on('visit:start', (visit) => { visit.animation.name = 'slide'; }); ``` -------------------------------- ### Migrate `willReplaceContent` and `contentReplaced` Events Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Migrate from `willReplaceContent` and `contentReplaced` events to the `content:replace` hook. Use `swup.hooks.before()` for pre-replacement logic and `swup.hooks.on()` for post-replacement logic. ```javascript // Run right before the content is replaced swup.on('willReplaceContent', () => {}) // [!code --] swup.hooks.before('content:replace', () => {}) // [!code ++] ``` ```javascript // Run directly after the content was replaced swup.on('contentReplaced', () => {}) // [!code --] swup.hooks.on('content:replace', () => {}) // [!code ++] ``` -------------------------------- ### Add Scroll Plugin after Swup Initialization Source: https://github.com/swup/docs/blob/main/src/docs/plugins/plugins.md Add the scroll plugin to an existing Swup instance using the `use` method. This allows for dynamic plugin management. ```javascript const swup = new Swup(); swup.use(new SwupScrollPlugin()); ``` -------------------------------- ### Accessing the visit object in page:view hook Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Access the visit object within the `page:view` hook to get information about the new page URL. This hook is called after the new page has been loaded and the DOM updated. ```javascript swup.hooks.on('page:view', (visit) => { console.log('New page: ', visit.to.url); }); ``` -------------------------------- ### Migrate Event Listeners to Hooks Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Migrate from the old event system to the new hook system. Use `swup.hooks.on()` instead of `swup.on()` and update hook names. ```javascript swup.on('pageView', () => {}) // [!code --] swup.hooks.on('page:view', () => {}) // [!code ++] ``` ```javascript swup.off('pageView', handler) // [!code --] swup.hooks.off('page:view', handler) // [!code ++] ``` -------------------------------- ### Navigate to a URL Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Initiates navigation to a specified URL. This is the primary method for programmatic page transitions. ```javascript swup.navigate(url); ``` -------------------------------- ### Navigate with custom metadata Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Navigates to a URL and includes custom metadata, which can be accessed in swup hooks. Useful for passing contextual information. ```javascript swup.navigate(url, { meta: { lorem: 'ipsum' } }) ``` -------------------------------- ### Shortcut for 'once' option Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Use the 'swup.hooks.once()' shortcut for registering a handler that should only execute once. ```javascript swup.hooks.once('page:view', () => {}); // once: true ``` -------------------------------- ### Infinite Scroll Cache Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Demonstrates persisting items loaded with infinite scroll between page visits. ```html https://swup-demos.onrender.com/infinite-scroll-cache/ Swup Demo: Infinite Scroll Cache ``` -------------------------------- ### navigate Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Navigates to a new URL, triggering a page transition. Options can be provided to customize the navigation, such as disabling animations, setting custom animations, replacing history entries, specifying the HTTP method, disabling the cache, or passing custom metadata. ```APIDOC ## navigate ### Description Navigates to a new URL and triggers a page transition. This method allows for customization of the navigation process through an options object. ### Method `swup.navigate(url, options) ` ### Parameters - **url** (string) - Required - The URL to navigate to. - **options** (object) - Optional - An object to configure the navigation. Supported options include: - **animate** (boolean) - Disable animations for this visit. - **animation** (string) - Set a custom animation name. - **history** (string) - Replace the current history entry instead of creating a new one (`'replace'`). - **method** (string) - The HTTP method to use for the request (e.g., `'POST'`). - **data** (FormData|object) - Data to send with the request, especially when using `method: 'POST'`. - **cache** (object) - Configure cache behavior. `read` (boolean) to disable reading from cache, `write` (boolean) to disable writing to cache. - **meta** (object) - Custom metadata to pass along, available in hooks. ``` -------------------------------- ### Enable Route Name Plugin for Classnames Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Configure the Route Name Plugin to add `from-*` and `to-*` classes to the `` tag, restoring swup 2 behavior. ```javascript const swup = new Swup({ plugins: [new SwupRouteNamePlugin({ paths: true })] }); ``` -------------------------------- ### Reusable Initialization Function with Conditions Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/reloading-javascript.md A function to initialize components, checking for the presence of specific elements on the page before executing initialization logic. This prevents errors if an element doesn't exist. ```javascript function init() { if (document.querySelector('#carousel')) { // new Carousel('#carousel') } if (document.querySelector('#lightbox')) { // $('#lightbox').lightbox() } if (document.querySelector('#something-else')) { // and so on } } ``` -------------------------------- ### Customize Containers for Replacement Source: https://github.com/swup/docs/blob/main/src/docs/announcements/swup-4.md Update the visit object's containers property to specify which page elements Swup should replace during the transition. Allows for targeted updates. ```javascript swup.hooks.on('visit:start', (visit) => { visit.containers = ['#sidebar']; }); ``` -------------------------------- ### Animated Forms Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Demonstrates animating form submissions using the Forms Plugin. ```html https://swup-demos.onrender.com/forms/ Swup Demo: Animated forms ``` -------------------------------- ### Migrate `transition` Object to `visit` Object Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Migrate from the swup 3 `transition` object to the swup 4 `visit` object. Access visit details like URL and animation name through the `visit` object in hook handlers. ```javascript swup.on('transitionStart', () => { // [!code --] console.log('Visit to', swup.transition.to); // [!code --] console.log('Animation name', swup.transition.custom); // [!code --] }); // [!code --] swup.hooks.on('visit:start', (visit) => { // [!code ++] console.log('Visit to', visit.to.url); // [!code ++] console.log('Animation name', visit.animation.name); // [!code ++] }); // [!code ++] ``` -------------------------------- ### Enable Native Animations in Swup Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/animations.md Initialize Swup with the `native` option set to true to enable the View Transitions API. ```js const swup = new Swup({ native: true }); ``` -------------------------------- ### Initialize New Components on Page Load with 'page:view' Hook Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md The 'page:view' hook can be used to initialize JavaScript components on the newly loaded page content. ```javascript swup.hooks.on('page:view', () => { if (document.querySelector('#carousel')) { const carousel = new Carousel('#carousel'); } }); ``` -------------------------------- ### Create and Call Custom Hook Source: https://github.com/swup/docs/blob/main/src/docs/plugins/create-plugin.md Create a new custom hook in the mount method and call it elsewhere in your plugin. Arguments can be passed to the hook. ```javascript this.swup.hooks.create('form:submit'); ``` ```javascript this.swup.hooks.call('form:submit'); ``` ```javascript this.swup.hooks.call('form:submit', { formData: 123 }); ``` -------------------------------- ### Slide Animation Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Showcases sliding pages into view horizontally using swup. ```html https://swup-demos.onrender.com/slide/ Swup Demo: Slide ``` -------------------------------- ### Update Swup Initialization with Container Selectors Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md When initializing Swup, container selectors should now use unique identifiers like IDs instead of class names. ```javascript const swup = new Swup({ containers: ['.section'] }) ``` ```javascript const swup = new Swup({ containers: ['#nav', '#content'] }) ``` -------------------------------- ### use/unuse Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Manages plugins by enabling or disabling them. Plugins can be added using `use` and removed using `unuse`. ```APIDOC ## use/unuse ### Description Enables or disables plugins for swup. ### Method `swup.use(plugin)` `swup.unuse(plugin)` ### Parameters - **plugin** (object|string) - For `use`, an instantiated plugin object. For `unuse`, either the plugin name (string) or an instantiated plugin object. ``` -------------------------------- ### Log Current and Next URL Source: https://github.com/swup/docs/blob/main/src/docs/announcements/swup-4.md Access the visit object within a hook to log the source and destination URLs of the current page transition. Useful for debugging or analytics. ```javascript swup.hooks.on('visit:start', (visit) => { console.log('Going from', visit.to.url, 'to', visit.from.url); }); ``` -------------------------------- ### CSS Transition Styles Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/example.md Defines CSS transitions for page loading and unloading animations using swup's classes. ```css /* Define a transition duration during page visits */ html.is-changing .transition-fade { transition: opacity 0.25s; opacity: 1; } /* Define the styles for the unloaded pages */ html.is-animating .transition-fade { opacity: 0; } ``` -------------------------------- ### Registering Multiple Hook Handlers at Once Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Register all hook handlers when creating a new Swup instance by passing a keyed object to the `hooks` option. ```javascript const swup = new Swup({ hooks: { 'visit:start': () => console.log('starting visit'), 'page:load': () => console.log('loaded page'), 'visit:end': () => console.log('finished visit') } }) ``` -------------------------------- ### swup.config.js Configuration for CI/CD Validation Source: https://github.com/swup/docs/blob/main/src/docs/other/ci-cd.md Configure swup and validation settings for CI/CD pipelines. This file defines swup options like animation selectors and containers, along with validation parameters such as expected style changes, sitemap location, and base URL. ```javascript export default { // just some info about your swup setup so pages can be properly validated swup: { animationSelector: '[class*="swup-transition-"]', // animationSelector options of swup used in your project containers: ['#swup'] // containers options of swup used in your project }, // setup of your validation validate: { stylesExpectedToChange: ['opacity', 'transform'], // styles which are animated on your animated elements (checks that at least one is changed during animation) sitemap: 'public/sitemap.xml', // path or link to your sitemap urls: [], // set of URL - if set, swup CLI will check these URLs only (alternative to sitemap) baseUrl: '', // baseUrl of your site - if set, swup CLI will crawl the site for you, so you don't need to define URL manually (not referenced pages like 404 won't be checked) asynchronous: false, // can run all tests at once asynchronously (way faster, but might cause problems) runTests: 'all' // can run only one check instead of all (containers, transition-duration, transition-styles) } }; ``` -------------------------------- ### Update CDN Script Path Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Update the CDN path for swup to version 3. ```diff - + ``` -------------------------------- ### Handle Swup Page View Hook in Alpine.js Source: https://github.com/swup/docs/blob/main/src/docs/integrations/alpine.md Demonstrates how to listen for the 'swup:page:view' hook within an Alpine.js component. This allows you to execute logic after a new page has been loaded and transitioned in. ```html
My Alpine Component
``` -------------------------------- ### Rename Navigation Method Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md The `swup.loadPage({ url })` method has been renamed to `swup.navigate(url)` for improved clarity. ```javascript swup.loadPage({ url: '/about' }); ``` ```javascript swup.navigate('/about'); ``` -------------------------------- ### Pause transition with Promise Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Return a Promise from a hook handler to pause the page transition. Swup will await the Promise before continuing. ```javascript // Delay the start of the page transition by 1 second swup.hooks.on('visit:start', () => { return new Promise((res) => setTimeout(res, 1000)); }); ``` -------------------------------- ### Delegate Event Listener Source: https://github.com/swup/docs/blob/main/src/docs/api/helpers.md Use delegateEvent to set up a delegated event listener on the document. This is efficient for handling events on dynamically added elements. The returned object can be used to destroy the listener. ```javascript const delegation = delegateEvent('form', 'submit', (event) => { console.log('Form submitted'); }); ``` ```javascript delegation.destroy(); ``` -------------------------------- ### JavaScript Animations with GSAP Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/animations.md Implements custom page out and in animations using GSAP, hooked into swup's animation lifecycle. ```js import gsap from 'gsap'; swup.hooks.replace('animation:out:await', async () => { await gsap.to('.transition-fade', { opacity: 0, duration: 0.25 }); }); swup.hooks.replace('animation:in:await', async () => { await gsap.fromTo('.transition-fade', { opacity: 0 }, { opacity: 1, duration: 0.25 }); }); ``` -------------------------------- ### Inline Forms Demo Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/demos.md Showcases submitting simple forms in place without full page loads using the Forms Plugin. ```html https://swup-demos.onrender.com/inline-forms/ Swup Demo: Inline forms ``` -------------------------------- ### Replace history entry for a link Source: https://github.com/swup/docs/blob/main/src/docs/api/markup.md Add `data-swup-history="replace"` to a link to make swup replace the current history entry instead of pushing a new one. ```html
``` -------------------------------- ### Handling Links to Current Page Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Configures Swup's behavior for links pointing to the active URL. Setting to 'navigate' performs a standard page refresh instead of just scrolling. ```javascript { linkToSelf: 'navigate' } ``` -------------------------------- ### findPlugin Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Retrieves an enabled plugin instance by its name. ```APIDOC ## findPlugin ### Description Returns the plugin instance by its name, if the plugin is currently enabled. ### Method `swup.findPlugin(pluginName)` ### Parameters - **pluginName** (string) - Required - The name of the plugin to find. ### Response - **pluginInstance** (object) - The plugin instance if found, otherwise `null` or `undefined`. ``` -------------------------------- ### Cache Properties and Methods Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Access and manage Swup's cache directly through the `swup.cache` object. This includes checking cache size, adding, retrieving, updating, deleting, clearing, and pruning cache entries. ```APIDOC ## Cache Properties and Methods ### Description Access and manage Swup's cache directly through the `swup.cache` object. This includes checking cache size, adding, retrieving, updating, deleting, clearing, and pruning cache entries. ### Properties #### size - **Type**: `number` - **Description**: The number of cache entries currently stored in memory. ```javascript swup.cache.size; ``` ### Methods #### set - **Description**: Creates or updates a cache record for a given URL. - **Parameters**: - `url` (string): The URL to cache. - `page` (object): An object containing at least `url` and `html` properties. - `url` (string): The URL of the page. - `html` (string): The HTML content of the page. ```javascript swup.cache.set('/about', { url: '/about', html: '...' }); ``` #### get - **Description**: Retrieves the page object for a given URL if it exists in the cache. - **Parameters**: - `url` (string): The URL to retrieve from the cache. - **Returns**: `object` | `undefined`: The cached page object or `undefined` if not found. ```javascript const page = swup.cache.get('/about'); ``` #### has - **Description**: Checks if a given URL is present in the cache. - **Parameters**: - `url` (string): The URL to check. - **Returns**: `boolean`: `true` if the URL is cached, `false` otherwise. ```javascript if (swup.cache.has('/about')) { // ... } ``` #### update - **Description**: Updates an existing cache record or adds custom data to it. Merges new data with existing record. - **Parameters**: - `url` (string): The URL of the cache record to update. - `data` (object): An object containing custom data to merge. ```javascript swup.cache.update('/about', { ttl: 1000, created: Date.now() }); ``` #### delete - **Description**: Removes a specific cache record by its URL. - **Parameters**: - `url` (string): The URL of the cache record to delete. ```javascript swup.cache.delete('/about'); ``` #### clear - **Description**: Empties the entire cache, removing all stored records. ```javascript swup.cache.clear(); ``` #### prune - **Description**: Removes cache entries that match a given condition. - **Parameters**: - `predicate` (function): A function that receives the URL and page object. Returns `true` to prune the entry, `false` to keep it. ```javascript swup.cache.prune((url, page) => { /* return true to prune, false to keep */ }); ``` ``` -------------------------------- ### Navigate with custom animation Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Navigates to a URL and applies a specific custom animation. Useful for unique transition effects. ```javascript swup.navigate(url, { animation: 'custom' }); ``` -------------------------------- ### Registering Hook Handlers with Options Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Set hook handler options like `once` or `before` by appending them to the hook name, separated by a dot. ```javascript const swup = new Swup({ hooks: { 'visit:start.once': () => console.log('triggers once'), 'content:replace.before': () => console.log('triggers before hook') } }) ``` -------------------------------- ### Create New History Record Source: https://github.com/swup/docs/blob/main/src/docs/api/helpers.md Use createHistoryRecord to push a new state to the browser's history, including custom data and swup-specific metadata. ```javascript createHistoryRecord('/new-page', { custom: 'data' }); ``` -------------------------------- ### Fetch Timeout Configuration Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Set a fetch timeout in milliseconds. If a page load exceeds this duration, swup triggers a timeout hook and falls back to a standard browser load. ```javascript { timeout: 10_000 } ``` -------------------------------- ### Implement Cache TTL Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Set a Time-To-Live (TTL) for cache entries by storing creation timestamp and TTL on cache set. Before each page load, prune entries that have expired. ```javascript const ttl = 5 * 60_000; // 5 minutes // When a page is cached, append the current timestamp and time-to-live swup.hooks.on('cache:set', (visit, { page }) => { swup.cache.update(page.url, { created: Date.now(), ttl }); }); // Before each request, remove all invalid entries by timestamp swup.hooks.before('page:load', () => { swup.cache.prune((url, { created, ttl }) => Date.now() > created + ttl); }); ``` -------------------------------- ### Navigate with POST request and data Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Performs navigation using a POST request, sending along form data. Suitable for form submissions that trigger page changes. ```javascript swup.navigate(url, { method: 'POST', data: new FormData() }); ``` -------------------------------- ### Use and unuse plugins Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Enables or disables plugins for swup. Plugins extend swup's functionality, such as scrolling or animations. ```javascript // Enable plugin: accepts an instantiated instance swup.use(new SwupScrollPlugin()); // Disable plugin: accepts either name or instance swup.unuse('SwupScrollPlugin'); ``` -------------------------------- ### Execute Hook Before Internal Handler Source: https://github.com/swup/docs/blob/main/src/docs/announcements/swup-4.md Run a custom function immediately before Swup's default content replacement logic. Useful for pre-processing or custom animations. ```javascript swup.hooks.before('content:replace', () => { // Execute before swup replaces the content }); ```