Touch-enabled Drag/Rotate/Resize/Snap Library – subjx

Category: Drag & Drop , Javascript | November 13, 2026
Authornichollascarter
Last UpdateNovember 13, 2026
LicenseMIT
Views2,902 views
Touch-enabled Drag/Rotate/Resize/Snap Library – subjx

subjx is a vanilla JavaScript library for dragging, resizing, and rotating HTML and SVG elements with the mouse or touch.

It includes snapping and boundary constraints, with alignment guides and customizable handles for SVG editing.

How to use it

1. Install subjx

Install subjx and import its stylesheet:

npm install subjx
import subjx from 'subjx';
import 'subjx/dist/style/subjx.css';

For direct browser use, load the distributed CSS and UMD bundle. The global initializer is lowercase subjx().

<link rel="stylesheet" href="./dist/style/subjx.css">
<script src="./dist/js/subjx.js"></script>

2. Create a draggable, resizable element

Add an element inside a positioned container:

<div id="stage" style="position:relative; min-height:280px;">
  <div class="shape" style="position:absolute; left:60px; top:40px; width:180px; height:100px; background:#eee;">
    Drag, resize, or rotate me
  </div>
</div>

Call subjx(target).drag(options) with a CSS selector, DOM element, or array-like collection. Grid snapping is disabled by default; set snap steps to enable it.

const transform = subjx('.shape').drag({
  container: '#stage',
  restrict: '#stage',
  snap: { x: 10, y: 10, angle: 15 },
  draggable: true,
  resizable: true,
  rotatable: true
});

3. Configure an SVG element

For SVG editing, configure alignment guides, resize handles, and their grab areas. subjx supports SVG <g>, <path>, <rect>, <ellipse>, <circle>, <line>, <polyline>, <polygon>, <text>, <image>, <use>, and <foreignObject> elements.

const svgTransform = subjx('#shape').drag({
  guides: {
    targets: '.artwork',
    bounds: '#paper',
    threshold: 6,
    snap: true
  },
  handles: ['tl', 'tr', 'bl', 'br'],
  hitRadius: 8,
  flip: false
});

4. Update an active instance

transform.update({ axis: 'x', snap: { x: 5, y: 5, angle: 15 } });
transform.update({ rotatable: false, handles: ['tl', 'br'] });

5. Clone an element

Use .clone() to drag a copy into a target area. The copy must be fully inside stack for onDrop to run.

const cloneable = subjx('.template').clone({
  stack: '#drop-area',
  appendTo: '#workspace',
  style: {
    border: '1px dashed green',
    background: 'transparent'
  },
  onDrop(event, elements, clone) {
    // The clone was dropped inside stack.
  }
});

Cloning options

Clone optionDescription
stackSelector or element containing the dropped clone. Default: document.body.
appendToSelector or element receiving the clone during dragging. Default: document.body.
styleCSS property values applied to the clone.

All Configuration Options

OptionDescription and default
containerCSS selector or element used as the transformation coordinate system. Default: the target’s parent element.
controlsContainerCSS selector or element receiving the controls. Default: container.
axisMovement axis: 'x', 'y' or 'xy'. Default: 'xy'.
snapGrid steps: { x, y, angle }. x/y are pixels; angle is degrees. Default: { x: 0, y: 0, angle: 0 }. Zero disables snapping.
eachSynchronize peer elements: { move, resize, rotate }. All three default to false.
proportionsMaintain the aspect ratio during resizing/scaling. Default: false.
flipAllow mirroring when an SVG resize handle passes the opposite side. Default: true.
draggableEnable dragging. Default: true.
resizableEnable resizing. Default: true.
rotatableEnable rotation. Default: true.
scalableResize through transform scaling. Default: false.
restrictSelector or element that bounds dragging, resizing, and rotation. Default: none.
applyTranslateApply completed drag movements to CSS left/top (HTML) or SVG position attributes. Default: false.
rotatorAnchorRotator direction: 'n', 's', 'w' or 'e'. Default: 'e'.
rotatorOffsetDistance of rotator from the element. Default: 50.
showNormalDisplay the line between the element and rotator. Default: true.
transformOriginShow a transform-origin handle or set an initial [x, y] position. Accepts boolean or [number, number]. Default: false.
cursorMoveCursor while dragging. Default: 'auto'.
cursorResizeResize cursor, following the grabbed handle direction by default.
cursorRotateRotation cursor. Default: 'grabbing'.
customArbitrary user data available through options.custom. Default: null.
handlesArray of enabled resize handles. Default: all; available keys listed below.
hitRadiusExtra SVG handle/edge grab area in screen pixels. Default: 0.
showHitAreasShow SVG grab areas. Default: false.
guidesSVG alignment guides: false, true or a configuration object. Default: false.

Resize handles

The handles array accepts corners and midpoints tl, tc, tr, ml, mr, bl, bc, br; edges te, be, le, re; and SVG line endpoints p1, p2.

SVG guides configuration

Guide optionDescription
targetsElements or selector used as alignment targets. Default: sibling elements.
boundsElement or selector with container edges and center; false disables bounds. Default: container.
thresholdSnap distance in screen pixels. Default: 6.
snapWhen false, draw alignment guides but do not snap. Default: true.

Methods and properties

APIPurpose
subjx(target)Select a CSS selector, DOM element, or array-like collection of elements.
subjx(target).drag(options, observable)Create draggable, resizable, rotatable controls. Optional shared observable synchronizes elements.
subjx(target).clone(options)Enable drag-and-drop cloning.
subjx.createObservable()Create an Observable for coordinated elements.
instance.controlsGetter returning the controls root DOM element.
instance.handlesGetter returning handle DOM elements by key.
instance.enable(options)Enable transform controls. Usually called internally by drag().
instance.disable()Disable transformations and remove controls/handles.
instance.update(options)Merge new options into an enabled instance and update affected controls.
instance.on(eventName, cb)Subscribe to an instance event.
instance.off(eventName, cb)Unsubscribe a callback from an instance event.
instance.exeDrag({ dx, dy })Apply programmatic drag deltas; obeys restrict.
instance.exeResize({ dx, dy, revX, revY, doW, doH })Resize by x/y deltas; revX/revY resize toward the left/top, and doW/doH select dimensions.
instance.exeRotate({ delta })Apply programmatic rotation; delta is in radians.
instance.applyAlignment(direction, frameElement?)Align to the container or optional frame. Directions: l, r, t, b, h, v, tl, tr, bl, br, th, bh, lv, rv.
instance.fitControlsToSize()Reposition controls after an external scale or SVG viewBox change.
instance.setTransformOrigin({ x, y, dx, dy }, pin?)Set the transformation origin. pin keeps its current position fixed when true.
instance.resetTransformOrigin()Reset the transformation origin.
instance.getDimensions()Return x, y, width, height, and rotation in degrees.
instance.getVertices(transformMatrix?)Return handle positions in container coordinates: SVG points or HTML coordinate arrays. Accepts an optional transform matrix.
htmlInstance.getBoundingRect(transformMatrix?)Return HTML bounding vertices; accepts an optional transform matrix.
svgInstance.getBoundingRect(svgElement, transformMatrix?)Return SVG bounding vertices for the specified element; accepts an optional SVG transform matrix.

Observable API

Observable notifier events are ongetstate, onapply, onmove, onresize, and onrotate.

MethodPurpose
observable.subscribe(eventName, observer)Subscribe an Observer to a notifier event.
observable.unsubscribe(eventName, observer)Remove an Observer from a notifier event.
observable.notify(eventName, source, payload)Notify subscribed Observers with the event-specific payload.

Synchronize multiple elements

Pass the same Observable to each element that should share transformations:

const shared = subjx.createObservable();
subjx('.shape-a').drag({ each: { move: true, resize: false, rotate: false } }, shared);
subjx('.shape-b').drag({ each: { move: true, resize: false, rotate: false } }, shared);

Callbacks and events

Pass these callbacks to .drag(). Movement, resize, rotation, and drop callbacks receive an event data object.

const instance = subjx('.shape').drag({
  onInit(elements) {},
  onMove({ clientX, clientY, dx, dy, transform }) {},
  onResize({ clientX, clientY, dx, dy, transform, width, height }) {},
  onRotate({ clientX, clientY, delta, transform }) {},
  onDrop({ clientX, clientY }) {},
  onDestroy(elements) {}
});
Transform eventEmitted during
dragStart/ drag/ dragEndDrag lifecycle.
resizeStart/ resize/ resizeEndResize lifecycle; also used for SVG line endpoint movement.
rotateStart/ rotate/ rotateEndRotation lifecycle.
setPointStart/ setPointEndCustom transform-origin movement begins and ends.
const handleDrag = ({ dx, dy }) => console.log(dx, dy);
instance.on('drag', handleDrag);
instance.off('drag', handleDrag);

Cloning callbacks and events

Callback or APIBehavior
onInit(elements)Runs when cloning is initialized; receives the original elements array.
onMove({ dx, dy })Runs while dragging the copy.
onDrop(event, elements, clone)Runs after a valid drop; receives the pointer event, original elements, and the copy. The event is a MouseEvent, Touch, or TouchEvent.
onDestroy(elements)Runs when cloning is disabled.
cloneable.on(event, handler), cloneable.off(event, handler)Register or remove a listener for dragStart, drag, or dragEnd.
cloneable.disable()Stop cloning and remove its event handlers.

Styling controls

Customize the controls by overriding these classes in your stylesheet:

ClassControls or state
.sjx-svg-hdl, .sjx-svg-hdl-{key}SVG handle and handle-specific variant.
.sjx-svg-lineSVG control edge.
.sjx-svg-hitExpanded SVG grab area.
.sjx-svg-hit-handle, .sjx-svg-hit-edgeHandle and edge hit areas.
.sjx-svg-hit-overlayCombined hit-area overlay.
.sjx-show-hitControls with visible hit areas.
.sjx-activeActive handle or edge.
.sjx-actingControls during resize, rotate, or origin movement.
.sjx-svg-guideSVG alignment guide.
.sjx-hdl, .sjx-hdl-lineHTML handle and control edge.

Upgrading from v1.4 to v2.0

  • Grid snapping now defaults to zero for x, y and angle. Pass explicit snap steps when needed.
  • Replace setCenterPoint() and resetCenterPoint() with setTransformOrigin() and resetTransformOrigin().
  • Replace the removed rotationPoint option with transformOrigin.
  • Access handle elements through the public handles getter.
  • Use the new update(options) method to reconfigure an active instance.
  • The Transformable.observable property is private. Pass a shared Observable through drag(options, observable) for peer transformations.
  • Removed Transformable notifier methods include notifyMove, notifyRotate, notifyResize, notifyApply, notifyGetState, subscribe, unsubscribe.
  • The Observable subscribe(), unsubscribe() and notify() methods now require notifier event names and typed event payloads.

Related resources

Changelog

v2.0.1 (11/13/2026)

  • Bugfixes

v2.0.0 (11/11/2026)

  • Added live option updates and public handle access; changed snapping defaults, cursors, and deprecated transform/observer APIs.
  • Fixed primary mouse button handling, observable unsubscription, and SVG resize-guide boundaries.

v1.4.0 (10/16/2026)

  • transform: flip option, working min size for SVG and HTML resize
  • bugfixes

v1.3.0 (10/09/2026)

  • svg: hitRadius option and handle highlighting
  • svg: alignment guides and snapping while dragging
  • svg: alignment guides while resizing and moving line endpoints
  • choose resize handles with the handles option
  • svg: endpoint controls for line elements
  • typings generated from the TypeScript source
  • bugfixes

v1.2.0 (09/02/2026)

  • align: optional target frame for applyAlignment

v1.1.2 (10/13/2025)

  • types: make “observable” argument for drag method optional

v1.1.1 (11/04/2023)

  • fixed issue on rotating to 90deg

v1.1.0 (07/04/2022)

  • Bug Fixes
  • src: add setCenterPoint method
  • added transform origin support

v1.0.0 (12/15/2021)

  • Bug Fixes
  • prepare prerelease version for supporting groupable feature
  • Change API

v1.0.0rc3 (12/13/2021)

  • Bugfix

v1.0.0rc1 (11/02/2021)

  • prepare prerelease version for supporting groupable feature
  • Changed API

04/19/2021

  • v0.3.9: update

04/05/2021

  • v0.3.8: feat: added alignment feature

03/19/2021

  • v0.3.7: fixed translate issue

03/02/2021

  • v0.3.5/6

02/26/2021

  • v0.3.4: fix: polygon points parsing issue

02/26/2021

  • v0.3.3: fix resizable/rotatable options init issues

02/24/2021

  • v0.3.2: fix logic with storing deltas

02/18/2021

  • v0.3.1: fix: elementsArray issue

02/07/2020

  • v0.2.6: Fix: fix regex for parsing transform matrix

01/29/2020

  • v0.2.5: Added new API methods

01/21/2020

  • v0.2.4: bugfix

12/29/2019

  • v0.2.2

10/26/2019

  • fix: Added “passive” option to touch events

09/08/2019

  • v0.1.7: fix: tc/bc handles wrong behavior

You Might Be Interested In:


One thought on “Touch-enabled Drag/Rotate/Resize/Snap Library – subjx”

  1. BW

    I got an error shows “Subjx is not defined”, and found there is no class named as Subjx in subjx.js, please help!

    Reply ↓

Leave a Reply