### Initialize Barba with Prefetch Plugin
Source: https://barba.js.org/docs/plugins/prefetch
Use this snippet to enable the prefetch plugin in Barba. Ensure Barba core and the prefetch plugin are installed and imported.
```javascript
import barba from '@barba/core';
import barbaPrefetch from '@barba/prefetch';
// tell Barba to use the prefetch plugin
barba.use(barbaPrefetch);
// init Barba
barba.init();
```
--------------------------------
### Install Barba.js with NPM or Yarn
Source: https://barba.js.org/docs/getstarted/install
Install Barba.js using your preferred package manager. This is recommended when using JavaScript bundlers like webpack or rollup.
```bash
# npm
npm install @barba/core
# yarn
yarn add @barba/core
```
--------------------------------
### Barba.js Initialization with CSS Plugin and Custom Rules
Source: https://barba.js.org/docs/plugins/css
Initializes Barba.js with the CSS plugin and defines custom transition rules based on namespaces. This setup allows for different transitions between specific pages.
```javascript
import barba from '@barba/core';
import barbaCss from '@barba/css';
// tell Barba to use the css plugin
barba.use(barbaCss);
// init Barba
barba.init({
transitions: [{
name: 'fade',
leave() {},
enter() {}
}, {
name: 'slide',
leave() {},
enter() {},
from: {
namespace: 'home'
},
to: {
namespace: 'products'
}
}]
});
```
--------------------------------
### Initialize Barba with Default Transition
Source: https://barba.js.org/docs/getstarted/basic-transition
This snippet shows the basic structure for initializing Barba.js and defining a default transition with leave and enter animation hooks. Use this as a starting point for custom page transitions.
```javascript
barba.init({
transitions: [{
name: 'default-transition',
leave() {
// create your stunning leave animation here
},
enter() {
// create your amazing enter animation here
}
}]
});
```
--------------------------------
### Partial Page Output with PHP for Barba.js
Source: https://barba.js.org/docs/advanced/recipes
Detect the `x-barba` header on the server-side (PHP example) to output only the necessary content, reducing bandwidth and server load for Barba.js transitions.
```php
```
--------------------------------
### Define Global Enter Hook
Source: https://barba.js.org/docs/advanced/hooks
Example of defining a global hook using `barba.hooks.enter` to log the namespace of the next page whenever an enter transition occurs. Global hooks can be set up anywhere.
```javascript
barba.hooks.enter((data) => {
console.log(data.next.namespace);
});
```
--------------------------------
### Transition Rule Conditions: Namespace
Source: https://barba.js.org/docs/advanced/transitions
Specify conditions for transitions using properties like `namespace`. This example shows a transition that only plays if the current page's namespace is 'home'.
```javascript
barba.init({
transitions: [{
name: 'custom-transition',
from: {
namespace: [
'home'
]
}
}]
});
```
--------------------------------
### Manage Custom Request Headers in Barba.js
Source: https://barba.js.org/docs/advanced/recipes
Set, get, check, delete, and clear custom HTTP headers for Barba.js requests. Headers must be set before the transition starts to be sent server-side.
```javascript
// set request headers
barba.headers.set('x-header-name', 'headerValue');
barba.headers.set('x-another-header-name', 'anotherHeaderValue');
// overwrite one
barba.headers.set('x-header-name', 'overwrite');
// get a specific header
const header = barba.headers.get('x-header-name');
// get all header
const headers = barba.headers.all();
// check if a custom header exists
if (barba.headers.has('x-header-name')) {
// do something
}
// delete a custom header
barba.headers.delete('x-header-name');
// clear all headers
barba.headers.clear();
```
--------------------------------
### Barba.js Hooks for Locomotive Scroll Lifecycle Management
Source: https://barba.js.org/docs/advanced/third-party
Manage Locomotive Scroll's state during Barba.js transitions using hooks. This example shows stopping scroll before transitions, resetting position on enter, and starting scroll after transitions.
```javascript
const scroll = new LocomotiveScroll();
// lock the scroll to prevent further animations when transitioning
barba.hooks.before(() => {
scroll.stop();
});
// reset scroll position and update the scroll when the next page is fetched
barba.hooks.enter(() => {
scroll.scrollTo({
offset: 0,
smooth: false,
disableLerp: true,
duration: 0
});
scroll.update();
});
// unlock the scroll, in order to let the user be able to scroll again
barba.hooks.after(() => {
scroll.start();
});
```
--------------------------------
### barba.history.previous
Source: https://barba.js.org/docs/advanced/utils
Get the previous history object, see history strategy.
```APIDOC
## barba.history.previous
### Description
Get the previous history object. See history strategy for more details.
### Usage
```javascript
const previousHistory = barba.history.previous
```
```
--------------------------------
### barba.history.current
Source: https://barba.js.org/docs/advanced/utils
Get the current history object, see history strategy.
```APIDOC
## barba.history.current
### Description
Get the current history object. See history strategy for more details.
### Usage
```javascript
const currentHistory = barba.history.current
```
```
--------------------------------
### barba.cache.get(url)
Source: https://barba.js.org/docs/advanced/utils
Get cache data for a given URL and retrieve action, request, status and target.
```APIDOC
## barba.cache.get(url)
### Description
Get cache data for a given URL and retrieve action, request, status and target.
### Parameters
- **url** (string) - The URL to get cache data for.
### Usage
```javascript
const cacheData = barba.cache.get('https://example.com/cached-page')
```
```
--------------------------------
### Custom Headers Management
Source: https://barba.js.org/docs/advanced/recipes
Set, get, check, delete, and clear custom request headers for `XMLHttpRequest` objects.
```APIDOC
## Custom headers
### Description
You can **pass custom request headers** to the `XMLHttpRequest` object and manage them using exposed methods.
### Request Example
```javascript
// set request headers
barba.headers.set('x-header-name', 'headerValue');
barba.headers.set('x-another-header-name', 'anotherHeaderValue');
// overwrite one
barba.headers.set('x-header-name', 'overwrite');
// get a specific header
const header = barba.headers.get('x-header-name');
// get all header
const headers = barba.headers.all();
// check if a custom header exists
if (barba.headers.has('x-header-name')) {
// do something
}
// delete a custom header
barba.headers.delete('x-header-name');
// clear all headers
barba.headers.clear();
```
### Note
Keep in mind that if you want a request header to be present server-side, you need to set it **before Barba starts the page transition**. By default, Barba sends **a non-removable custom HTTP Header** named `x-barba`.
```
--------------------------------
### Initialize Barba with a Plugin
Source: https://barba.js.org/docs/plugins/intro
Import and use a Barba plugin with custom options before initializing Barba. Ensure correct import naming when using a CDN.
```javascript
import barba from '@barba/core';
import barbaPlugin from '@barba/plugin';
// tell Barba what plugin to use
barba.use(barbaPlugin, {
custom: 'value',
});
// init Barba
barba.init({
...
});
```
--------------------------------
### Barba.init Options
Source: https://barba.js.org/docs/advanced/options
This snippet shows the available options for initializing Barba.js with their default values.
```APIDOC
## barba.init Options
### Description
Configuration options for initializing Barba.js.
### Method
`barba.init(options)`
### Parameters
#### Request Body
- **cacheFirstPage** (boolean) - Optional - Disable cache on the first rendered page.
- **cacheIgnore** (IgnoreOption) - Optional - Disable cache or ignore some routes.
- **debug** (boolean) - Optional - Enable debug mode.
- **logLevel** (keyof LogLevels) - Optional - Set custom log level for fine-grained debugging.
- **prefetchIgnore** (IgnoreOption) - Optional - Disable prefetch or ignore routes.
- **prevent** (PreventCheck) - Optional - Set custom prevent check.
- **preventRunning** (boolean) - Optional - Prevent click when transition is running.
- **requestError** (RequestCustomError) - Optional - Set custom request error.
- **schema** (ISchemaAttribute) - Optional - Set custom schema to override data-barba attributes.
- **timeout** (number) - Optional - Request timeout.
- **transitions** (ITransitionPage[]) - Optional - Array of Transitions.
- **views** (IView[]) - Optional - Array of Views.
### Request Example
```json
{
"cacheFirstPage": false,
"cacheIgnore": false,
"debug": false,
"logLevel": "off",
"prefetchIgnore": false,
"prevent": null,
"preventRunning": false,
"schema": null,
"timeout": 2000,
"transitions": [],
"views": []
}
```
### Response
#### Success Response (200)
Barba.js initialization is typically a one-time setup and does not return a specific response body. The success is indicated by the application functioning as expected.
#### Response Example
N/A
```
--------------------------------
### Initialize Barba with CSS Plugin
Source: https://barba.js.org/docs/plugins/css
Import and use the barbaCss plugin before initializing Barba. This enables the CSS class management for transitions.
```javascript
import barba from '@barba/core';
import barbaCss from '@barba/css';
// tell Barba to use the css plugin
barba.use(barbaCss);
// init Barba
barba.init();
```
--------------------------------
### Import and Initialize Barba.js with a Bundler
Source: https://barba.js.org/docs/getstarted/install
Import Barba.js as a module and initialize it within your application. This approach leverages the benefits of bundlers for optimized builds.
```javascript
import barba from '@barba/core';
barba.init({
// ...
});
```
--------------------------------
### Initialize Barba.js from CDN
Source: https://barba.js.org/docs/getstarted/install
Initialize Barba.js after including it via a CDN script tag. The CDN will default to the @latest version and the UMD build.
```javascript
```
--------------------------------
### BarbaJS Legacy HTML with Opacity Transition
Source: https://barba.js.org/docs/getstarted/legacy
This HTML file sets up the BarbaJS wrapper and container for the homepage. It includes basic styles to prevent layout shifts during transitions and initializes BarbaJS with a simple GSAP-based opacity transition. Ensure this file is linked to other pages via anchor tags.
```html
Index — BarbaJS legacy example
Home
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
About
```
--------------------------------
### Prefetch Configuration and Usage
Source: https://barba.js.org/docs/advanced/strategies
Configure Barba.js to prefetch pages on user interaction (mouseover, touchstart) and programmatically prefetch specific URLs to improve perceived performance.
```APIDOC
## Prefetch Configuration and Usage
### `prefetchIgnore`
Allows Barba to **prefetch your pages** on `mouseover` or `touchstart` events. This leverages the delay between user hover and click to start prefetching.
Value | Description
---|---
`false` _(default)_ | Prefetch all eligible links
`true` | Ignore all prefetching
`String | String[]` | Ignore route pattern(s)
**Example:**
```javascript
barba.init({
prefetchIgnore: '/home/'
});
```
> To prefetch all eligible links that **enter the viewport**, use the @barba/prefetch plugin.
### `barba.prefetch(url)`
You can **programmatically prefetch some URLs** using the `barba.prefetch` code method:
**Example:**
```javascript
barba.prefetch('about.html');
```
> Note that **all prefetched URLs are stored absolute** in the barba.cache. If you prefetch `about.html`, it will be stored as `https://localhost/about.html`.
```
--------------------------------
### Initialize Barba with Router Plugin and Custom Routes
Source: https://barba.js.org/docs/plugins/router
Define your routes and then use the router plugin with these routes before initializing Barba. The `routes` property accepts an array of Route objects, each with a `name` and a `path`. The `path` supports dynamic segments and regular expressions.
```javascript
import barba from '@barba/core';
import barbaRouter from '@barba/router';
// define your routes
const myRoutes = [{
path: '/index',
name: 'home'
}, {
path: '/product/:id',
name: 'item'
}];
// tell Barba to use the router with your routes
barba.use(barbaRouter, {
routes: myRoutes
});
// init Barba
barba.init();
```
--------------------------------
### Barba.js Initialization Options
Source: https://barba.js.org/docs/advanced/options
Defines the default configuration for Barba.js initialization. Use these options to customize caching, debugging, and transition behavior.
```javascript
barba.init({
cacheFirstPage: false,
cacheIgnore: false,
debug: false,
logLevel: 'off',
prefetchIgnore: false,
prevent: null,
preventRunning: false,
schema: [[SchemaAttribute]],
timeout: 2e3,
transitions: [],
views: []
})
```
--------------------------------
### barba.go(href, trigger, e)
Source: https://barba.js.org/docs/advanced/utils
Tell Barba to go to a specific URL and play your transitions, if available, without using a browser “force reload”.
```APIDOC
## barba.go(href, trigger, e)
### Description
Tell Barba to go to a specific URL and play your transitions, if available, without using a browser “force reload”.
### Parameters
- **href** (string) - The URL to navigate to.
- **trigger** (Trigger) - Optional. The trigger for the navigation.
- **e** (LinkEvent | PopStateEvent) - Optional. The event that triggered the navigation.
### Usage
```javascript
barba.go('https://example.com')
```
```
--------------------------------
### Define Transitions with Rules
Source: https://barba.js.org/docs/advanced/transitions
Configure specific transitions using `from` and `to` rules to control when a transition should play based on the current and next page properties. These rules are evaluated based on priority.
```javascript
barba.init({
transitions: [{
name: 'custom-transition',
from: {
// set of conditions to be fulfilled
// to play the transition
},
to: {
// set of conditions to be fulfilled
// to play the transition
}
}]
});
```
--------------------------------
### Configure Barba Prefetch Plugin Options
Source: https://barba.js.org/docs/plugins/prefetch
Configure the prefetch plugin with custom options for root element, timeout, and link limit. This allows finer control over which links are prefetched and when.
```javascript
import barba from '@barba/core';
import barbaPrefetch from '@barba/prefetch';
// get the wrapper
const wrapper = document.querySelector('.prefetch-wrapper');
// tell Barba to use the prefetch plugin
barba.use(barbaPrefetch, {
root: wrapper,
timeout: 2500,
limit: 0
});
// init Barba
barba.init();
```
--------------------------------
### Define Base Hooks with Promises or `this.async()`
Source: https://barba.js.org/docs/advanced/hooks
Demonstrates various ways to define base hooks like `leave` using Promises (arrow function, ES6 syntax, resolve call) or the `this.async()` method for asynchronous operations.
```javascript
// using a promise (returned with arrow function)
leave: (data) => asyncAnimation(data.current.container)
```
```javascript
// using a promise (with ES6 argument syntax)
leave: ({ current }) => asyncAnimation(current.container)
```
```javascript
// using a promise (with a resolve call)
leave: (data) => {
return new Promise(resolve => {
callbackAnimation(data.current.container, {
onComplete: () => {
resolve();
}
});
});
}
```
```javascript
// `this.async()`
leave(data) {
const done = this.async();
callbackAnimation(data.current.container, {
onComplete: () => {
done();
}
});
}
```
```javascript
// async/await
async leave(data) {
await asyncAnimation(data.current.container);
}
```
--------------------------------
### Initialize Barba.js with Custom View Logic
Source: https://barba.js.org/docs/getstarted/custom-code
Use the `views` property in `barba.init` to define custom code that runs for specific page namespaces. The `beforeEnter` and `afterEnter` hooks are ideal for refreshing components or libraries.
```javascript
barba.init({
views: [{
namespace: 'home',
beforeEnter() {
// update the menu based on user navigation
menu.update();
},
afterEnter() {
// refresh the parallax based on new page content
parallax.refresh();
}
}]
});
```
--------------------------------
### Timeout Configuration
Source: https://barba.js.org/docs/advanced/recipes
Adjust the timeout duration for page loading to prevent Barba from aborting transitions on slow networks.
```APIDOC
## timeout
### Description
On slow network or with a high page weight, the server can take time to give a response to the user. In case the page take **more than timeout** to be loaded, it lead Barba to abort the transition and display a _Timeout error_ message. To prevent this behavior, you can increase the `timeout`.
### Request Example
```javascript
barba.init({
timeout: 5000
});
```
### Note
In addition, you can properly catch the error by using the `requestError` callback. If a timeout occurs when you are trying to go to another page, Barba will redirect you instead of reloading the page.
```
--------------------------------
### Include Barba.js via CDN
Source: https://barba.js.org/docs/getstarted/install
Include the minified Barba.js production file directly in your HTML using a CDN. It's recommended to use a specific tagged version for stability.
```html
```
--------------------------------
### Google ReCaptcha Initialization
Source: https://barba.js.org/docs/advanced/third-party
Include the Google ReCaptcha API script and initialize the reCaptcha execution within a Barba view's beforeEnter hook. Ensure the script is loaded before calling grecaptcha.ready().
```html
```
```javascript
barba.init({
views: [{
namespace: 'index',
beforeEnter() {
grecaptcha.ready(() => {
grecaptcha.execute(key, {
action: 'captcha_index'
}).then((token) => {
// send token to your backend in order to check the captcha:
// you will need to make a POST request with token and private key
// see https://developers.google.com/recaptcha/docs/verify#api_request
});
});
}
}
});
```
--------------------------------
### Configure Prefetch Ignore Patterns
Source: https://barba.js.org/docs/advanced/strategies
Use `prefetchIgnore` to define routes that Barba should not prefetch. This prevents prefetching on pages where it might be undesirable.
```javascript
barba.init({
prefetchIgnore: '/home/'
});
```
--------------------------------
### barba.prefetch(href)
Source: https://barba.js.org/docs/advanced/utils
Prefetch the given URL, see prefetch strategy.
```APIDOC
## barba.prefetch(href)
### Description
Prefetch the given URL. See prefetch strategy for more details.
### Parameters
- **href** (string) - The URL to prefetch.
### Usage
```javascript
barba.prefetch('https://example.com')
```
```
--------------------------------
### Enable Sync Mode for Concurrent Transitions
Source: https://barba.js.org/docs/advanced/transitions
Enable sync mode to play 'leave' and 'enter' transition hooks concurrently. This mode waits for the next page to be ready before playing the enter transition, allowing for crossfade effects.
```javascript
barba.init({
transitions: [{
sync: true,
leave() {
// transition that will play concurrently to `enter`
},
enter() {
// transition that will play concurrently to `leave`
}
}]
});
```
--------------------------------
### Basic Opacity Transition with GSAP
Source: https://barba.js.org/docs/getstarted/basic-transition
Implement a simple fade-out and fade-in transition using GSAP. The 'leave' hook animates the current container to opacity 0, and the 'enter' hook animates the next container from opacity 0. Ensure proper CSS positioning for cross-fading effects.
```javascript
barba.init({
transitions: [{
name: 'opacity-transition',
leave(data) {
return gsap.to(data.current.container, {
opacity: 0
});
},
enter(data) {
return gsap.from(data.next.container, {
opacity: 0
});
}
}]
});
```
--------------------------------
### Programmatically Prefetch a URL
Source: https://barba.js.org/docs/advanced/strategies
Use the `barba.prefetch` method to manually trigger prefetching for a specific URL. Prefetched URLs are stored as absolute paths in the cache.
```javascript
barba.prefetch('about.html');
```
--------------------------------
### Initialize Lenis with Barba.js for Native Scrolling
Source: https://barba.js.org/docs/advanced/third-party
Integrate Lenis for native browser scrolling with Barba.js. Lenis does not require manual updates between page transitions as it uses the browser's native scrolling mechanism.
```javascript
import barba from '@barba/core';
import Lenis from '@studio-freight/lenis';
// init lenis
const lenis = new Lenis({
lerp: 0.1,
smooth: true,
});
const loop = (time) => {
lenis.raf(time);
requestAnimationFrame(loop);
};
requestAnimationFrame(loop);
// init barba
barba.init();
```
--------------------------------
### Enable Barba.js Debugging
Source: https://barba.js.org/docs/advanced/recipes
Enable the Barba.js debugger to display transition information in the console for debugging purposes. Recommended for development environments only.
```javascript
barba.init({
debug: true
});
```
--------------------------------
### Define Views with Namespaces in Barba.js
Source: https://barba.js.org/docs/advanced/views
Define views for different namespaces to execute logic before entering or after leaving specific page sections. Ensure each view is tied to a unique namespace.
```javascript
barba.init({
views: [{
namespace: 'index',
beforeLeave(data) {
// do something before leaving the current `index` namespace
}
}, {
namespace: 'contact',
beforeEnter(data) {
// do something before entering the `contact` namespace
}
}]
});
```
--------------------------------
### Partial Output for Server-Side Rendering
Source: https://barba.js.org/docs/advanced/recipes
Configure Barba.js to handle partial page outputs from server-side languages like PHP, reducing bandwidth and server load.
```APIDOC
## Partial output
### Description
If you are using a **server side language like PHP**, you can detect your custom HTTP headers and output just the container instead of the entire page: this could result in **less bandwidth usage** and **less server-side load**.
### Request Example
```php
```
### Note
Note that doing so, you have to manually handle the update of the page `title`.
```
--------------------------------
### Barba.js CSS Plugin Transition Hooks
Source: https://barba.js.org/docs/plugins/css
Demonstrates the use of Barba.js transition hooks when the CSS plugin is active. Note that the `once` hook is overridden by the plugin and code within it will not execute.
```javascript
barba.init({
transitions: [{
name: 'hello'
once: () => {
// code here won't run...
},
beforeLeave: () => {
console.log('This message will be displayed in the console!');
}
}]
});
```
--------------------------------
### barba.version
Source: https://barba.js.org/docs/advanced/utils
Retrieve the current @barba/core version.
```APIDOC
## barba.version
### Description
Retrieve the current @barba/core version.
### Usage
```javascript
barba.version
```
```
--------------------------------
### history.store Method
Source: https://barba.js.org/docs/advanced/strategies
Store custom data associated with user navigation, making it accessible across page transitions.
```APIDOC
#### `history.store`
In some situations, you may need to **store custom information based on user navigation** and access them later in your code. Barba now offers a way of doing this with ease using the `barba.history.store` method.
### Usage
```javascript
barba.history.store({
id: 2547,
random: Math.random(),
href: window.location.href,
});
```
### Accessing Stored Data
Custom data can be accessed from `barba.history.previous.data` after a page transition:
```javascript
const id = barba.history.previous.data.id;
const random = barba.history.previous.data.random;
const href = barba.history.previous.data.href;
```
> Be careful, data will be overwritten if you call twice the `store` method with the same data attribute. Data are automatically rolled within the history using `replaceState` API.
```
--------------------------------
### Define Transition with Custom Name
Source: https://barba.js.org/docs/plugins/css
When initializing Barba, specify a 'name' property for your transition. This name will be used as a prefix for generated CSS classes.
```javascript
barba.init({
transitions: [{
name: 'hello'
once: () => {}
}]
});
```
--------------------------------
### Self Transition for Same-Page Navigation
Source: https://barba.js.org/docs/advanced/transitions
Implement a 'self' transition that is triggered when navigating to the same page, often used for hash-based navigation. This transition can utilize all base hooks.
```javascript
transitions: [{
name: 'self',
enter() {
// create your self transition here
},
}]
```
--------------------------------
### Programmatically Access and Call Views in Barba.js
Source: https://barba.js.org/docs/advanced/views
Access and trigger view lifecycle methods programmatically using the `barba.views.byNamespace` Map. This is useful for manual control over view execution.
```javascript
// return all views as a Map
const views = barba.views.byNamespace;
// get the view of the `home` namespace
const homeView = views.get('home');
// call the home `afterEnter` view
homeView.afterEnter();
```
--------------------------------
### CSS for Browser Load Transition
Source: https://barba.js.org/docs/plugins/css
Provides CSS classes to enable a transition effect on the initial page load when using Barba.js. Ensure the `.barba-once-active` class is set for the transition to be visible.
```css
.barba-once-active {
transition: opacity 450ms ease;
}
.barba-once {
opacity: 0;
}
.barba-once-to {
opacity: 1;
}
```
--------------------------------
### Basic Opacity Transition CSS
Source: https://barba.js.org/docs/plugins/css
Define CSS rules for Barba's default transition classes to create a simple opacity fade effect. Ensure these classes are applied to your container.
```css
.barba-leave-active,
.barba-enter-active {
transition: opacity 450ms ease;
}
.barba-leave,
.barba-enter-to {
opacity: 1;
}
.barba-enter,
.barba-leave-to {
opacity: 0;
}
```
--------------------------------
### Enable Caching for the First Page
Source: https://barba.js.org/docs/advanced/strategies
Set `cacheFirstPage` to `true` to cache the initial page load. Be cautious as this cached HTML might become outdated if modified by other scripts.
```javascript
barba.init({
cacheFirstPage: true
});
```
--------------------------------
### Programmatically Add History Entries
Source: https://barba.js.org/docs/advanced/strategies
Use `barba.history.add` to programmatically push or replace history entries. Specify the URL, a trigger (like 'barba'), and the action ('push' or 'replace').
```javascript
// push a new entry in the history
history.add('push.html', 'barba', 'push');
// replace a history entry
history.add('replace.html', 'barba', 'replace');
```
--------------------------------
### barba.history.add(url, trigger, action)
Source: https://barba.js.org/docs/advanced/utils
Push or replace a new state in the browser history, see history strategy.
```APIDOC
## barba.history.add(url, trigger, action)
### Description
Push or replace a new state in the browser history. See history strategy for more details.
### Parameters
- **url** (string) - The URL to add to the history.
- **trigger** (Trigger) - The trigger for the history entry.
- **action** (HistoryAction) - Optional. The action to perform (push or replace).
### Usage
```javascript
barba.history.add('https://example.com/new-page', 'click', 'push')
```
```
--------------------------------
### barba.url.parse(url)
Source: https://barba.js.org/docs/advanced/utils
Parse the given URL and retrieve a IUrlBase object.
```APIDOC
## barba.url.parse(url)
### Description
Parse the given URL and retrieve a `IUrlBase` object.
### Parameters
- **url** (string) - The URL to parse.
### Usage
```javascript
const parsedUrl = barba.url.parse('https://example.com/path?query=value#hash')
```
```
--------------------------------
### Combine Multiple Transition Rules
Source: https://barba.js.org/docs/advanced/transitions
Define a transition that triggers based on a combination of custom classes, route names, and namespaces. Barba prioritizes these rules to determine which transition to play.
```javascript
barba.init({
transitions: [{
name: 'custom-transition',
from: {
// define a custom rule based on the trigger class
custom: ({ trigger }) => {
return trigger.classList && trigger.classList.contains('use-custom-transition');
},
// define rule based on multiple route names
route: [
'index',
'product'
]
},
to: {
// define rule based on multiple namespaces
namespace: [
'home',
'item'
]
}
}]
});
```
--------------------------------
### Configure Cache Ignore Patterns
Source: https://barba.js.org/docs/advanced/strategies
Use `cacheIgnore` to specify routes that should not be cached. This is useful for pages with dynamic content or specific user interactions.
```javascript
barba.init({
cacheIgnore: ['/contact/', '/:category/post?']
});
```
--------------------------------
### preventRunning Option
Source: https://barba.js.org/docs/advanced/strategies
Configure Barba.js to prevent page 'force reloads' during active transitions, ensuring a smoother user experience for long transitions.
```APIDOC
## preventRunning Option
### Description
Tells Barba to **prevent page “force reload”** when the user clicks on an eligible link during a transition is running. This option is useful if you don’t want your users to break running transitions, especially if they are long.
### Configuration
```javascript
barba.init({
preventRunning: true
});
```
### Usage
This option is set during the `barba.init()` configuration. When set to `true`, Barba will automatically prevent navigation if a transition is currently in progress.
```
--------------------------------
### barba.force(href)
Source: https://barba.js.org/docs/advanced/utils
Force Barba to redirect to a specific URL without playing your transitions, equivalent to location.href change.
```APIDOC
## barba.force(href)
### Description
Force Barba to redirect to a specific URL without playing your transitions, equivalent to `location.href` change.
### Parameters
- **href** (string) - The URL to redirect to.
### Usage
```javascript
barba.force('https://example.com')
```
```
--------------------------------
### Store Custom Data in History
Source: https://barba.js.org/docs/advanced/strategies
Utilize `barba.history.store` to save custom data associated with the current navigation state. This data can be accessed later from `barba.history.previous.data` after a transition.
```javascript
barba.history.store({
id: 2547,
random: Math.random(),
href: window.location.href,
});
```
--------------------------------
### Handle Request Errors with Barba.js
Source: https://barba.js.org/docs/advanced/recipes
Catch request errors, such as 404 responses, and implement custom navigation logic. Returning `false` prevents Barba from forcing the navigation.
```javascript
barba.init({
requestError: (trigger, action, url, response) => {
// go to a custom 404 page if server respond with a 404 response status
if (action === 'click' && response.status && response.status === 404) {
barba.go('/404');
}
// prevent Barba from redirecting the user to the requested URL
// this is equivalent to e.preventDefault() in this context
return false;
},
});
```
--------------------------------
### history.add Method
Source: https://barba.js.org/docs/advanced/strategies
Programmatically add or replace history entries to keep the browser history synchronized with user interactions.
```APIDOC
#### `history.add`
This method brings the ability to **programmatically push or replace history entries** to easily keep the history up to date in your application based on user interaction.
### Arguments
- `url` (String): URL of the page to push/replace in the history.
- `trigger` (Object | String): The element that triggers the history action or a string 'barba' for programmatic trigger.
- `action` (String): `'push'` (default) or `'replace'.
### Usage
```javascript
// push a new entry in the history
history.add('push.html', 'barba', 'push');
// replace a history entry
history.add('replace.html', 'barba', 'replace');
```
> See `History` utility API documentation to learn more.
```
--------------------------------
### Cache Configuration
Source: https://barba.js.org/docs/advanced/strategies
Configure Barba.js's caching mechanism to control which pages are stored and whether the first page should be cached. This reduces bandwidth usage and server load.
```APIDOC
## Cache Configuration
### `cacheIgnore`
Allows Barba to **cache your pages**. Saving pages in the cache results in **less bandwidth usage** and **less server-side load**.
Value | Description
---|---
`false` _(default)_ | Cache all
`true` | Ignore all
`String | String[]` | Ignore route pattern(s)
**Example:**
```javascript
barba.init({
cacheIgnore: ['/contact/', '/:category/post?']
});
```
> Cache lifetime is **restricted to Barba instance** and will be cleared when leaving the site.
### `cacheFirstPage`
Allows Barba to **cache the first rendered page**. This can be useful in some situations, but often it's better not to cache the first page as it may be modified by other scripts.
Value | Description
---|---
`false` _(default)_ | Do not cache the first rendered page
`true` | Cache the first rendered page
**Example:**
```javascript
barba.init({
cacheFirstPage: true
});
```
```
--------------------------------
### requestError Callback
Source: https://barba.js.org/docs/advanced/recipes
Allows you to catch and handle request errors during page transitions. Returning `false` prevents Barba from forcing navigation.
```APIDOC
## requestError
### Description
Allows you to **catch request errors**. If this function returns `false`, wrong links will not be “force” triggered.
### Parameters
#### Argument `trigger`
- `HTMLElement` 'barba': The clicked/hovered HTMLElement
- `String` 'back': Programmatic navigation
- `String` 'forward': Browser backward/forward button
#### Argument `action`
- `String` 'enter': Page was reached **on mouseover** regarding the `prefetchIgnore` strategy
- `String` 'click': Page was reached with a **user click**
- `String` 'prefetch': Page was reached with a **programmatic prefetch** or the @barba/prefetch plugin
#### Argument `url`
- `String`: Requested URL
#### Argument `response`
- `Object`: Fetch error with `message` or response with `status`, `statusText`, etc.
### Request Example
```javascript
barba.init({
requestError: (trigger, action, url, response) => {
// go to a custom 404 page if server respond with a 404 response status
if (action === 'click' && response.status && response.status === 404) {
barba.go('/404');
}
// prevent Barba from redirecting the user to the requested URL
// this is equivalent to e.preventDefault() in this context
return false;
},
});
```
### Note
If you use `barba.go()` directive without returning `false`, you will be redirected to the requested URL because Barba uses `barba.force()` to reach the page.
```
--------------------------------
### Accessing Data Properties in Hooks
Source: https://barba.js.org/docs/advanced/hooks
Illustrates how to access properties of the `data` object within hooks, such as `data.current.url.href`, to retrieve information about the current page during a transition.
```javascript
barba.init({
transitions: [{
leave(data) {
// get the current URL
let href = data.current.url.href;
}
}]
});
```
--------------------------------
### CSS for Fade and Slide Transitions
Source: https://barba.js.org/docs/plugins/css
Defines the CSS transitions for 'fade' and 'slide' effects, including opacity and transform properties. These styles are applied based on the transition names defined in Barba.js.
```css
.fade-leave-active,
.fade-enter-active,
.slide-leave-active,
.slide-enter-active {
transition: opacity 450ms ease, transform 650ms ease-in-out;
}
.fade-leave,
.fade-enter-to {
opacity: 1;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
.slide-leave,
.slide-enter-to {
transform: translateX(0);
}
.slide-enter,
.slide-leave-to {
transform: translateX(100%);
}
```
--------------------------------
### Barba.js Default HTML Structure
Source: https://barba.js.org/docs/getstarted/markup
This is the default HTML structure recommended for Barba.js. The `data-barba="wrapper"` attribute defines the main Barba section, and `data-barba="container"` marks the content that will be updated during transitions. The `data-barba-namespace` attribute is used to identify individual pages.
```html
```
--------------------------------
### Initialize and Update Locomotive Scroll with Barba.js Hooks
Source: https://barba.js.org/docs/advanced/third-party
Initialize Locomotive Scroll and use Barba.js hooks to update the scroll instance after page transitions. This ensures smooth scrolling is maintained across different pages.
```javascript
// init LocomotiveScroll on page load
let scroll = new LocomotiveScroll({
el: container.querySelector('[data-scroll-container]'),
smooth: true
});
// update the scroll after entering a page
barba.hooks.after(() => {
scroll.update();
});
```
--------------------------------
### Generated CSS Classes with Custom Prefix
Source: https://barba.js.org/docs/plugins/css
When a transition name is provided, Barba CSS uses it as a prefix for 'once' hook classes. Default prefixes are used for 'leave' and 'enter' hooks unless also specified.
```css
/* transition name is used as prefix for `once` hook */
.hello-once {}
.hello-once-active {}
.hello-once-to {}
/* default prefix is used for `leave` and `enter` hooks */
.barba-leave {}
.barba-leave-active {}
.barba-leave-to {}
.barba-enter {}
.barba-enter-active {}
.barba-enter-to {}
```
--------------------------------
### Prevent Interrupted Transitions with preventRunning
Source: https://barba.js.org/docs/advanced/strategies
Set `preventRunning` to `true` to stop users from triggering new page loads during an active transition. This is useful for long transitions to prevent user frustration.
```javascript
barba.init({
preventRunning: true
});
```
--------------------------------
### BarbaJS Legacy About Page HTML
Source: https://barba.js.org/docs/getstarted/legacy
This HTML file represents another page in the website. It includes the BarbaJS wrapper and container but does not require the BarbaJS or GSAP scripts as they are loaded on the main page and not reloaded between transitions.
```html
About — BarbaJS legacy example
About
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Go back home
```
--------------------------------
### Animate with GSAP and ScrollTrigger
Source: https://barba.js.org/docs/advanced/third-party
Integrate GSAP and ScrollTrigger for animations within Barba.js views. Ensure ScrollTrigger instances are killed on page leave to prevent overlaps.
```html
```
```javascript
import barba from '@barba/core';
import gsap from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';
// global instance
const instance;
// init barba
barba.init({
views: [{
namespace: 'home',
beforeEnter() {
// get the element you want to animate
const element = document.querySelector('.scrolltrigger-element');
// create a basic timeline
const timeline = gsap.to(element, {
x: 500,
duration: 2
});
// create instance each time you enter the page
instance = ScrollTrigger.create({
animation: timeline,
trigger: element,
start: 'center 75%',
markers: true
});
},
afterLeave() {
// kill instance each time you leave the page
instance.kill();
},
}]
});
```
--------------------------------
### Locomotive Scroll Initialization with Barba
Source: https://barba.js.org/docs/advanced/third-party
Initialize Locomotive Scroll and re-initialize it after each Barba transition to ensure correct DOM element detection. Use the data-scroll-container attribute on the main scrollable section.
```javascript
const scroll = new LocomotiveScroll();
barba.hooks.after(() => {
scroll.init();
});
barba.init();
```
--------------------------------
### barba.history Object
Source: https://barba.js.org/docs/advanced/strategies
Access and manage navigation information stored by Barba.js, including previous and current page details.
```APIDOC
## History
### `barba.history`
While browsing the website, Barba stores useful navigation informations into the `history` property. You can **access those informations at any time** in your application.
#### `history.previous|current`
The most useful are the `previous` and `current` history attributes. It allows you to access the page `namespace`, the window `scroll` position and the page `url`. They both shares the same set of properties:
- `ns` (String): Namespace of the page.
- `scroll` (Object): `x` / `y` positions of the scroll.
- `url` (String): URL of the history position.
- `data` (Object): Custom data for the current page.
> Note: `barba.history.previous` is `null` when the application starts.
```
--------------------------------
### Replace Browser History Entry with Barba.js
Source: https://barba.js.org/docs/advanced/strategies
Use `data-barba-history="replace"` to update the current browser history entry without pushing a new one. This is useful for scenarios where you want to modify the URL or state without creating a new history point.
```html
black
white
```
--------------------------------
### barba.destroy()
Source: https://barba.js.org/docs/advanced/utils
Destroy the Barba instance and properly remove EventListeners on eligible links.
```APIDOC
## barba.destroy()
### Description
Destroy the Barba instance and properly remove `EventListener` on eligible links.
### Usage
```javascript
barba.destroy()
```
```
--------------------------------
### Store and Restore Scroll Position with Barba.js Hooks
Source: https://barba.js.org/docs/advanced/recipes
Store the current scroll position using Barba.js `leave` hook and then restore it manually. This is useful when `history.scrollRestoration` is set to 'manual'.
```javascript
let scrollX = 0
let scrollY = 0
barba.hooks.leave(() => {
scrollX = barba.history.current.scroll.x;
scrollY = barba.history.current.scroll.y;
});
// then later in the code...
window.scrollTo(scrollX, scrollY);
```
--------------------------------
### Custom Link Prevention with prevent
Source: https://barba.js.org/docs/advanced/strategies
Define a custom function for the `prevent` option to conditionally disable Barba for specific links. The function receives the clicked element, event, and href, returning `true` to prevent Barba.
```javascript
barba.init({
// define a custom function that will prevent Barba
// from working on links that contains a `prevent` CSS class
prevent: ({ el }) => el.classList && el.classList.contains('prevent')
});
```