share

How to Add Barba.js Page Transitions to Your Website

August 3, 2018 | Dev / Code, Graphics, Software

Barba Javascript page transition tutorial

Page transitions and animations for a better user experience

Barba.js is a Javascript library that uses PJAX (Pushstate Ajax). Before we explain Barba and how you can use it to enhance your website, let’s look at a bit of history behind Ajax.

What websites use Barba.js for page transitions?

Barba JS has become one of the premier go-to solutions for developers looking to add a sexy page transition to their website. Some websites using Barba to power their transitions include:

Here are a few demos from Barba’s website:

Website page transitions
Website page barba js
Website page barba js

Usually, when one thinks of Internet Explorer, they think of unexpected crashes, errors, security flaws, slow performance and lack of compatibility with modern day internet. But back in the mid-90’s, this was not the case.

In that time, Internet Explorer was on the bleeding edge of new CSS implementations and was the standard that all other browser sought after.

In those days, Internet Explorer was blazingly fast, compatible with any CSS properties someone could throw at it and less accident prone in general than any other browser on the market.

This leads me to my next point which is that in 1999 Microsoft released Internet Explorer 5.X which was the first browser to support the XMLHttpRequest which is the foundation upon which modern day single-page applications are built. Nowadays we call it AJAX which is a term coined by someone other than Microsoft.

Ajax is a means by which the client can send additional requests to the server for resources that weren’t originally included in the initial page load.

More and more websites are slowly beginning to use AJAX to create single-page applications as opposed to the traditional static ones.

The difference between a static HTML website and a single-page application is that when the user clicks on a link in the same domain, instead of reloading all of the resources such as CSS, HTML, Javascript, and re-rendering it, the browser will instead request only the resources that are different from the page that the user is currently on. This helps in a few ways:

  1. Only resources that are different from the current page as opposed to the destination are loaded thus decreasing load time.
  2. Instead of a blank screen, the user can see possibly one of your awesome page transitions which decreases bounce rate.
  3. You have more control over what your application does overall.

How to integrate Barba.js into your website

In a very simple form, you can see ajax by simply opening up the developer console and typing


$('.elementOnCurrentPage').load('/path/to/destination/page .elementOnDestinationPage');

What this will do is load the content of the element that’s on the destination page into the container specified by ‘.elementOnCurrentPage’. But there are a lot of other things to consider

  1. How do I ensure Google Analytics is updated with every new page view?
  2. Click events attached to dynamic content will be destroyed when the page reloads.
  3. How do I inhibit the anchor’s default behavior?

With great power comes great responsibility and converting your standard website into a web application will take a bit of work but the pay off is great because you’ll be one of the 5% (as of this writing) to be using ajax.

First, go on over to Barbajs.org and grab a copy of barba.js or here’s a link to include it in the footer of your website. It’s important that the DOM is ready when Barba executes.

Now you’ll want to create another file called barbaMain.js and include it after Barba, in the footer. This is where we’ll put our custom page transitions and functionality. Let’s create a simple fade out / fade in transition between pages. Takes this snippet and add it to barbaMain.js:


Barba.Pjax.start();
var lastElementClicked;
Barba.Dispatcher.on('linkClicked', function(el) {
  lastElementClicked = el;
});
var FadeTransition = Barba.BaseTransition.extend({
  start: function() {
    /**
     * This function is automatically called as soon the Transition starts
     * this.newContainerLoading is a Promise for the loading of the new container
     * (Barba.js also comes with an handy Promise polyfill!)
     */

    // As soon the loading is finished and the old page is faded out, let's fade the new page
    Promise
      .all([this.newContainerLoading, this.fadeOut()])
      .then(this.fadeIn.bind(this));
  },

  fadeOut: function() {
    /**
     * this.oldContainer is the HTMLElement of the old Container
     */

    return $(this.oldContainer).animate({
        opacity: 0
      }, 400, function() {

      }).promise(),
  },

  fadeIn: function() {
    /**
     * this.newContainer is the HTMLElement of the new Container
     * At this stage newContainer is on the DOM (inside our #barba-container and with visibility: hidden)
     * Please note, newContainer is available just after newContainerLoading is resolved!
     */

    var _this = this;
    var $el = $(this.newContainer);

    $(this.oldContainer).hide();

    $el.css({
      visibility: 'visible',
      opacity: 0
    });

    $el.animate({
      opacity: 1
    }, 400, function() {

      /**
       * Do not forget to call .done() as soon your transition is finished!
       * .done() will automatically remove from the DOM the old Container
       */
      _this.done();

    });
  }
});
/**
 * Next step, you have to tell Barba to use the new Transition
 */

Barba.Pjax.getTransition = function() {
  /**
   * Here you can use your own logic!
   * For example you can use different Transition based on the current page or link...
   */
    return FadeTransition;
};

As an added bonus, add this


Barba.Prefetch.init();

Just after Barba.Pjax.start(); and when the user hovers the link, the next page will begin loading before they even click the anchor! This greatly reduces page load time. Finally, the last thing you’ll want to do is encase the content of your pages with this:

<pre>
<main id="barba-wrapper">
    <div class="barba-container" data-namespace="grid">
    </div>
</main>
</pre>

Everything that’s inside “barba-container” will be counted as the “oldContainer” and respectively, everything in between the barba-container of the destination page will be counted as the “newContainer”. If your header stays the same between pages, you can put this just below your nav menu just outside of the closing tag of your header. For example in WordPress, you could put the opening tags at the bottom of the header.php and the closing tags at the top of the footer.php. If you’d like to make a different transition. Try putting an element in between “barba-wrapper” and “barba-container” by which I mean in between the two opening tags. Anything in between these two tags will be kept so you can use it to add any kind of graphics you might want.

Additionally, you can use Google new “Universal Analytics” code as you normally would and page views are automatically sent when the user clicks a link.

One of the reasons this is great is because you can have several times more control over the resources that your website loads by creating custom logic. For instance, you can add the following after Barba.Pjax.start();


Barba.Dispatcher.on('initStateChange', function () {
    if (window.location.href.indexOf('contact') != -1) {
        que_script('scripts.js');
    });
});
function que_script(scriptSrc) {
  $('body script').each(function() {
    if ($(this).attr('src') == scriptSrc) {
      $(this).remove();
    }
  });
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.src = scriptSrc;
  document.getElementsByTagName("footer")[0].appendChild(newScript);
}

This way you can choose what scripts are loaded on what pages, thus decreasing load time even further.

Share This Article

related articles

some sponsors

Haven’t signed up for our newsletter?

Be a lot cooler if ya did


We send nothing but the good shit. Once a week. That’s it.

Be a lot cooler if ya did

UX and Web Design blog articles
Web Development & Coding blog articles
Lifestyle blog articles
Branding blog articles
Graphic design blog articles
Software reviews blog articles

Time's up, let's do this

Stay up-to-date with all of the design and creative news, resources, and inspiration by signing up for the CreativesFeed newsletter!