Skip to content

GerHobbelt/nprogress

 
 

Repository files navigation

NProgress

Slim progress bars for Ajax'y applications. Inspired by Google, YouTube, and Medium.

This version has the ability to display a progress message next to the spinner (top right corner). All relevant functions (start(), set(), inc(), trickle()) have an additional property (msg) that can be any (HTML) string. You will definitely want to play with the CSS to make it look good on your site, but it looks just great on white background (has a glow to the text).

This is also a pure JS version of rsantacruz's NProgress, which comes form mparramont's fork (see link above).

You do NOT need jQuery or any other JS library for this version.

Installation

Add nprogress.js and nprogress.css to your project.

<script src='nprogress.js'></script>
<link rel='stylesheet' href='nprogress.css'/>

NProgress is available via bower and npm and spm.

$ bower install --save nprogress
$ npm install --save nprogress

Basic usage

Simply call start() and done() to control the progress bar.

NProgress.start();  // or NProgress.start("Uploading data");
NProgress.done();

Turbolinks (version 5+)

Ensure you're using Turbolinks 5+, and use this: (explained here)

$(document).on('turbolinks:click', function() {
  NProgress.start();
});
$(document).on('turbolinks:render', function() {
  NProgress.done();
  NProgress.remove();
});

Turbolinks (version 3 and below)

Ensure you're using Turbolinks 1.3.0+, and use this: (explained here)

$(document).on('page:fetch',   function() { NProgress.start(); });
$(document).on('page:change',  function() { NProgress.done(); });
$(document).on('page:restore', function() { NProgress.remove(); });

Pjax

Try this: (explained here)

$(document).on('pjax:start', function() { NProgress.start(); });
$(document).on('pjax:end',   function() { NProgress.done();  });

Ideas

  • Add progress to your Ajax calls! Bind it to the jQuery ajaxStart and ajaxStop events.

  • Make a fancy loading bar even without Turbolinks/Pjax! Bind it to $(document).ready and $(window).load.

Advanced usage

Percentages: To set a progress percentage, call .set(n), where n is a number between 0..1.

NProgress.set(0.0);     // Sorta same as .start()
NProgress.set(0.4, "Uploading form data");
NProgress.set(1.0);     // Sorta same as .done()

Incrementing: To increment the progress bar, just use .inc(). This increments it with a random amount. This will never get to 100%: use it for every image load (or similar).

NProgress.inc();
NProgress.inc("default", "A little more");
NProgress.inc(0.2, "20% more");

If you want to increment by a specific value, you can pass that as a parameter:

NProgress.inc(0.2);    // This will get the current status value and adds 0.2 until status is 0.994

Force-done: By passing true to done(), it will show the progress bar even if it's not being shown. (The default behavior is that .done() will not do anything if .start() isn't called)

NProgress.done(true);

Get the status value: To get the status value, use .status. The status value is null when the progress bar is not being shown, otherwise the status value will be the last perunage set via .set() (and .inc())

Configuration

minimum

Changes the minimum percentage used upon starting. (default: 0.08)

NProgress.configure({ minimum: 0.1 });

template

You can change the markup using template. To keep the progress bar working, keep an element with role='bar' in there. See the default template for reference.

NProgress.configure({
  template: "<div class='....'>...</div>"
});

easing and speed

Adjust animation settings using easing (a CSS easing string) and speed (in ms). (default: ease and 200)

NProgress.configure({ easing: 'ease', speed: 500 });

trickle

Turn off the automatic incrementing behavior by setting this to false. (default: true)

NProgress.configure({ trickle: false });

trickleRate and trickleSpeed

You can adjust the trickleRate (how much to increase per trickle) and trickleSpeed (how often to trickle, in ms).

NProgress.configure({ trickleRate: 0.01, trickleSpeed: 200 });

showSpinner

Turn off loading spinner by setting it to false. (default: true)

NProgress.configure({ showSpinner: false });

parent

Specify this to change the parent container. (default: body)

NProgress.configure({ parent: '#container' });

direction : leftToRightIncreased, leftToRightReduced, rightToLeftIncreased, rightToLeftReduced.

change the direction of progress bar's animation.(default: leftToRightIncreased)

NProgress.configure({ direction: 'leftToRightReduced' });

forceRedraw

Force redraw in the browser when the progress changes. Can have performance implications. (default: false)

NProgress.configure({ forceRedraw: 'true' });

removeFromDOM

Remove the component from the DOM when done, re-add when needed. This can have performance implications on complex apps in IE 11 as style calculations are slow. (default: false)

NProgress.configure({ removeFromDOM: 'true' });

Customization

Just edit variables.less or nprogress.less (which are used to produce nprogress.css) to your liking. Tip: you probably only want to find and replace occurrences of #29d.

The included CSS file is pretty minimal... in fact, feel free to scrap it and make your own!

You can regenerate the CSS file using the shell script (after having installed NPM and ran npm install):

./build.sh

Resources

Support

Bugs and requests: submit them through the project's issues tracker.
Issues

Questions: ask them at StackOverflow with the tag nprogress.
StackOverflow

Chat: join us at gitter.im.
![Chat](http://img.shields.io/badge/gitter-rstacruz / nprogress-brightgreen.svg)

Thanks

NProgress © 2013-2016, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors.

ricostacruz.com  ·  GitHub @rstacruz  ·  Twitter @rstacruz

Status npm version spm package

Public API

  • NProgress.version: A string containing the current NProgress version.

  • NProgress.settings: Direct access to the NProgress settings; see above for a comprehensive list of the available settings.

  • NProgress.configure(settings): Update the NProgress settings. Preferably called before you start NProgress, but this is not mandatory.

    Returns the NProgress instance for easy chaining:

    NProgress.configure({...}).start().set(0.01, 'blabla');
    
  • NProgress.set(n, msg): Sets the progress bar status, where n is a number from 0.0 to 1.0.

    msg is an optional string which will be displayed below the progress bar. The message may contain HTML (innerHTML).

  • NProgress.isStarted(): Returns TRUE when the progress bar is displayed and in progress.

  • NProgress.start(msg): Shows the progress bar. This is the same as setting the status to 0%, except that it doesn't go backwards.

    msg is an optional string which will be displayed below the progress bar. The message may contain HTML (innerHTML).

  • NProgress.done(force, msg): Hides the progress bar.

    This is the sort of the same as setting the status to 100%, with the difference being done() makes some placebo effect of some realistic motion.

    If true is passed in the force argument, it will show the progress bar even if its hidden.

    msg is an optional string which will be displayed below the progress bar. The message may contain HTML (innerHTML).

  • NProgress.inc(amount, msg): Increments by a random amount, unless the amount argument is a number, in which case that perunage (number between 0 and 1) will be added to the current progress bar status.

    This method will start showing the progress bar if it isn't displayed yet.

    msg is an optional string which will be displayed below the progress bar. The message may contain HTML (innerHTML).

  • NProgress.trickle(msg): Increments by a small random amount (determined by the NProgress.settings.trickleRate setting).

    msg is an optional string which will be displayed below the progress bar. The message may contain HTML (innerHTML).

  • NProgress.showSpinner(): Shows the spinner independently from the progress bar.

    Note: Whether this method delivers or not is controlled by the NProgress.settings.showSpinner setting.

  • NProgress.hideSpinner(): Hides the spinner independently from the progress bar.

    Note: Whether this method delivers or not is controlled by the NProgress.settings.showSpinner setting.

  • NProgress.showBar(): Shows the bar independently from the progress bar.

    Note: Whether this method delivers or not is controlled by the NProgress.settings.showBar setting.

  • NProgress.hideBar(): Hides the bar independently from the progress bar.

    Note: Whether this method delivers or not is controlled by the NProgress.settings.showBar setting.

  • NProgress.promise($promise): Waits for all supplied jQuery promises and increases the progress as the promises resolve.

    This method will start showing the progress bar if it isn't displayed yet.

  • NProgress.isRendered(): Checks if the progress bar is rendered.

Internals (API)

These methods are also available for use by the application code, but these are otherwise considered internal; while many of these help to provide a minimal DOM abstraction layer, a few others are very specific to NProgress, e.g. the .render() method listed below.

For (un)registering event listeners with NProgress this helper is available: you'll only need to call its addEventListener and/or removeEventListener methods when (un)registering your listeners with the NProgress.settings.onDone and NProgress.settings.onDoneBefore events.

  • NProgress.Internals.generateFunctionRegister(): Generator for the new addEventListener/removeEventListener API that sits on top of our events (onDone & onDoneBefore).

    This generator produces a function/class which offers these new addEventListener/removeEventListener methods; calling the generated object directly will invoke all registered handlers.

    Example (pseudo)code:

    // create new instance of event registrar
    var evtIF = NProgress.Internals.generateFunctionRegister();
    ...
    // register callback(s):
    evtIF.addEventListener(a);
    evtIF.addEventListener(b);
    ...
    // 'fire' the 'event': this will invoke registered callbacks 
    // `a` and `b`, where each will receive the `args` passed 
    // into evtIF:
    evtIF(args);
    
    • NProgress.Internals.generateFunctionRegister().addEventListener(callback): Add a callback/listener to the event; a la the DOM addEventListener, duplicate registrations are skipped.

      Returns a reference to the current function registrar instance.

    • NProgress.Internals.generateFunctionRegister().removeEventListener(callback): Remove the targeted listener callback (if it is still present in the event listener set); when no parameter or a non-function-type parameter is passed, it means all listeners will be removed at once.

      Returns a reference to the current function registrar instance.

  • NProgress.Internals.queue(): Returns a queue function/object which queues a function fn to be executed. Queued functions are executed with an interval of NProgress.settings.speed msecs between them (unless you need them to dequeue faster, which can be accomplished by setting the .showingProgress attribute of your fn callback/function to a truthy value, in which case this function will dequeue in a 1/20th of the NProgress.settings.speed interval.

    • NProgress.Internals.queue(fn).next(): You can also trigger the dequeue-ing of the next queued function by invoking the .next() method directly.

    Example (pseudo)code:

    // create a new queue instance:
    var q = NProgress.Internals.queue();
    // queue functions to be executed:
    q(f1); q(f2); q(f3);
    q(f4)(f5)(f6);
    ...
    function f1() {
      ...
      // don't wait for the timeout/interval 
      // to invoke the next queued function:
      q.next();
      // and you can even chain these:
      q.next().next().next();
      // and after this the remaining queued 
      // functions will be dequeued at 
      // the designated interval.
    }
    ...
    // and this function will dequeue 
    // much faster once after the previous 
    // dequeued function:
    function q5() { ...}
    q2.showingProgress = true;
    
  • NProgress.Internals.css(): Return function which applies CSS properties to an element, similar to the jQuery css method, i.e. by auto-detecting if the property is available standard or with a vendor prefix.

    • css(element, property, value): apply the value to the given CSS property.

    • css(element, properties): apply the values to the given CSS properties listed in the properties object.

    Example (pseudo)code:

    // create a new css instance:
    var css = NProgress.Internals.css();
    ...
    // apply one property value
    css(el, 'display', 'block');
    // remove another property, by setting it to NULL
    css(el, 'opacity', null);
    // apply a set of properties
    css(el, {
      display: 'block',
      position: 'relative'
    });
    

Internal NProgress specific methods:

  • NProgress.render(fromStart): (Internal) renders the progress bar markup based on the template setting.

  • NProgress.remove(): (Internal) Removes the progress bar. Opposite of render().

  • NProgress.getPositioningCSS(): Determine which positioning CSS rule to use: sniffs the context and returns one of these, depending on the browser capabilities discovered:

    • 'translate3d': Modern browsers with 3D support, e.g. Webkit, IE10

    • 'translate': Browsers without 3D support, e.g. IE9

    • 'margin': Browsers without translate() support, e.g. IE7-8

Several methods which serve as a very minimal DOM abstraction layer:

  • NProgress.Internals.hasClass(element, name): Determines if an element or space separated list of class names contains a class name.

  • NProgress.Internals.addClass(element, name): Adds a class to an element.

  • NProgress.Internals.removeClass(element, name): Removes a class from an element.

  • NProgress.Internals.classList(element): Gets a space separated list of the class names on the element.

    The list is wrapped with a single space on each end to facilitate finding matches within the list.

  • NProgress.Internals.removeElement(element): Removes an element from the DOM.

  • NProgress.Internals.findElementByAny(root, selector): Return the DOM node for the given selector.

    The selector can be:

    • a DOM node -- in which case this DOM node is immediately produced. This is useful when the user code already has a reference to the desired DOM node and passes it via the NProgress options.

    • an ID string -- (without the leading '#')

    • a query string -- which identifies a single DOM node. (When it doesn't, the first DOM node that matches will be produced as per https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector)

About

For slim progress bars like on YouTube, Medium, etc

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 51.4%
  • CSS 33.5%
  • HTML 14.7%
  • Shell 0.4%