LoadingBar.js: Adding a YouTube-Like Loading Bar to Your Website

Adding a YouTube-Like Loading Bar to Your Website with LoadingBar.js

YouTube have recently added a red loading bar at the top of the page to indicate that the next page is loading. You may wonder why they didn’t rely on the browser’s loading bar. That’s because the next page is being loaded with AJAX which doesn’t trigger the normal page load mechanism. That’s why the browser didn’t pick it up. As some of you may know, loading the entire content via AJAX can make your website load faster than the normal way.

That’s because all the static content is left unchanged, and only the dynamic content is being loaded, that way you don’t have to keep asking the server for static content that will never change over and over creating an overload.

YouTube-Like Loading Bar

[tut demo=”http://onextrapixel.com/examples/youtube-like-ajax-loading-bar/” download=”http://onextrapixel.com/examples/youtube-like-ajax-loading-bar/youtube-like-ajax-loading-bar.zip”]

Create a YouTube-Like Loading Bar for Web

As mentioned in a blog post by Dmitry Fadeyev over at UsabilityPost, many developers are integrating this UI pattern to their websites more and more. Today I decided to build a jQuery plugin that will let you add a loading bar to any AJAX links on your website. Let me show you how it works.

Basic Usage

Loading Bar is a jQuery plugin I built to help you add a loading bar to all your AJAX links with no hassle. The script is basically a wrapper of the jQuery AJAX function with a few twists. To add this to your website, simply include the latest jQuery library together with the jquery.loadingbar.js and loadingbar.css into your document’s <head> and call the function as shown below:

HTML Markup

<a href="<<URL>>" class="ajax-call">..</a>
<div id="loadingbar-frame"></div>

For the HTML all we need is the AJAX link and the container that you wish the result to appear in. Make sure to replace the <<URL>> with your AJAX url.

JavaScript

$(".ajax-call").loadingbar({
  target: "#loadingbar-frame",
  replaceURL: false,
  direction: "right",

  /* Default Ajax Parameters.  */
  async: true, 
  complete: function(xhr, text) {},
  cache: true,
  error: function(xhr, text, e) {},
  global: true,
  headers: {},
  statusCode: {},
  success: function(data, text, xhr) {},
  dataType: "html",
  done: function(data) {}
});

For the JS part, simply call a .loadingbar on a jQuery selector you wish to initiate the loading bar while retrieving AJAX results. The script will use the href attribute for the AJAX call and it will automatically place the results in the container with the ID loadingbar-frame. Here are the explanations of what these parameters do:

  • Target: You can change the container by changing the target parameter of the function call to your preferred selector.
  • replaceURL will allow you to visibly change the URL of your browser to the href attribute of the link that was clicked. This is extremely useful when you are using this script for your pagination where you want the URL of your browser to reflect the content displaying. The default value is false.
  • Direction will allow you to control the direction in which the bar will progress. The default value is “right” which is the same as you see on YouTube.

Everything below “Default Ajax Parameters” is the same as the default jQuery AJAX call. You can override it accordingly. For more info, refer to the jQuery.ajax document available here.

For Further Customization

Sometimes, you may want to have each link perform differently, for example you may want one link to perform a GET request and another to perform a POST request. You can assign each individual link with its own settings by using the available markup as shown below:

HTML Markup

<a href="http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?&tags=everest&tagmode=any&format=json" 
data-datatype="json" data-type="GET" data-target="#frame">Click Me</a>

You can assign the dataType and type of the AJAX call by simply adding the data-datatype and data-type attributes respectively as shown above. You can also assign a different container by defining your preferred jQuery selector in the data-target attribute.

For the example above, I used the Flickr API which allows me to get pictures tagged “everest” from Flickr. I had also specified that I want the result to be in json format, for which I then set the dataType of the AJAX call to be json, data-type to be GET and assign my own container #frame which will hold all the results returned from the API.

CSS Customization

You can easily change the feel and aesthetic of the bar by using CSS. To change color, go into loadingbar.css and change these values:

#loadingbar {
	background: YOUR COLOR;
}

#loadingbar dd, #loadingbar dt {
  -moz-box-shadow: YOUR COLOR 1px 0 6px 1px;
  -ms-box-shadow: YOUR COLOR 1px 0 6px 1px;
  -webkit-box-shadow: YOUR COLOR 1px 0 6px 1px;
  box-shadow: YOUR COLOR 1px 0 6px 1px;
}

[tut demo=”http://onextrapixel.com/examples/youtube-like-ajax-loading-bar/” download=”http://onextrapixel.com/examples/youtube-like-ajax-loading-bar/youtube-like-ajax-loading-bar.zip”]

You’re Done!

And that’s it. You will now have an awesome loading bar for all your AJAX calls. I hope you enjoy this tutorial and my plugin. If you have any questions, feature requests or suggestions, please let me know in the comments below.

Pete is a Bangkok entrepreneur, a UI designer, and a Ruby on Rails developer. He is the founder of Bucketlistly.com and MyColorscreen.com. Other than his businesses, design and development, he also loves astronomy, indie music, and blogging.

Comments

    • Lay,
    • September 2, 2013
    / Reply

    Great!

  1. / Reply

    Nice. One comment, GET and POST are not data types at all, they are HTTP methods. I suggest you to change the attribute name to something more accurate in terms of the semantics, like http-method, for instance.

      • richdadgiang,
      • October 22, 2013
      / Reply

      Hello, Could you please help me install this plugin? My website is a wordpress website. But i don’t know how to install it. Please help me step by step or give me a video tutorial. Thanks

    • ADOLF WITZELING,
    • September 2, 2013
    / Reply

    I read this article with interest. Nice tut!

    • Active Web Group,
    • September 3, 2013
    / Reply

    Hi, I highly suggest you make your demos “Pinterest Friendly” – the only image it is grabbing off the page is very tiny, blurry, and irrelevant.

    • Michael Shen,
    • September 11, 2013
    / Reply

    Nice

    • Anthony,
    • October 7, 2013
    / Reply

    Very slick! Nice!

    • Giang Nguyen,
    • October 20, 2013
    / Reply

    Hello, Could you please help me install this plugin? My website is a wordpress website. But i don’t know how to install it. Please help me step by step or give me a video tutorial. Thanks

    • Juan Vilar,
    • October 23, 2013
    / Reply

    ¡I detected a small bug in your code!!!

    lets say I have a listing of several links with the same class but different HREFs



    …..and so on

    when you do

    $(‘.foo’).loadingbar( …..) ;

    no matter how many links, they will always point to HREF of the FIRST URL, rendering php dynamic URL targeting useless with this AWESOME ASSKICKING plugin.

    this is caused because on your script
    —————————
    $.fn.loadingbar = function(options){
    var settings = $.extend({}, defaults, options),
    el = $(this),
    href = el.attr(“href”),
    target = (el.data(“target”)) ? el.data(“target”) : settings.target,
    type = (el.data(“type”)) ? el.data(“type”) : settings.type,
    datatype = (el.data(“datatype”)) ? el.data(“datatype”) : settings.dataType

    return this.each(function(){
    el.click(function (){
    $.ajax({
    type: type,
    url: href,
    async: settings.async,
    complete: settings.complete,
    cache: settings.cache,
    error: settings.error,
    global: settings.global,
    headers: settings.headers,
    statusCode: settings.statusCode,

    …. (and so on) …..

    ——————–

    you create the “settings” variable that only grabs the parameters of the first URL rather than the URL of each one…..

    the solution is very simple, just move the declaration of the settings variable declaration INSIDE the each selector , this way
    ——————————-
    return this.each(function(){
    var settings = $.extend({}, defaults, options),
    el = $(this),
    href = el.attr(“href”),
    target = (el.data(“target”)) ? el.data(“target”) : settings.target,
    type = (el.data(“type”)) ? el.data(“type”) : settings.type,
    datatype = (el.data(“datatype”)) ? el.data(“datatype”) : settings.dataType

    el.click(function (){
    $.ajax({
    type: type,
    url: href,
    async: settings.async,
    complete: settings.complete,
    cache: settings.cache,
    error: settings.error,
    global: settings.global,
    headers: settings.headers,

    (and so on) ….
    —————

    it worked like a charm and now my links show up and work properly

    thanks for this plugin!!!

      • Эрдэнэбилэг Батбаатар,
      • January 26, 2014
      / Reply

      You can use any id

      <a href="<>” class=”ajax-call” id=”ajax-call-1″>..

  2. / Reply

    How to make automatic loading page, without press button?
    thank you…..

      • Bruno Rodrigues,
      • May 8, 2015
      / Reply

      To do this, you have to user “trigger”. Se below:

      // Show Loading Bar
      $(“.ajax-call”).loadingbar({
      target: “#”,
      replaceURL: false,
      direction: “right”,

      /* Default Ajax Parameters. */
      async: true,
      complete: function(xhr, text) {},
      cache: true,
      error: function(xhr, text, e) {},
      global: true,
      headers: {},
      statusCode: {},

      success: function(data, text, xhr) {},

      dataType: “html”,
      done: function(data) {}
      });

      //Automatic when the page load
      $(‘.ajax-call’).trigger(‘click’);

      });

  3. / Reply

    Thanks :)

  4. / Reply

    Oh this is sweet. I would love a WordPress integration tutorial. Otherwise, AWESOME ! Thanks :)

  5. / Reply

    Cool one Pete. :-)

    • Jiego Cordoviz,
    • December 18, 2013
    / Reply

    Great man, but looking at it, it only works for tags’ href? What about buttons or any other elements? Not everyone uses tags to invoke an Ajax call.

      • zigzaggin,
      • January 3, 2014
      / Reply

      This is easily remedied. On line 43 of the source change from:

      href = el.attr(“href”)

      to

      href = (el.attr(“href”) != “”) ? el.attr(“href”) : el.data(“href”)

      This will then allow you to use a data-href attribute on any element to treat it similar to a link.

  6. / Reply

    Hi, First of all thanks for nice feature and smooth demo,
    How i can do for a button click i tried by $(this).loadingbar({ // my code }); but am not able to do, below sample code what i do for my button click ajax call

    $(“#btn_AddData”).on(‘click’, function () {
    var mydatastring=”id=10^productName=DummyName”;
    $.ajax({
    type: “POST”,
    url: “Ajax_function/myfunction.asmx/addNewRecordr,
    data: “{ ‘prefix’: ‘” + mydatastring + “‘}”,
    contentType: “application/json; charset=utf-8”,
    dataType: “json”,
    success: OnSuccess,
    error: OnErrorCall
    });

    function OnSuccess(response) { alert(“Record Added Sucessfully.”); }

    function OnErrorCall() { alert(“Error Occurs!”); }
    });

    • Howard Tan,
    • June 16, 2014
    / Reply

    very cool!!

    • Zacharia Samuel Grierson,
    • December 11, 2014
    / Reply

    Could this be used when you load the page, like a softloader so when the page loads it runs up the top.
    No need for the AJAX call.

    • Michael Jarn Gotostos,
    • June 5, 2015
    / Reply

    how do i send a data using tour plugin?

    here is my code..

    $(“#click”).loadingbar({

    type: “POST”,

    url: “sql.php”,

    data: {“value”:$(‘#hiddenID’).attr(‘value’)},

    done: function(data){

    if(!isFinite(data)){

    //alert(data);

    $(‘#hiddenID’).remove();

    $(‘#mess’).append(data).show();

    //$(‘.preloader’).hide();

    } else {

    //alert(data);

    $(‘#click’).remove();

    $(‘#holder’).append(‘No more newsfeeds to post’).show();

    }

    },

    cache: false,

    async: true

    });

    everytime i click the link my PHP file cant find the $_POST value. please help

  7. / Reply

    Demo is working but link do not update on address bar like YouTube. Please update script. When we click on each **a href** this should load and also update same address in address bar.

Leave a Reply

Your email address will not be published. Required fields are marked *

Deals