spin.js - Documentation

What is Spin.js?

Spin.js is a small, lightweight JavaScript library for creating customizable spinning loading indicators. It provides a simple and efficient way to display a visual cue to users while a page or application is loading data or performing a lengthy operation. Unlike many other loading spinner libraries, Spin.js prioritizes minimal code size and ease of integration, making it a perfect choice for projects that need to remain performant and maintain a small footprint. It offers a range of customization options allowing developers to tailor the spinner’s appearance to match their application’s style.

Key Features and Benefits

Setting up Spin.js: Installation and Configuration

Spin.js is easily integrated into your project. The simplest method is to download the spin.js file from the project’s website or via a package manager like npm or yarn.

Using a CDN (Content Delivery Network):

Include the following script tag in the <head> section of your HTML file:

<script src="https://cdn.jsdelivr.net/npm/spin.js@2.3.2/spin.min.js"></script> 

Using npm:

npm install spin.js

Then, import it into your JavaScript code:

import Spinner from 'spin.js';

Using yarn:

yarn add spin.js

Then, import it into your JavaScript code:

import Spinner from 'spin.js';

After including the library, you are ready to create and use spinners. No further configuration is typically needed.

Basic Usage Example

This example demonstrates creating a simple spinner and adding it to a specific element on your page.

<!DOCTYPE html>
<html>
<head>
  <title>Spin.js Example</title>
  <script src="https://cdn.jsdelivr.net/npm/spin.js@2.3.2/spin.min.js"></script> 
</head>
<body>

<div id="spinner"></div>

<script>
  const opts = {
    lines: 13, // The number of lines to draw
    length: 20, // The length of each line
    width: 10, // The line thickness
    radius: 30, // The radius of the inner circle
    scale: 1, // Scales overall size of the spinner
    corners: 1, // Corner roundness (0..1)
    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
    color: '#000', // CSS color or array of colors
    fadeColor: 'transparent', // CSS color or array of colors
    shadow: true, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 2e9, // The z-index (defaults to 2000000000)
    top: '50%', // Top position relative to parent in px
    left: '50%', // Left position relative to parent in px
  };
  const target = document.getElementById('spinner');
  const spinner = new Spinner(opts).spin(target);

  // ...later, when the loading is complete...
  spinner.stop();
</script>

</body>
</html>

This code creates a spinner with the specified options and adds it to the element with the ID “spinner”. Remember to replace "https://cdn.jsdelivr.net/npm/spin.js@2.3.2/spin.min.js" with the correct path if you’re not using a CDN. The spinner.stop() method is called when the loading process is finished to remove the spinner from the page. Refer to the Spin.js documentation for a complete list of available options.

Core Concepts

Understanding Spinners

Spin.js uses the concept of a “spinner” object to represent the loading indicator. This object is created using the Spinner constructor, which accepts an optional configuration object as an argument. The configuration object allows you to customize various aspects of the spinner’s appearance and behavior. Once created, the spinner can be added to the DOM (Document Object Model) using the spin() method, which takes a target element as an argument. This places the spinner visually within the specified element. The spinner can subsequently be removed by calling the stop() method. At its core, a Spin.js spinner is a collection of lines that rotate, creating the visual effect of a loading animation. These lines are rendered using CSS, allowing for easy styling and customization.

Customization Options

Spin.js provides a wide range of options for customizing the appearance and behavior of your spinners. These options are passed as a JavaScript object to the Spinner constructor. Key customization options include:

Refer to the complete API documentation for a comprehensive list of all available customization options and their data types.

Spinner Types and Styles

While Spin.js doesn’t explicitly define different “types” of spinners in the sense of pre-built styles, the extensive customization options allow for a wide variety of visual appearances. You can create different styles by adjusting parameters like the number of lines, their length and width, the colors, speed, and the animation property. The animation property allows you to specify the name of a CSS animation to apply to the spinner lines, providing a path to create more complex and visually distinct loading indicators. The flexibility of the CSS-based rendering is key to the diverse styles achievable.

Responsiveness and Adaptability

Spin.js spinners are inherently responsive. Because the size and positioning are controlled via the options passed to the constructor (including scale, radius, top, left) and the styling is controlled through CSS, spinners will adapt to different screen sizes and resolutions. You can make your spinners more responsive by using relative units (like percentages) for sizing and positioning within your CSS. For example, using percentages for top and left will help center the spinner regardless of the parent container’s dimensions. Likewise, using relative units in your CSS class applied via className will ensure that the spinner scales appropriately with its surroundings. No special configuration within Spin.js is required for responsiveness; it is a result of its design and its reliance on CSS for rendering.

API Reference

Spinner Constructor

The Spinner constructor creates a new spinner object. It accepts a single optional argument: an object containing configuration options. These options determine the spinner’s appearance and behavior. If no options are provided, default values are used.

const spinner = new Spinner(); // Creates a spinner with default options
const spinner = new Spinner({
  lines: 12,
  length: 7,
  width: 5,
  radius: 10,
  color: '#000',
  speed: 1,
  // ... other options
});

The available options are detailed in the “Customization Options” section and the full API documentation. The constructor returns a Spinner object which can then be manipulated via its methods.

Methods: start(), stop(), toggle()

Properties: color, size, lines, speed etc.

While Spin.js doesn’t directly expose properties for modification after the spinner is created, the visual attributes of the spinner are determined by the options passed to the constructor. These options effectively act as read-only properties that define the spinner’s state. For example, color, lines, length, width, radius, speed, etc., influence the spinner’s appearance and behavior. To change these attributes, you would need to create a new Spinner object with the updated options and replace the old one. Direct access and manipulation of properties after initialization are not supported.

Events

Spin.js does not currently offer a built-in event system. There are no events triggered during the spinner’s lifecycle (start, stop, etc.). If you need event handling related to the spinner’s state, you will have to manage it externally within your application’s code by monitoring its start/stop status directly, or implement custom event listeners based on the state changes within your application’s logic.

Advanced Configuration Options

Beyond the basic customization options, Spin.js offers some more advanced configuration settings:

Consult the complete API documentation for a detailed explanation of each option and its possible values. Remember that some options interact with each other, so experimentation may be required to achieve the desired visual effect.

Customization and Styling

CSS Customization

Spin.js spinners are rendered using CSS, making them highly customizable. The primary method for styling is through the className option passed to the Spinner constructor. This option allows you to assign a CSS class to the spinner’s container element. You can then define styles for this class in your external CSS stylesheet to control aspects such as:

Example CSS:

.my-spinner {
  width: 50px;
  height: 50px;
  margin: 0 auto; /* Center the spinner */
}

.my-spinner .spinner-line { /* Style individual lines */
  background-color: blue; /*Example*/
}

/*Custom Animation*/
@keyframes my-custom-spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}
.my-spinner {
    animation: my-custom-spin 2s linear infinite;
}

Remember to include this CSS in your HTML file, usually within a <style> tag or linked from an external .css file.

Modifying Spinner Appearance

The appearance of the spinner is primarily controlled through options passed to the Spinner constructor (e.g., lines, length, width, radius, color, speed, corners, shadow, fadeColor). Changing these options will directly affect the visual properties of the spinner. To modify an existing spinner’s appearance you need to stop it, create a new Spinner instance with the updated options, and start the new spinner in the same location.

Creating Custom Spinners

Creating custom spinners involves combining the use of the className option with custom CSS. Define a unique class name (e.g., .my-custom-spinner) in the Spinner constructor’s options. Then, create a set of CSS rules that target this class and define the desired styles for the spinner’s lines, container, and any other elements you add. You can leverage CSS animations to create custom spinning or loading effects. This approach ensures that you can have multiple spinners with different appearances within the same application.

Integrating with Frameworks (React, Angular, Vue)

Spin.js is a vanilla JavaScript library and is framework-agnostic; it can be easily integrated into popular JavaScript frameworks like React, Angular, and Vue. The integration process generally involves:

Example (React):

import React, { useState, useEffect, useRef } from 'react';
import Spinner from 'spin.js';

function MyComponent() {
  const [isLoading, setIsLoading] = useState(true);
  const spinnerRef = useRef(null);

  useEffect(() => {
    const opts = { lines: 10, color: 'blue' }; //Your custom options
    const spinner = new Spinner(opts);
    spinner.spin(spinnerRef.current);
    // Simulate loading...
    setTimeout(() => {
      setIsLoading(false);
      spinner.stop();
    }, 2000);
    return () => {
        //Clean up the spinner on unmount if necessary
        if (spinner) {
          spinner.stop();
        }
      };
  }, []);

  return (
    <div>
      {isLoading && <div ref={spinnerRef}></div>}
      <h1>My Component</h1>
    </div>
  );
}

export default MyComponent;

Adapt this pattern for Angular and Vue, using their respective component lifecycle methods and data binding mechanisms. Remember to appropriately handle the creation and destruction of the spinner instances to prevent memory leaks. The core concept remains the same across all frameworks: include Spin.js, create a Spinner object, control its lifecycle, and style it using CSS.

Advanced Usage

Performance Optimization

Spin.js is already designed to be lightweight and performant. However, for optimal performance in demanding applications, consider these points:

Accessibility Considerations

Accessibility is crucial for inclusive design. While Spin.js itself doesn’t directly handle accessibility features, you should ensure your implementation considers accessibility best practices. Here are some key points:

Troubleshooting Common Issues

Integration with other libraries

Spin.js integrates seamlessly with most other JavaScript libraries since it’s a simple, self-contained library without external dependencies. However, there are a few considerations:

Remember to always consult the documentation for both Spin.js and any other libraries you’re integrating with to ensure compatibility and proper usage.

Examples and Use Cases

Loading Indicators

The most common use case for Spin.js is as a loading indicator. Display a spinner while fetching data from an API, processing a large file, or performing any other time-consuming operation. This provides visual feedback to the user, letting them know that the application is working.

const opts = { color: '#007bff', lines: 12, length: 10 }; // Example options
const spinner = new Spinner(opts);
const target = document.getElementById('loading-indicator');

// Start spinner before API call
spinner.spin(target);
fetch('/api/data')
  .then(response => response.json())
  .then(data => {
    // Update UI with data
    // ...
    spinner.stop(); // Stop spinner after data is received
  })
  .catch(error => {
    // Handle error
    spinner.stop(); // Stop spinner even on error
  });

Remember to add a <div id="loading-indicator"></div> to your HTML where the spinner will be displayed.

Progress Bars

While Spin.js itself is not a progress bar, it can be effectively combined with one. You could display a progress bar alongside a spinner to provide more detailed feedback to the user. The spinner could indicate that an operation is in progress, while the progress bar displays the percentage of completion. This would require additional logic within your application to manage both the spinner and the progress bar.

Interactive Spinners

You can make spinners more interactive by associating them with user events or actions. For instance, a spinner could appear when a user clicks a button that initiates a long-running process, and disappear after the process is complete. Or a spinner could be dynamically displayed within a form while data is submitted to the server. This involves properly integrating the spinner’s lifecycle (start and stop) with the events relevant to your application.

const button = document.getElementById('myButton');
const spinnerContainer = document.getElementById('spinnerContainer');
const spinner = new Spinner({ color: 'green' });

button.addEventListener('click', () => {
  spinner.spin(spinnerContainer);
  // Perform some lengthy operation...
  setTimeout(() => {
    spinner.stop();
    // Update the UI after the operation completes
  }, 3000);
});

This example shows a spinner appearing only when the button is clicked.

Custom Animations

Spin.js allows for custom CSS animations through the animation option. Define a CSS animation using @keyframes and specify its name in the animation property when creating the spinner. This enables a high degree of control over the spinner’s visual style.

@keyframes myCustomSpin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* ... later in your JavaScript ... */
const spinner = new Spinner({
    animation: 'myCustomSpin',
    color: 'orange'
});
spinner.spin(document.getElementById('mySpinner'));

This approach enables the creation of unique and visually appealing spinners beyond the default styles. Remember that complex animations might impact performance; strive for simplicity when creating custom animations.

Contributing to Spin.js

This section outlines how to contribute to the Spin.js project. Contributions are welcome, whether it’s bug fixes, new features, or improvements to the documentation.

Setting up Development Environment

  1. Fork the Repository: Fork the official Spin.js repository on GitHub to your own account.

  2. Clone Your Fork: Clone your forked repository to your local machine:

    git clone <your-fork-url>
  3. Install Dependencies: Navigate to the project directory and install the necessary dependencies using npm or yarn:

    npm install  // or yarn install
  4. Set up a Development Server (optional): While not strictly required for contributing code changes, setting up a development server can be helpful for testing and previewing your changes. Spin.js doesn’t have a built-in development server. You’ll need to build one as needed, possibly using a simple HTTP server to serve the files. This is usually only necessary for large-scale changes or new features that require extensive testing.

  5. Run Tests (recommended): Before making any changes, run the existing tests to ensure the project is working correctly on your machine. See the “Testing and Debugging” section for more details.

Code Style Guide

Spin.js follows a consistent code style. Adhere to these guidelines when submitting code changes:

Ensure your code is well-formatted and follows these guidelines before submitting a pull request. Use a code formatter (e.g., Prettier) to help maintain consistent styling.

Testing and Debugging

Spin.js uses a testing framework. The specific testing framework may be listed in the project’s README or documentation. The tests typically cover the core functionality of the library.

  1. Run Tests: Run the tests using the command specified in the project’s documentation (likely npm test or yarn test). This will verify that the existing code functions correctly.

  2. Write Tests: When adding new features or fixing bugs, write corresponding tests to ensure your changes do not introduce regressions. Good test coverage is essential for maintaining the quality of the project.

  3. Debugging: Use your browser’s developer tools to debug your code. Set breakpoints in your code and step through the execution to identify issues.

Submitting Pull Requests

  1. Create a Branch: Create a new branch from the main or master branch for your changes:

    git checkout -b <your-branch-name>
  2. Make Your Changes: Make your code changes and commit them with clear and descriptive commit messages.

  3. Push Your Branch: Push your branch to your forked repository:

    git push origin <your-branch-name>
  4. Create a Pull Request: On GitHub, create a pull request from your branch to the main branch of the original Spin.js repository. Provide a clear description of your changes and address any feedback from reviewers.

  5. Address Feedback: Respond to any comments or requests for changes from the project maintainers. Make necessary revisions and push updates to your branch.

Remember to follow the project’s contribution guidelines, if any, when submitting your pull request. A well-written pull request with clear explanations of your changes increases the likelihood of a timely review and acceptance.