### Use async/await in visit:start handler Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Async/await handlers are supported. This example waits for a custom function before starting the transition. ```javascript // Wait for a custom function before starting the transition swup.hooks.on('visit:start', async () => { await myCustomFunction(); }); ``` -------------------------------- ### Complete example: full HTML setup Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/example.md The complete code required for a basic Swup setup, combining the content container, animation styles, and initialization in a single HTML file. ```html Swup Example

Welcome

Lorem ipsum dolor sit amet.

``` -------------------------------- ### Install locally: clone repository and install dependencies Source: https://github.com/swup/docs/blob/main/README.md Clones the swup/docs repository and installs npm dependencies. Run these commands in a terminal to set up the project locally. ```sh git clone git@github.com:swup/docs.git cd ./docs npm install ``` -------------------------------- ### Install a delegated event listener with 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. The example listens for submit events on form elements. ```javascript const delegation = delegateEvent('form', 'submit', (event) => { console.log('Form submitted'); }); ``` -------------------------------- ### HTML example with from-* and to-* classes Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Example HTML output when the Route Name Plugin is configured with `paths: true`, showing `from-homepage` and `to-about` classes. ```html ``` -------------------------------- ### Install @swup/scroll-plugin via npm Source: https://github.com/swup/docs/blob/main/src/docs/plugins/plugins.md Install the scroll plugin package using npm. ```shell npm install @swup/scroll-plugin ``` -------------------------------- ### Install Swup via npm Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/installation.md Use this command to install the Swup package in projects using a bundler. ```shell npm install swup ``` -------------------------------- ### Interactive demo link Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/example.md An interactive demo to try out the fade animation built in this guide. The demo is hosted at the provided URL. ```swupdemo https://swup-demos.onrender.com/basic/ Swup Demo: Basic ``` -------------------------------- ### Delay page transition with a promise in visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Return a promise from a hook handler to pause execution. This example delays the start of the page transition by 1 second. ```javascript // Delay the start of the page transition by 1 second swup.hooks.on('visit:start', () => { return new Promise((res) => setTimeout(res, 1000)); }); ``` -------------------------------- ### Set all hook handlers at once in Swup instance options Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md When creating a Swup instance, you can register multiple hook handlers by passing a keyed object to the 'hooks' option. This example registers handlers for 'visit:start', 'page:load', and 'visit:end'. ```javascript const swup = new Swup({ hooks: { 'visit:start': () => console.log('starting visit'), 'page:load': () => console.log('loaded page'), 'visit:end': () => console.log('finished visit') } }) ``` -------------------------------- ### Example visit object shape Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Example visit object for a navigation from /home to /about#anchor. Shows the shape and properties of the visit object, including from, to, containers, animation, trigger, cache, history, scroll, and meta. ```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: {} } ``` -------------------------------- ### Run swup tests locally Source: https://github.com/swup/docs/blob/main/src/docs/other/contributions.md Run this command in the swup repository to install dependencies and execute the test suite before creating a pull request. ```shell npm install && npm run test ``` -------------------------------- ### Initialize Swup with ES module import Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/example.md Load and initialize Swup by importing it from the CDN and creating a new instance. This is the final step to get Swup working. ```javascript import Swup from 'https://unpkg.com/swup@4?module'; const swup = new Swup(); ``` -------------------------------- ### 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. ```APIDOC ## delegateEvent ### Description Install a delegated event listener on the document using delegate-it. ### Parameters - **selector** (string) - Required - The CSS selector for the target elements. - **eventName** (string) - Required - The event type to listen for. - **handler** (function) - Required - The event handler function. ### Returns Returns a delegation object with a `destroy()` method to stop listening. ### Example ```javascript const delegation = delegateEvent('form', 'submit', (event) => { console.log('Form submitted'); }); ``` To stop listening: ```javascript delegation.destroy(); ``` ``` -------------------------------- ### hooks option registering visit:start and visit:end handlers Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Registers hook handlers in the options object. The example logs 'start' on visit:start and 'end' on visit:end. ```javascript { hooks: { 'visit:start': () => console.log('start'), 'visit:end': () => console.log('end') } } ``` -------------------------------- ### Location helper usage Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Example of using the new `Location` helper to parse URLs from link elements. ```javascript import { Location } from 'swup'; const { url, hash } = Location.fromElement(linkEl); ``` -------------------------------- ### Install latest swup via npm Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Use this command to update the swup package to the latest version in your project. ```shell npm install swup@latest ``` -------------------------------- ### Change content containers on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Sets visit.containers to ['#sidebar'] to replace only the sidebar on the current visit. ```javascript swup.hooks.on('visit:start', (visit) => { visit.containers = ['#sidebar']; }); ``` -------------------------------- ### Develop and preview: run watch mode Source: https://github.com/swup/docs/blob/main/README.md Starts watch modes for both Eleventy and WebPack, which compile markdown to HTML and bundle assets (SCSS, JavaScript) respectively. The terminal will print the exact localhost URL for previewing the work. ```sh npm run watch ``` -------------------------------- ### Pass custom metadata via visit.meta Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Stores arbitrary data in visit.meta on 'visit:start' and retrieves it in a later hook ('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' }); ``` -------------------------------- ### Listen to Swup DOM events with swup: prefix Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md All hooks are also triggered on the document with a 'swup:' prefix. This example listens for 'swup:page:view' and accesses the visit object from the event's detail. ```javascript document.addEventListener('swup:page:view', ({ detail: { visit } }) => { console.log('Going to', visit.to.url); }); ``` -------------------------------- ### HTML Container with Animation Classes Source: https://github.com/swup/docs/blob/main/src/docs/announcements/swup-4.md Example of a content container element that receives animation classes when animationScope is set to 'containers'. ```html
Content
``` -------------------------------- ### Configure swup validation in swup.config.js Source: https://github.com/swup/docs/blob/main/src/docs/other/ci-cd.md Define validation settings and swup configuration in a swup.config.js file. This example includes default values for animation selectors, containers, and validation parameters. ```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) } }; ``` -------------------------------- ### Access trigger event on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Logs the DOM event that triggered the visit, typically a click event or undefined if triggered via the API. ```javascript swup.hooks.on('visit:start', (visit) => { console.log('Click event', visit.trigger.event); // MouseEvent }); ``` -------------------------------- ### Get cache size with swup.cache.size Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Access the size property to get the number of cache entries in memory. ```javascript swup.cache.size; // 13 ``` -------------------------------- ### Set hook handler options like once or before in Swup instance options Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Hook handler options such as 'once' or 'before' can be set by appending them to the hook name with a dot. This example shows 'visit:start.once' and 'content:replace.before'. ```javascript const swup = new Swup({ hooks: { 'visit:start.once': () => console.log('triggers once'), 'content:replace.before': () => console.log('triggers before hook') } }) ``` -------------------------------- ### Disable cache on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Sets visit.cache.read to false to control whether swup checks the cache or saves the new page, overriding the cache option. ```javascript swup.hooks.on('visit:start', (visit) => { visit.cache.read = false; }); ``` -------------------------------- ### Get cached page with swup.cache.get Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Return the page object for a cached URL, or undefined if not cached. ```javascript const page = swup.cache.get('/about'); ``` -------------------------------- ### Identify history visits on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Checks visit.history.popstate to detect back/forward button visits and logs the direction (forwards, backwards, or undefined). ```javascript swup.hooks.on('visit:start', (visit) => { if (visit.history.popstate) { console.log('History visit', visit.history.direction); } }); ``` -------------------------------- ### Disable animations on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Sets visit.animation.animate to false to load the new page instantaneously without animations. ```javascript swup.hooks.on('visit:start', (visit) => { visit.animation.animate = false; }); ``` -------------------------------- ### Access trigger element on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Logs the DOM element that triggered the visit, typically a link element or undefined if triggered via the API. ```javascript swup.hooks.on('visit:start', (visit) => { console.log('Clicked link', visit.trigger.el); // HTMLAnchorElement }); ``` -------------------------------- ### Replace history entry on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Sets visit.history.action to 'replace' to replace the current history entry instead of creating a new one. ```javascript swup.hooks.on('visit:start', (visit) => { visit.history.action = 'replace'; }); ``` -------------------------------- ### Parse a URL from a string using Location.fromUrl Source: https://github.com/swup/docs/blob/main/src/docs/api/helpers.md Parse a URL string into a Location object. The example shows destructuring the url and hash properties, with the expected values commented. ```javascript const href = 'http://example.net/about#anchor'; const { url, hash } = Location.fromUrl(href); // url = /about // hash = #anchor ``` -------------------------------- ### Access swup.location properties Source: https://github.com/swup/docs/blob/main/src/docs/api/properties.md Shows how to access properties of the swup.location object, which inherits from the native URL object and includes an additional url property. Use these to get the current page's path, query, and hash after redirects. ```javascript swup.location.href // https://example.net/path?query#hash swup.location.url // /path?query swup.location.pathname // /path swup.location.search // ?query swup.location.hash // #hash ``` -------------------------------- ### log(content, object?) Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Does nothing by default, but outputs the passed content when the debug plugin is used. Accepts two arguments: the content of the message and an optional log object which gets printed in a console group. ```APIDOC ## log(content, object?) ### Description Does nothing by default, but outputs the passed content when the debug plugin is used. Accepts two arguments, the content of message and an optional log object which gets printed in a console group. ### Method log ### Signature `swup.log(content, object?)` ### Parameters - **content** (any) - Required - The content of the message. - **object** (object) - Optional - A log object printed in a console group. ### Request Example ```javascript swup.log('Something happened', { lorem: 'ipsum' }); ``` ### Response No return value documented. ``` -------------------------------- ### CSS transition styles for animation class Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/example.md Define a CSS transition on the `transition-fade` class. The `html.is-changing` rule sets the transition and opacity during page visits, while `html.is-animating` sets the unloaded page styles. This example uses CSS animations; Swup also supports JS animations and native View Transitions. ```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; } ``` -------------------------------- ### Register and remove a handler with swup.hooks.on/off Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Remove a previously registered handler by passing the same function to swup.hooks.off. This example registers a handler for page:view and removes it later. ```javascript const handler = () => console.log('New page loaded'); // Register a handler swup.hooks.on('page:view', handler); // Remove it again later swup.hooks.off('page:view', handler); ``` -------------------------------- ### Build the site Source: https://github.com/swup/docs/blob/main/README.md Builds the documentation site for production. Run this command to generate the static HTML files. ```sh npm run build ``` -------------------------------- ### Use one transition-* element to set animation duration Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/common-issues.md Swup waits for any element with a transition-* class to finish animating. Using it on all animated elements is not required and often leads to bugs. It is recommended to use one element with a transition-* class to set the animation duration and make other animations happen independently. The CSS example shows a logo animation without the transition-* prefix. ```css /* Note: no transition-* prefix */ html.is-changing .logo { transition: 0.4s; opacity: 1; } html.is-animating .logo { opacity: 0; } ``` -------------------------------- ### Initialize Swup and Alpine.js Source: https://github.com/swup/docs/blob/main/src/docs/integrations/alpine.md Initialize both libraries to enable automatic initialization of Alpine components. ```javascript import Swup from 'swup'; import Alpine from 'alpinejs'; const swup = new Swup(); Alpine.start(); ``` -------------------------------- ### Initialize Swup via CDN Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/installation.md Include the minified production file from a CDN and initialize Swup in a script tag. ```html ``` -------------------------------- ### Initialize Swup with a bundler Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/installation.md Import the Swup class and create a new instance in your application code. ```javascript import Swup from 'swup'; const swup = new Swup(); ``` -------------------------------- ### Enable plugin at initialization Source: https://github.com/swup/docs/blob/main/src/docs/plugins/plugins.md Pass the plugin instance in the plugins array when creating a new Swup instance. ```javascript const swup = new Swup({ plugins: [new SwupScrollPlugin()] }); ``` -------------------------------- ### Initialize Swup via ESM and UMD fallback Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/installation.md Use the module type for modern browsers and the nomodule attribute for older browser compatibility. ```html ``` -------------------------------- ### Add plugin after initialization with use() Source: https://github.com/swup/docs/blob/main/src/docs/plugins/plugins.md Use swup's use method to add a plugin after the Swup instance has been created. ```javascript const swup = new Swup(); swup.use(new SwupScrollPlugin()); ``` -------------------------------- ### use(plugin) / unuse(plugin) Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Enable and disable plugins. `use` accepts an instantiated plugin instance, while `unuse` accepts either the plugin name or instance. ```APIDOC ## use(plugin) / unuse(plugin) ### Description Enable and disable plugins. ### Method use / unuse ### Signature `swup.use(plugin)` / `swup.unuse(plugin)` ### Parameters - **plugin** (object|string) - Required - For `use`: an instantiated plugin instance. For `unuse`: either the plugin name (string) or the plugin instance. ### Request Example ```javascript // Enable plugin: accepts an instantiated instance swup.use(new SwupScrollPlugin()); // Disable plugin: accepts either name or instance swup.unuse('SwupScrollPlugin'); ``` ### Response No return value documented. ``` -------------------------------- ### Registering event handlers for init on load and navigation Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/reloading-javascript.md Creates a Swup instance and registers init to run on initial load (using readyState or DOMContentLoaded) and after every navigation via the 'page:view' hook. ```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()); ``` -------------------------------- ### swup.cache.update(url, data) Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Update a cache record, overwriting or adding custom data. Gets merged with existing data. ```APIDOC ## swup.cache.update(url, data) ### Description Update a cache record, overwriting or adding custom data. Gets merged with existing data. ### Parameters - **url** (string) - Required - The URL of the cache record to update. - **data** (object) - Required - The data to merge into the existing record. ### Example ```javascript swup.cache.update('/about', { ttl: 1000, created: Date.now() }); ``` ``` -------------------------------- ### Use shortcuts for common handler options Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Shows the shortcuts for common handler options: once and before. These are equivalent to passing the corresponding option object. ```javascript swup.hooks.once('page:view', () => {}); // once: true swup.hooks.before('content:replace', () => {}); // before: true ``` -------------------------------- ### navigate(url, options) Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Navigates and transitions to a URL. Accepts an options object to configure the visit, such as disabling animations, setting a custom animation name, replacing history, sending POST requests, controlling cache, and passing custom metadata. ```APIDOC ## navigate(url, options) ### Description Navigate and transition to a URL. Pass an options object to configure how the page is loaded. ### Method navigate ### Signature `swup.navigate(url, options?)` ### Parameters - **url** (string) - Required - The URL to navigate to. - **options** (object) - Optional - Configuration object with the following properties: - **animate** (boolean) - Optional - Set to `false` to disable animations for this visit. - **animation** (string) - Optional - Set a custom animation name. - **history** (string) - Optional - Set to `'replace'` to replace the current history entry instead of creating a new one. - **method** (string) - Optional - HTTP method to use, e.g., `'POST'`. - **data** (FormData) - Optional - Form data to send with the request. - **cache** (object) - Optional - Cache configuration with `read` and `write` booleans. - **meta** (object) - Optional - Custom metadata available in all hooks. ### Request Example ```javascript swup.navigate(url); swup.navigate(url, { animate: false }); swup.navigate(url, { animation: 'custom' }); swup.navigate(url, { history: 'replace' }); swup.navigate(url, { method: 'POST', data: new FormData() }); swup.navigate(url, { cache: { read: false, write: true } }); swup.navigate(url, { meta: { lorem: 'ipsum' } }); ``` ### Response No return value documented. ``` -------------------------------- ### Disable scroll reset on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Sets visit.scroll.reset to false to keep the current scroll position after the new page loads. ```javascript swup.hooks.on('visit:start', (visit) => { visit.scroll.reset = false; }); ``` -------------------------------- ### Sanitize a string with classify Source: https://github.com/swup/docs/blob/main/src/docs/api/helpers.md Sanitize a string for use in CSS classnames or URL slugs. The example converts 'Lorem ipsum' to 'lorem-ipsum'. ```javascript const className = classify('Lorem ipsum'); ``` -------------------------------- ### Initialize new components on the page with swup.hooks.on('page:view') Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Use this snippet to initialize a component (e.g., a carousel) after a page view, but only if the component's root element exists on the new page. ```javascript swup.hooks.on('page:view', () => { if (document.querySelector('#carousel')) { const carousel = new Carousel('#carousel'); } }); ``` -------------------------------- ### Enable and disable plugins Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Shows how to enable a plugin with use and disable it with unuse. The use method accepts an instantiated instance, while unuse accepts either the name or instance. ```javascript // Enable plugin: accepts an instantiated instance swup.use(new SwupScrollPlugin()); // Disable plugin: accepts either name or instance swup.unuse('SwupScrollPlugin'); ``` -------------------------------- ### Helper import diff: getPageData Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Update import paths for helpers from `swup/lib/helpers` to `swup`. ```diff - import { getPageData } from 'swup/lib/helpers'; + import { getPageData } from 'swup'; ``` -------------------------------- ### Set custom animation name on visit:start Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Sets visit.animation.name to 'slide' to apply a custom .to-slide class on the html element for CSS targeting. ```javascript swup.hooks.on('visit:start', (visit) => { visit.animation.name = 'slide'; }); ``` -------------------------------- ### Create a history record with 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 and internal metadata that swup recognizes. ```javascript createHistoryRecord('/new-page', { custom: 'data' }); ``` -------------------------------- ### Migrating from transition object to visit object Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Shows the transition from the deprecated swup 3 transition object to the new swup 4 visit object. ```js 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 ++] ``` -------------------------------- ### 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) - Required - The URL for the new history record. - **data** (object) - Optional - Custom data to append to the history record. ### Example ```javascript createHistoryRecord('/new-page', { custom: 'data' }); ``` ``` -------------------------------- ### Log a message Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Outputs the passed content when the debug plugin is used. Accepts two arguments: the content of message and an optional log object which gets printed in a console group. ```javascript swup.log('Something happened', { lorem: 'ipsum' }); ``` -------------------------------- ### Access visit object in page:view hook Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/visit.md Use this snippet to access the visit object in any hook handler. The example logs the URL of the new page from the visit.to.url property. ```javascript swup.hooks.on('page:view', (visit) => { console.log('New page: ', visit.to.url); }); ``` -------------------------------- ### Enable native View Transitions 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 browser's built-in View Transitions API. ```js const swup = new Swup({ native: true }); ``` -------------------------------- ### Replace custom hook default handler with axios Source: https://github.com/swup/docs/blob/main/src/docs/plugins/create-plugin.md Consumers can replace the default handler of a custom hook with their own implementation. This example uses axios instead of fetch to submit the form. ```javascript swup.hooks.replace('form:submit', (visit, { action, data }) => { return axios.get(action, { params: data }).then(/* */); }); ``` -------------------------------- ### Configure swup in astro.config.mjs Source: https://github.com/swup/docs/blob/main/src/docs/integrations/astro.md Add the swup integration to your Astro configuration file to enable client-side transitions. ```javascript // astro.config.mjs import { defineConfig } from 'astro/config'; import swup from '@swup/astro'; export default defineConfig({ integrations: [swup()] }); ``` -------------------------------- ### Route Name Plugin configuration Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md To restore the previous behavior of adding `from-*` and `to-*` classes, use the Route Name Plugin with `paths: true`. ```javascript const swup = new Swup({ plugins: [new SwupRouteNamePlugin({ paths: true })] }); ``` -------------------------------- ### Display loading indicator during transitions with animation hooks Source: https://github.com/swup/docs/blob/main/src/docs/lifecycle/hooks.md Use these two hooks to show a loading indicator when the outgoing animation starts and hide it when the incoming animation ends. The indicator is toggled via the 'hidden' property. ```javascript swup.hooks.on('animation:out:start', () => { document.querySelector('#loader').hidden = false; }); swup.hooks.on('animation:in:end', () => { document.querySelector('#loader').hidden = true; }); ``` -------------------------------- ### swup.cache.set(url, page) Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Create a cache record for the specified URL. Pass in a page object with a `url` and `html` property. ```APIDOC ## swup.cache.set(url, page) ### Description Create a cache record for the specified URL. Pass in a page object with a `url` and `html` property. ### Parameters - **url** (string) - Required - The URL to cache. - **page** (object) - Required - The page object with `url` and `html` properties. ### Example ```javascript swup.cache.set('/about', { url: '/about', html: '...' }); ``` ``` -------------------------------- ### Import Swup and SwupScrollPlugin Source: https://github.com/swup/docs/blob/main/src/docs/plugins/plugins.md Import the Swup core and the scroll plugin for use in your JavaScript bundle. ```javascript import Swup from 'swup'; import SwupScrollPlugin from '@swup/scroll-plugin'; ``` -------------------------------- ### Clear cache with swup.cache.clear Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Empty the entire cache. ```javascript swup.cache.clear(); ``` -------------------------------- ### Accessing the visit object Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Demonstrates how to use the visit object to access visit details and modify animation settings during hooks. ```javascript // Get the next URL and the link element that was clicked swup.hooks.on('page:view', (visit) => { console.log('New page: ', visit.to.url); console.log('Triggered by: ', visit.trigger.el); }); // Disable animations on the upcoming visit swup.hooks.on('visit:start', (visit) => { visit.animation.animate = false; }); ``` -------------------------------- ### Navigate with custom metadata Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Sends along custom metadata available in all hooks via the meta option. ```javascript swup.navigate(url, { meta: { lorem: 'ipsum' } }) ``` -------------------------------- ### Event delegation helper diff Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Swup now bundles its event delegation library. Replace `delegate-it` with the `delegateEvent` helper on the swup instance. The delegate parent `document` is assumed. ```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) + ); ``` -------------------------------- ### Configure linkToSelf behavior Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Determines how swup handles links to the current URL. Setting to 'navigate' performs a regular navigation instead of scrolling to the top. ```javascript { linkToSelf: 'navigate' } ``` -------------------------------- ### Running code before content replacement Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Uses swup.hooks.before to execute code right before the content is replaced, replacing the old willReplaceContent event. ```js // Run right before the content is replaced swup.on('willReplaceContent', () => {}) // [!code --] swup.hooks.before('content:replace', () => {}) // [!code ++] ``` -------------------------------- ### Find plugin instance Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Returns the plugin instance by that name, if enabled. ```javascript const pluginInstance = swup.findPlugin('SwupScrollPlugin'); ``` -------------------------------- ### CDN script import diff Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Update the CDN script tag from `https://unpkg.com/swup@2/dist/swup.min.js` to `https://unpkg.com/swup@3`. ```diff - + ``` -------------------------------- ### Switch from events to hooks Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Replace event listeners with the new hook-based system. ```js this.swup.on('contentReplaced', () => {}); // [!code --] this.swup.hooks.on('content:replace', () => {}); // [!code ++] ``` -------------------------------- ### Content container with id and animation class Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/example.md Mark the main element as a content container by adding the id `#swup` and the animation class `transition-fade`. The container and animation selectors are defaults and can be adjusted in the options. ```html

Welcome

Lorem ipsum dolor sit amet.

``` -------------------------------- ### Configure animateHistoryBrowsing Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Set animateHistoryBrowsing to true to enable animations on back/forward button visits. Defaults to false. ```javascript { animateHistoryBrowsing: false } ``` -------------------------------- ### Set cache record with swup.cache.set Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Create a cache record for a URL by passing a page object with url and html properties. ```javascript swup.cache.set('/about', { url: '/about', html: '...' }); ``` -------------------------------- ### Default Swup options Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Shows the default options object passed to the Swup constructor. These defaults can be overridden during initialization. ```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 }); ``` -------------------------------- ### Configure skipPopStateHandling Source: https://github.com/swup/docs/blob/main/src/docs/options/options.md Provides a custom callback to determine if a popstate event should be handled by swup or the browser. Defaults to ignoring entries without a custom source property. ```javascript { skipPopStateHandling: (event) => event.state?.source !== 'swup' } ``` -------------------------------- ### findPlugin(name) Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Returns the plugin instance by that name, if enabled. ```APIDOC ## findPlugin(name) ### Description Returns the plugin instance by that name, if enabled. ### Method findPlugin ### Signature `swup.findPlugin(name)` ### Parameters - **name** (string) - Required - The name of the plugin. ### Request Example ```javascript const pluginInstance = swup.findPlugin('SwupScrollPlugin'); ``` ### Response Returns the plugin instance if enabled. ``` -------------------------------- ### Import helpers from swup Source: https://github.com/swup/docs/blob/main/src/docs/api/helpers.md Import the helper functions getCurrentUrl and updateHistoryRecord from the swup package. ```javascript import { getCurrentUrl, updateHistoryRecord } from 'swup'; ``` -------------------------------- ### Run Hook Before Internal Handler Source: https://github.com/swup/docs/blob/main/src/docs/announcements/swup-4.md Execute a hook handler before the internal Swup handler using the before method. ```javascript swup.hooks.before('content:replace', () => { // Execute before swup replaces the content }); ``` -------------------------------- ### Navigate to a URL Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Calls the navigate method to transition to a URL. ```javascript swup.navigate(url); ``` -------------------------------- ### Navigate with POST request and form data Source: https://github.com/swup/docs/blob/main/src/docs/api/methods.md Sends a POST request with form data by specifying method and data options. ```javascript swup.navigate(url, { method: 'POST', data: new FormData() }); ``` -------------------------------- ### Registering hooks with swup.hooks.on Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Replaces the old swup.on event registration with the new swup.hooks.on method. ```js swup.on('pageView', () => {}) // [!code --] swup.hooks.on('page:view', () => {}) // [!code ++] ``` -------------------------------- ### Script import diff: UMD path Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading-v3.md Update the script tag path for the UMD version of swup from `./dist/swup.js` to `./dist/Swup.umd.js`. ```diff - + ``` -------------------------------- ### Limit cache pages with cache:set hook Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Prune the cache to a maximum number of entries by listening to the cache:set hook and using cache.prune. ```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)); }); ``` -------------------------------- ### Combining DOMContentLoaded and swup hooks for page changes Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/reloading-javascript.md Template for running code on initial load and after every page change by swup using the 'page:view' hook. ```javascript document.addEventListener('DOMContentLoaded', () => { // This runs on initial load }); swup.hooks.on('page:view', () => { // This runs after every page change by swup }); ``` -------------------------------- ### Use animationSelector to avoid conflicts with transition-* classes Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/common-issues.md When third-party libraries like Foundation use transition-* classes, swup may wait for animations on those elements, causing timing issues. Setting a stricter animationSelector to a custom prefix like 'swup-transition-' fixes the problem. The HTML and CSS show the corresponding class usage and animation styles. ```javascript var swup = new Swup({ animationSelector: '[class*="swup-transition-"]' }); ``` ```html
``` ```css html.is-changing .swup-transition-fade { transition: 0.4s; opacity: 1; } html.is-animating .swup-transition-fade { opacity: 0; } ``` -------------------------------- ### Collecting initialization scripts in an init function Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/reloading-javascript.md Defines an init function that conditionally initializes components based on the presence of related elements on the page. ```javascript function init() { if (document.querySelector('#carousel')) { // new Carousel('#carousel') } if (document.querySelector('#lightbox')) { // $('#lightbox').lightbox() } if (document.querySelector('#something-else')) { // and so on } } ``` -------------------------------- ### swup.cache.get(url) Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Return the page object if the given URL is cached, `undefined` otherwise. ```APIDOC ## swup.cache.get(url) ### Description Return the page object if the given URL is cached, `undefined` otherwise. ### Parameters - **url** (string) - Required - The URL to retrieve. ### Returns - **page** (object) - The cached page object, or `undefined` if not cached. ### Example ```javascript const page = swup.cache.get('/about'); ``` ``` -------------------------------- ### swup.cache.clear() Source: https://github.com/swup/docs/blob/main/src/docs/api/cache.md Empty the cache. ```APIDOC ## swup.cache.clear() ### Description Empty the cache. ### Example ```javascript swup.cache.clear(); ``` ``` -------------------------------- ### Update swup CDN version Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Update the script source URL to point to version 4 when loading swup via CDN. ```html // [!code --] // [!code ++] ``` -------------------------------- ### Await hook completion Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/upgrading.md Use the await keyword when you need to wait for all hook handlers to finish. ```js this.swup.triggerEvent('formSubmit'); // [!code --] await this.swup.hooks.call('form:submit'); // [!code ++] ``` -------------------------------- ### Target fallback animations for unsupported browsers Source: https://github.com/swup/docs/blob/main/src/docs/getting-started/animations.md Use the swup-native class to apply CSS transitions only in browsers that do not support the View Transitions API. ```css html.is-changing:not(.swup-native) .transition-fade { transition: 0.25s opacity; opacity: 1; } html.is-animating:not(.swup-native) .transition-fade { opacity: 0; } ``` -------------------------------- ### Persist element state with data-swup-persist Source: https://github.com/swup/docs/blob/main/src/docs/api/markup.md Use data-swup-persist with a unique key to preserve an element's content, data, and event listeners across page loads. ```html