axis

axis

Restrict movement to a single axis (x or y)

The axis plugin locks movement to horizontal (x) or vertical (y) direction. Perfect for sliders, scrollbars, or any UI requiring one-dimensional dragging.

axis('x'); // Only horizontal movement
axis('y'); // Only vertical movement
axis(null); // Free movement (removes constraint)

Basic Usage

import { axis, Draggable } from '@neodrag/vanilla';

const horizontal = document.getElementById('horizontal');
const vertical = document.getElementById('vertical');
const free = document.getElementById('free');

new Draggable(horizontal, [axis('x')]);
new Draggable(vertical, [axis('y')]);
new Draggable(free, [axis(null)]);

Dynamic Axis Switching

import { axis, Draggable, Compartment } from '@neodrag/vanilla';

let currentAxis = 'x';
const axisComp = new Compartment(() => axis(currentAxis));

const element = document.getElementById('draggable');
const button = document.getElementById('switch-button');
const display = document.getElementById('axis-display');

new Draggable(element, () => [axisComp]);

button.addEventListener('click', () => {
  currentAxis = currentAxis === 'x' ? 'y' : 'x';
  axisComp.current = axis(currentAxis);
  display.textContent = `Currently locked to: ${currentAxis} axis`;
});

Real-World Examples

Horizontal Slider Component

import {
  axis,
  bounds,
  BoundsFrom,
  events,
  Draggable,
} from '@neodrag/vanilla';

const track = document.getElementById('track');
const handle = document.getElementById('handle');
const valueDisplay = document.getElementById('value');

function handleDrag(data) {
  const trackWidth = track.offsetWidth;
  const value = Math.round((data.offset.x / trackWidth) * 100);
  valueDisplay.textContent = `${value}%`;
}

new Draggable(handle, [
  axis('x'),
  bounds(BoundsFrom.element(track)),
  events({ onDrag: handleDrag }),
]);

Split Pane Resizer

// Vertical divider for horizontal split
const plugins = [
  axis('x'),
  bounds(
    BoundsFrom.parent({
      left: 100, // Min pane width
      right: 100, // Min pane width
    }),
  ),
];

How It Works

The axis plugin modifies the proposed movement during dragging:

  • axis('x'): Sets proposed.y = null (no vertical movement)
  • axis('y'): Sets proposed.x = null (no horizontal movement)
  • axis(null): No changes (free movement)

This happens in the plugin’s drag hook, so other plugins receive the constrained movement values.

API Reference

function axis(value?: 'x' | 'y' | null | undefined): Plugin;

Parameters:

  • value - The axis to constrain movement to
    • 'x' - Horizontal only
    • 'y' - Vertical only
    • null or undefined - No constraint

Returns: A plugin object for use with draggable.