preline
Version:
Preline UI is an open-source set of prebuilt UI components based on the utility-first Tailwind CSS framework.
315 lines (231 loc) • 11.1 kB
Markdown
# Advanced Range Slider
Advanced Range Slider solutions for massive datasets.
[](https://www.npmjs.com/package/@preline/range-slider) [](https://opensource.org/licenses/MIT) [](https://preline.co/plugins/advanced-range-slider.html)
## Contents
- [Overview](#overview)
- [Installation](#installation)
- [Basic usage](#basic-usage)
- [Configuration Options](#configuration-options)
- [JavaScript API](#javascript-api)
- [Events](#events)
- [Common Patterns](#common-patterns)
- [License](#license)
## Overview
The Advanced Range Slider component provides a flexible range input interface for selecting numeric values within a specified range. It integrates with noUiSlider for advanced functionality including dual handles, custom formatting, and smooth animations.
**Key Features:**
- Single and dual handle support
- Custom value formatting
- Smooth animations and transitions
- Integration with noUiSlider
- Programmatic control via JavaScript API
- Event system for value tracking
- Disabled state support
## Installation
To get started, install Advanced Range Slider plugin via npm, else you can skip this step if you are already using Preline UI as a package.
```bash
npm i nouislider @preline/range-slider
```
### CSS
Use [`@source`](https://tailwindcss.com/docs/functions-and-directives#source-directive) to register the plugin's JavaScript path for Tailwind CSS scanning, then [`@import`](https://tailwindcss.com/docs/functions-and-directives#import-directive) the plugin's CSS files into your Tailwind CSS file.
```css
@import "tailwindcss";
/* @preline/range-slider */
@source "../node_modules/@preline/range-slider/*.js";
@import "./node_modules/@preline/range-slider/variants.css";
@import "./node_modules/@preline/range-slider/theme.css";
```
### JavaScript
Include the JavaScript that powers the interactive elements near the end of your `</body>` tag:
```html
<script src="./node_modules/nouislider/dist/nouislider.min.js"></script>
<script src="./node_modules/@preline/range-slider/index.js"></script>
```
### Manual Initialization
Use the `non-auto` entry if you need manual initialization. In this mode, automatic initialization on page load is not included, so the component should be initialized explicitly.
```html
<script src="./node_modules/nouislider/dist/nouislider.min.js"></script>
<script type="module">
import HSRangeSlider from "@preline/range-slider/non-auto.mjs";
new HSRangeSlider(document.querySelector("#range-slider"));
</script>
```
### Via Bundler
When using a bundler (Vite, webpack, etc.), import the plugin directly as an ES module. `noUiSlider` is referenced as a global, so expose it on `window` before importing the plugin.
`@preline/range-slider` is the auto-init entry: it scans the DOM and initializes matching elements automatically.
```js
import * as noUiSlider from "nouislider";
window.noUiSlider = noUiSlider;
import "@preline/range-slider";
```
`@preline/range-slider/non-auto` is the manual entry: use it when you want explicit control over when initialization happens, either via `autoInit()` or by creating a specific instance yourself.
```js
import * as noUiSlider from "nouislider";
window.noUiSlider = noUiSlider;
import HSRangeSlider from "@preline/range-slider/non-auto";
HSRangeSlider.autoInit();
// Or initialize a specific element manually
const el = document.querySelector("#range-slider");
if (el) new HSRangeSlider(el);
```
### TypeScript
This package ships with TypeScript type definitions. No additional `@types/` package is needed.
## Basic usage
The following example demonstrates the minimal HTML structure required for an advanced range slider component. This is a base template without custom styling - you can apply your own CSS classes and styles as needed. The slider allows selecting a value between 0 and 100.
```html
<div data-hs-range-slider='{
"cssClasses": {},
"start": 50,
"connect": "lower",
"range": {
"min": 0,
"max": 100
}
}'></div>
```
**Structure Requirements:**
- `data-hs-range-slider`: Required on the container element, contains configuration options as JSON
- Container element will be automatically populated with slider markup by the plugin
**Initial State:**
- Slider starts at the value specified in `start` option
- Range is defined by `min` and `max` in the `range` option
## Configuration Options
### Data Options
> **Note:** Since our plugin is an extension of the [noUiSlider](https://refreshless.com/nouislider/) plugin, all its [options](https://refreshless.com/nouislider/slider-options/) can be passed as parameters to our plugin.
Data options are specified in the `data-hs-range-slider` attribute as a JSON object.
| Option | Target Element | Type | Default | Description |
| --- | --- | --- | --- | --- |
| `data-hs-range-slider` | Container element | - | - | Activate a Range Slider by specifying on an element. Should be added to the initialized element. Since our plugin is an extension of the [noUiSlider](https://refreshless.com/nouislider/) plugin, all its [options](https://refreshless.com/nouislider/slider-options/) can be passed as parameters to our plugin. |
| `:disabled` | Inside `data-hs-range-slider` | boolean | `false` | Makes the element unavailable for interaction. When `true`, the slider cannot be moved. |
| `:formatter` | Inside `data-hs-range-slider` | string \| object | - | Output value formatting options. Can be a string or an object with formatting configuration. |
| `:formatter:type` | Inside `data-hs-range-slider` | `"integer"` \| `"thousandsSeparatorAndDecimalPoints"` \| null | `null` | Defines an output formatter type. `integer` formats as integer, `thousandsSeparatorAndDecimalPoints` adds thousands separators and decimal points. |
| `:formatter:prefix` | Inside `data-hs-range-slider` | string | - | Adds a prefix to the output value (e.g., "$" for currency). |
| `:formatter:postfix` | Inside `data-hs-range-slider` | string | - | Adds a postfix to the output value (e.g., "px" for pixels). |
**Example:**
```html
<div data-hs-range-slider='{
"start": [20, 80],
"connect": true,
"range": {
"min": 0,
"max": 100
},
"formatter": {
"type": "integer",
"prefix": "$",
"postfix": ""
},
"disabled": false
}'></div>
```
### Tailwind Modifiers
| Name | Description |
| --- | --- |
| `hs-range-slider-disabled:*` | A modifier that allows you to set Tailwind classes when slider has "disabled" attribute set to "true". |
## JavaScript API
The `HSRangeSlider` object is available in the global `window` object after the plugin is loaded.
### Instance Methods
These methods are called on a range slider instance.
| Method | Parameters | Return Type | Description |
| --- | --- | --- | --- |
| `formattedValue()` | None | `any` | Returns the current values formatted using the `formatter` option. Returns formatted values as specified in the formatter configuration. |
| `destroy()` | None | `void` | Destroys the range slider instance, removes all generated markup, classes, and event listeners. Use when removing slider from DOM. |
### Static Methods
These methods are called directly on the `HSRangeSlider` class.
| Method | Parameters | Return Type | Description |
| --- | --- | --- | --- |
| `HSRangeSlider.getInstance(target, isInstance)` | `target`: `HTMLElement \| string` (CSS selector)<br>`isInstance`: `boolean` (optional) | `HTMLElement \| { id: string \| number, element: HSRangeSlider } \| null` | Returns the range slider instance or element associated with the target. If `isInstance` is `true`, returns collection item object `{ id, element }` where `element` is the `HSRangeSlider` instance. If `isInstance` is `false` or omitted, returns the DOM element (`HTMLElement`). Returns `null` if range slider instance is not found. |
### Usage Examples
**Example 1: Getting formatted value**
```javascript
// Get the range slider instance
const instance = HSRangeSlider.getInstance('#hs-range-slider', true);
if (instance) {
const { element } = instance;
// Get formatted value
const formatted = element.formattedValue();
console.log('Formatted value:', formatted);
}
```
**Example 2: Accessing noUiSlider instance**
```javascript
const instance = HSRangeSlider.getInstance('#hs-range-slider', true);
if (instance) {
const { element } = instance;
// Access underlying noUiSlider instance
const noUiSlider = element.el.noUiSlider;
if (noUiSlider) {
// Use noUiSlider methods
const currentValue = noUiSlider.get();
console.log('Current value:', currentValue);
}
}
```
**Example 3: Destroying range slider instance**
```javascript
const instance = HSRangeSlider.getInstance('#hs-range-slider', true);
if (instance) {
const { element } = instance;
const removeBtn = document.querySelector('#hs-remove-btn');
removeBtn.addEventListener('click', () => {
// Clean up before removing from DOM
element.destroy();
// Now safe to remove the element
document.querySelector('#hs-range-slider').remove();
});
}
```
## Events
> **Note:** Note that all [events](https://refreshless.com/nouislider/events-callbacks/) available in the [noUiSlider](https://refreshless.com/nouislider/) plugin are also available in our plugin, just use `el.noUiSlider` to handle events.
Range slider instances emit events that can be listened to for value tracking and custom behavior.
| Event Name | When Fired | Callback Parameter | Description |
| --- | --- | --- | --- |
| `on:update` | When slider value is updated | `[integer, integer?]` | Fires when the slider value changes. Returns an array with current values. For single handle, array contains one value. For dual handles, array contains two values. |
### Event Usage Example
```javascript
// Get range slider instance
const instance = HSRangeSlider.getInstance('#hs-range-slider', true);
if (instance) {
const { element } = instance;
// Listen to update event via noUiSlider
if (element.el.noUiSlider) {
element.el.noUiSlider.on('update', (values) => {
console.log('Slider updated:', values);
console.log('Formatted value:', element.formattedValue());
// Perform actions after slider value changes
// e.g., update UI, send to server, filter data
});
}
}
```
## Common Patterns
### Pattern 1: Dual Handle Range
Create a range slider with two handles for selecting a range.
```html
<div data-hs-range-slider='{
"start": [20, 80],
"connect": true,
"range": {
"min": 0,
"max": 100
}
}'></div>
```
### Pattern 2: Formatted Values
Add prefix and postfix to slider values.
```html
<div data-hs-range-slider='{
"start": 50,
"range": {
"min": 0,
"max": 100
},
"formatter": {
"type": "integer",
"prefix": "$",
"postfix": ""
}
}'></div>
```
## License
Copyright (c) 2026 Preline Labs.
Licensed under the [MIT License](https://opensource.org/licenses/MIT).