javascriptnode.jsnpmspin.js

How to use spin.js from client (Javascript, Node)


I'm trying to use spin.js (https://spin.js.org/#!) from the client but am I have some problems.
Doing

npm install spin.js

then

const Spinner = require('spin.js');

does not work as you need to browserify the module in order to use the module from the client.

I've also tried to copy and past spin.js (https://spin.js.org/spin.js) and refer it from the html but it gave me an error in spin.js at

export { Spinner };

as

Uncaught SyntaxError: Unexpected token export

What is needed to use spin.js from a client?


Solution

  • Ok so I figured it out.

    What you have to do is:

    Copy the spin.js file into your local filesystem (call it spin.js) and refer to the local spin.js at the end of the body tag in the html file.

    ...
    <script type="text/javascript" src="js/spin.js"></script>
    <script type="text/javascript" src="js/scriptWithSpinner.js"></script>
    </body>
    

    Comment out the following line in spin.js.

    export { Spinner };
    

    Copy the CSS from https://spin.js.org/spin.css and store it in your local filesystem. Refer to the CSS from the header of the html file.

    <head>
        <meta charset="utf-8">
        ...
    
        <link rel="stylesheet" type="text/css" href="mystyles.css" />
        <link rel="stylesheet" type="text/css" href="spin.css" />
        ...
    </head>
    

    If you are using express, you might need to expose the directory with the js and CSS in your server code so the html file can read it.

    Now you can directly use globally defined Spinner object from scriptWithSpinner.js, no imports or requires necessary.

    scriptWithSpinner.js

    var opts = {
      lines: 13, // The number of lines to draw
      length: 38, // The length of each line
      width: 17, // The line thickness
      radius: 45, // The radius of the inner circle
      scale: 1, // Scales overall size of the spinner
      corners: 1, // Corner roundness (0..1)
      color: '#ffffff', // CSS color or array of colors
      fadeColor: 'transparent', // CSS color or array of colors
      speed: 1, // Rounds per second
      rotate: 0, // The rotation offset
      animation: 'spinner-line-fade-quick', // The CSS animation name for the lines
      direction: 1, // 1: clockwise, -1: counterclockwise
      zIndex: 2e9, // The z-index (defaults to 2000000000)
      className: 'spinner', // The CSS class to assign to the spinner
      top: '50%', // Top position relative to parent
      left: '50%', // Left position relative to parent
      shadow: '0 0 1px transparent', // Box-shadow for the lines
      position: 'absolute' // Element positioning
    };
    
    var target = document.getElementsByClassName('uploader')[0];
    var spinner = new Spinner(opts).spin(target);