Normalize Scroll Left

0.2.1 · active · verified Sun Apr 19

This utility library addresses the inconsistent behavior of the `Element.scrollLeft` property when an element's direction is set to Right-to-Left (RTL) across different browsers. It provides methods to detect the browser's specific `scrollLeft` implementation type (e.g., WebKit's 'default', Firefox/Opera's 'negative', IE/Edge's 'reverse') and then normalize `scrollLeft` values to a consistent, WebKit-like `0` (most left) to `100` (most right) range for both getting and setting. The current stable version is 0.2.1. Releases appear to be driven by bug fixes and feature enhancements, such as ESM support in v0.2.0. Its key differentiator is robust feature detection to abstract away browser quirks, enabling developers to work with a predictable `scrollLeft` API for RTL content, based on established patterns from jQuery plugins and Stack Overflow solutions. It explicitly handles Server-Side Rendering (SSR) environments by returning `indeterminate` or `NaN` for relevant functions, indicating non-browser execution.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates detecting scroll behavior, creating an RTL scrollable element, and using normalized functions to get and set its scroll position consistently across browsers.

import { detectScrollType, getNormalizedScrollLeft, setNormalizedScrollLeft } from 'normalize-scroll-left';

// This quickstart demonstrates how to use normalize-scroll-left to handle
// inconsistent Element.scrollLeft behavior in RTL layouts across browsers.

// 1. Detect the browser's scroll type (caches result)
//    Must be called after the DOM body is loaded.
const scrollType = detectScrollType();
console.log(`Detected scroll type: ${scrollType}`); // e.g., 'default', 'negative', 'reverse', 'indeterminate' in SSR

// 2. Create a dummy scrollable element for demonstration
const container = document.createElement('div');
container.id = 'my-scrollable-container';
container.style.direction = 'rtl';
container.style.width = '100px';
container.style.overflowX = 'scroll';
container.style.whiteSpace = 'nowrap';
container.style.border = '1px solid black';
container.innerHTML = '<span style="display:inline-block; width:200px; height:20px;">Scrollable Content</span>';
document.body.appendChild(container);

// Simulate scrolling to the most right (normalized to 100)
setNormalizedScrollLeft(container, 100, 'rtl');
console.log(`After setting normalized scrollLeft to 100 (most right): ${getNormalizedScrollLeft(container, 'rtl')}`);

// Simulate scrolling to a specific position (normalized to 20)
setNormalizedScrollLeft(container, 20, 'rtl');
console.log(`After setting normalized scrollLeft to 20: ${getNormalizedScrollLeft(container, 'rtl')}`);

// Clean up
document.body.removeChild(container);

view raw JSON →