User guide

barba.js [v2]

stability-beta CircleCI Coverage Status Commitizen friendly Conventional Commits License Slack channel

Barba.js is a small (7kb minified and compressed) and easy-to-use library that helps you creating fluid and smooth transitions between your website’s pages.

It helps reducing the delay between your pages, minimizing browser HTTP requests and enhancing your user’s web experience.

Notice: This guide assumes intermediate level knowledge of HTML, CSS, and JavaScript. It is worth mentioning that all the code examples use ES6+ syntax.
If you are not comfortable with, we encourage you to grasp the basics then come back.
In case of emergency, check this “legacy” code example.

Install

Using npm:

npm install @barba/core

or using yarn:

yarn add @barba/core

or using a CDN:

<script src="https://unpkg.com/@barba/core"></script>

Getting started

See @barba/core for more details…

import barba from '@barba/core'; // Or nothing if loaded via the browser

// Basic default transition, with no rules and minimal hooks…
barba.init({
  transitions: [
    {
      leave({ current, next, trigger }) {
        // Do something with `current.container` for your leave transition
        // then return a promise or use `this.async()`
      },
      enter({ current, next, trigger }) {
        // Do something with `next.container` for your enter transition
        // then return a promise or use `this.async()`
      },
    },
  ],
});

// Dummy example to illustrate rules and hooks…
barba.init({
  transitions: [
    {
      name: 'dummy transitions',
      // Apply only when leaving `[data-barba-namespace="home"]`.
      namespace: 'home',
      // Apply only when transitioning to `[data-barba-namespace="products | contact"]`.
      to: {
        namespace: ['products', 'contact'],
      },
      // Apply only if clicked link contains `.cta`.
      custom: ({ current, next, trigger }) =>
        trigger.classList && trigger.classList.contains('cta'),
      // Do leave and enter concurrently.
      sync: true,
      // Available hooks…
      beforeAppear() {},
      appear() {},
      afterAppear() {},
      beforeLeave() {},
      leave() {},
      afterLeave() {},
      beforeEnter() {},
      enter() {},
      afterEnter() {},
    },
  ],
});

Browser support

Barba.js can be viewed as a progressive enhancement. Main “modern features” used are:

@barba/prefetch also uses IntersectionObserver

Cross-browser support is as follows:

You can use polyfill.io:

<script
  crossorigin="anonymous"
  src="https://polyfill.io/v3/polyfill.min.js?features=default%2CArray.prototype.find%2CIntersectionObserver"
></script>

or implement your own solution (es6-promise and Core.js or es6-shim, …).