noUiSlider - Documentation

Getting Started

Installation

noUiSlider can be installed via npm, yarn, or by downloading the files directly.

npm:

npm install nouislider

yarn:

yarn add nouislider

Direct Download:

Download the necessary files (nouislider.js and nouislider.css) from the official noUiSlider website and include them in your project.

Basic Usage

After installation, include the JavaScript and CSS files in your HTML. Then, create a slider element in your HTML, give it a unique ID, and initialize the slider using JavaScript. The core initialization involves selecting the slider element and calling the noUiSlider.create() method, passing the element and an options object. The options object defines the slider’s behavior, such as range, start value, and formatting.

First Example

This example creates a simple slider with a range from 0 to 100, starting at 50:

<!DOCTYPE html>
<html>
<head>
  <title>noUiSlider Example</title>
  <link rel="stylesheet" href="nouislider.css">
</head>
<body>

<div id="slider"></div>

<script src="nouislider.js"></script>
<script>
  const slider = document.getElementById('slider');

  noUiSlider.create(slider, {
    start: [50],
    connect: [true, false],
    range: {
      'min': 0,
      'max': 100
    }
  });
</script>

</body>
</html>

Remember to replace "nouislider.css" and "nouislider.js" with the actual paths to your downloaded files.

Including CSS

It’s crucial to include the nouislider.css stylesheet in your HTML’s <head> section. This stylesheet provides the necessary visual elements for the slider. Failure to include this file will result in a non-functional or visually broken slider. Make sure the path to the CSS file is correct relative to your HTML file. For example:

<link rel="stylesheet" href="nouislider.css">

Core Concepts

Slider Structure

A noUiSlider instance consists of a container element (the element you pass to noUiSlider.create()), one or more handles that the user interacts with, and a connecting element(s) that visually represent the range selected by the handles. The slider’s visual appearance is determined by the CSS file and can be customized. The underlying structure is based on a single, flexible container which adapts to its content. The handles are positioned absolutely within this container, allowing for precise control over their placement.

Handles and Ranges

Handles are the interactive elements that users drag to adjust the slider’s value. A slider can have one or more handles. Each handle represents a separate value, which might be linked (e.g., a range selection) or independent. The start option in the initialization configures the initial positions of the handles. The range option specifies the minimum and maximum values for the slider. The connect option controls which connecting elements (if any) are displayed between the handles and/or the range limits. These connecting elements visually represent the selected range(s).

Connecting to Values

noUiSlider doesn’t directly manipulate your application’s data. Instead, it provides events and methods to get and set the slider’s values. You can use the get() method to retrieve the current values of the handles. Conversely, you can use the set() method to change the handle positions programmatically. These values are numerical, and you can easily map them to your application’s data using functions or transformations within your code. The values are based on the defined range and are always within those boundaries.

Events and Callbacks

noUiSlider triggers several events during its operation, allowing you to integrate it seamlessly into your application’s logic. These events, such as update, change, and set, provide information about the slider’s state changes. You can attach event listeners to these events and execute custom code whenever a significant event happens, such as when the user moves a handle or programmatically sets a value. Callbacks are functions that are executed in response to these events, allowing you to react to user interactions and maintain data synchronization. Using these events and callbacks is crucial for dynamic interactions.

Options and Configuration

noUiSlider offers a wide range of options to customize its appearance and behavior. These options are passed as an object to the noUiSlider.create() method. Here are some of the most important ones:

start

Specifies the initial position(s) of the handle(s). For a single handle slider, this is a single number. For multiple handles, it’s an array of numbers. Each number represents the starting value for the corresponding handle. The values should fall within the specified range.

start: [0, 100] // For a range slider with two handles starting at 0 and 100
start: 50        // For a single handle slider starting at 50

connect

Controls the visual connection between handles. It can be a boolean, an array of booleans, or a string.

step

Specifies the increment step size between values. If omitted, the slider allows for continuous values. If set to a number, the slider values will only snap to multiples of that number.

step: 1 // Values will increment/decrement by 1
step: 5 // Values will increment/decrement by 5

range

Defines the minimum and maximum values of the slider.

range: {
  'min': 0,
  'max': 100
}

orientation

Sets the slider’s orientation.

orientation: 'horizontal' // Default
orientation: 'vertical'

direction

Controls the direction of the slider’s values.

direction: 'ltr' // Left-to-right (default)
direction: 'rtl' // Right-to-left

tooltips

Enables tooltips to display the current value(s) of the handle(s). Can be a boolean or a function that formats the value.

tooltips: true // Simple tooltips
tooltips: [wNumb({ decimals: 1 }), null] // Custom formatting for first handle only.

format

Allows custom formatting of the slider’s values using the wNumb library.

format: wNumb({ decimals: 2, thousand: '.' })

pips

Configures the visual pips (markers) along the slider. Provides options to set the density, position, and formatting of the pips. See the noUiSlider documentation for details on this extensive option.

animate

Enables or disables animation when setting values programmatically using the set() method.

animate: true // Enable animation (default)
animate: false // Disable animation

animationDuration

Specifies the duration of the animation in milliseconds when animate is enabled.

animationDuration: 300 // Animation lasts 300 milliseconds

Advanced Usage

Keyboard Navigation

noUiSlider provides built-in support for keyboard navigation. Users can use the arrow keys (left/right for horizontal, up/down for vertical sliders) to adjust the handle positions. The step option influences the increment/decrement size. Page Up/Page Down keys typically move the handle by a larger increment. This feature enhances accessibility and provides an alternative input method for users.

ARIA Attributes

noUiSlider automatically generates appropriate ARIA attributes to improve accessibility for screen readers. These attributes provide semantic information about the slider’s role, current values, and range. The attributes are generated based on the slider’s configuration and state, ensuring proper screen reader interaction. No extra configuration is generally needed to leverage these accessibility features.

Customizing Appearance

While noUiSlider provides a default CSS file, you can extensively customize its visual appearance. By overriding the default styles in your own CSS, you can change colors, sizes, handle shapes, and virtually any other visual aspect of the slider. Inspecting the default CSS can help you understand the structure and classes you need to target for customization. The flexibility allows you to seamlessly integrate the slider into diverse designs.

Localization

To adapt noUiSlider to different languages, you’ll mainly focus on the format option and potentially the tooltips option. The format option, leveraging the wNumb library, allows you to specify custom formatting for numbers, including thousands separators and decimal points based on locale conventions. Similarly, if you use custom tooltips, you can translate the displayed values within your tooltip formatting function.

Using with Frameworks (React, Angular, Vue)

noUiSlider is a vanilla JavaScript library and works well within various JavaScript frameworks. The integration usually involves creating a wrapper component that handles the slider’s initialization and updates. The component manages the slider instance, listens for relevant events, and updates the framework’s state accordingly. Many community-contributed components and examples are available for popular frameworks like React, Angular, and Vue, simplifying the integration process. These components often provide higher-level abstractions, simplifying the interaction between noUiSlider and your framework’s component lifecycle.

Methods and Properties

noUiSlider provides several methods and properties to interact with and control the slider instance.

set()

Programmatically sets the value(s) of the slider handle(s). Accepts a single number (for single-handle sliders) or an array of numbers (for multiple-handle sliders). The animate option controls whether the update is animated.

slider.noUiSlider.set(75); // Single handle slider
slider.noUiSlider.set([20, 80]); // Range slider

get()

Retrieves the current value(s) of the slider handle(s). Returns a single number or an array of numbers, depending on the slider configuration.

let value = slider.noUiSlider.get(); // Get the current value(s)

reset()

Resets the slider to its initial values as defined in the start option during initialization.

slider.noUiSlider.reset();

destroy()

Completely removes the slider instance from the DOM, freeing up resources and ensuring no memory leaks. This method should be called when the slider is no longer needed.

slider.noUiSlider.destroy();

updateOptions()

Allows modifying the slider’s options after initialization. This is useful for dynamically changing the slider’s behavior or appearance. Not all options can be updated; consult the documentation for details on which options are mutable.

slider.noUiSlider.updateOptions({ step: 10 }); // Change the step size

on() / off()

Methods for attaching and detaching event listeners. Events include update, change, slide, set, start, and end. These methods provide a robust way to handle slider events and interact with your application logic.

slider.noUiSlider.on('update', function(values, handle, unencoded, tap, positions){
    // Handle update event
});
slider.noUiSlider.off('update'); // Remove the event listener

target

This property refers to the original DOM element to which the noUiSlider instance was attached.

let sliderElement = slider.noUiSlider.target;

options

This property provides a read-only access to the current configuration options of the slider instance. It allows inspecting the settings after initialization or after using updateOptions().

let currentOptions = slider.noUiSlider.options;

Examples

These examples demonstrate various configurations and features of noUiSlider. Remember to include nouislider.css and nouislider.js in your HTML file before using these code snippets.

Range Slider

This example creates a range slider with two handles, allowing selection of a range of values.

<div id="range-slider"></div>
<script>
  const rangeSlider = document.getElementById('range-slider');
  noUiSlider.create(rangeSlider, {
    start: [20, 80],
    connect: true,
    range: {
      'min': 0,
      'max': 100
    }
  });
</script>

Dual-Handle Slider

Similar to the range slider, but with independent handles. Changes to one handle don’t affect the other.

<div id="dual-slider"></div>
<script>
  const dualSlider = document.getElementById('dual-slider');
  noUiSlider.create(dualSlider, {
    start: [20, 80],
    connect: [true, false], //Only connects the lower handle to min
    range: {
      'min': 0,
      'max': 100
    }
  });
</script>

Slider with Pips

This example adds visual pips (markers) to the slider for better readability.

<div id="slider-pips"></div>
<script>
  const sliderPips = document.getElementById('slider-pips');
  noUiSlider.create(sliderPips, {
    start: 50,
    range: {
      'min': 0,
      'max': 100
    },
    pips: {
      mode: 'steps',
      density: 5
    }
  });
</script>

Slider with Tooltips

This adds tooltips displaying the current handle values.

<div id="slider-tooltips"></div>
<script>
  const sliderTooltips = document.getElementById('slider-tooltips');
  noUiSlider.create(sliderTooltips, {
    start: 50,
    range: {
      'min': 0,
      'max': 100
    },
    tooltips: true
  });
</script>

Slider with Custom Formatting

This example uses wNumb for custom number formatting. Remember to include wNumb if you haven’t already.

<div id="slider-format"></div>
<script>
  const sliderFormat = document.getElementById('slider-format');
  noUiSlider.create(sliderFormat, {
    start: 1234.56,
    range: {
      'min': 0,
      'max': 2000
    },
    format: wNumb({ decimals: 2, thousand: ',', suffix: '€' })
  });
</script>

Slider with Keyboard Navigation

Keyboard navigation is enabled by default. This example simply demonstrates its functionality within a basic slider.

<div id="slider-keyboard"></div>
<script>
  const sliderKeyboard = document.getElementById('slider-keyboard');
  noUiSlider.create(sliderKeyboard, {
    start: 50,
    range: {
      'min': 0,
      'max': 100
    }
  });
</script>

Remember to replace placeholder IDs with your actual element IDs. These examples provide a starting point for more complex slider configurations. Consult the noUiSlider documentation for more advanced options and customization possibilities.

Troubleshooting

This section provides guidance on resolving common issues and debugging noUiSlider implementations.

Common Issues

Debugging Tips

Support and Community

For further assistance, you can explore the following resources:

API Reference

This section provides a detailed overview of the noUiSlider API.

Constructor

The core of noUiSlider is the noUiSlider.create() constructor. It takes two arguments:

const slider = document.getElementById('slider');
noUiSlider.create(slider, {
    start: 0,
    range: { 'min': 0, 'max': 100 }
});

The constructor returns a noUiSlider instance object which exposes various methods and properties.

Methods

The noUiSlider instance provides the following methods:

Options

The options object passed to the constructor configures the slider’s behavior and appearance. Key options include:

See the full list of options in the complete documentation.

Events

noUiSlider triggers various events that you can listen for using the on() method:

Event listeners receive arguments providing detailed information about the event context. Refer to the full documentation for specific argument details for each event. Consult the documentation for detailed descriptions of each event and its arguments.