hcg-draggable - Live Demo

Interactive demos of hcg-draggable, a lightweight zero-dependency JavaScript library for draggable elements. Try axis lock, grid snap, containment, drag handles, and revert. Full documentation

1. Basic free drag (auto-init via attribute)

Add data-hcg-draggable and the element is draggable on page load.

Try it
drag me
View usage code
<div data-hcg-draggable>drag me</div>

2. Axis lock (horizontal only)

Set data-hcg-axis="x" to lock movement to one axis.

Try it
x only
View usage code
<div data-hcg-draggable data-hcg-axis="x">x only</div>

hcgDraggable("#slider", { axis: "x" });

3. Snap to 40px grid

Movement snaps to a fixed pixel step.

Try it
grid 40
View usage code
<div data-hcg-draggable data-hcg-grid="40">grid 40</div>

hcgDraggable("#box", { grid: [40, 40] });

4. Containment (stay inside the dashed area)

Use containment: "parent" to keep the element inside its container.

Try it
contained
View usage code
<div class="area">
  <div data-hcg-draggable data-hcg-containment="parent">contained</div>
</div>

hcgDraggable("#box", { containment: "parent" });

5. Drag by handle only

Only the title bar starts a drag; the body stays interactive.

Try it
:: title bar (handle)
Body is not draggable.
View usage code
hcgDraggable("#card", {
  handle: ".bar",
  onEnd: function (e) { console.log("dropped at", e.x, e.y); }
});

6. Drag threshold + cancel + click suppression

A 5px threshold lets the button click normally. cancel blocks drag starts on the button.

Try it

Drag me, or click the button.

View usage code
hcgDraggable("#clickable", {
  dragThreshold: 5,
  cancel: "button"
});

7. Bring to front on grab

Overlapping boxes rise above the others when grabbed.

Try it
box A
box B
box C
View usage code
hcgDraggable(".box", { bringToFront: true });

8. Toggle options at runtime (setOption)

Change axis or disable dragging on a live instance.

Try it
setOption

View usage code
var d = hcgDraggable("#runtime");
d.setOption("axis", "x");
d.setOption("axis", null);
d.setOption("disabled", true);

9. Containment after window resize

Contained elements are re-clamped when the window is resized.

Try it
contained
View usage code
<div id="resize-area">
  <div data-hcg-draggable data-hcg-containment="#resize-area">contained</div>
</div>

var d = hcgDraggable("#box", { containment: "#resize-area" });
d.contain();

10. Revert to start position

With revert: true, the element animates back when released.

Try it
revert me
View usage code
hcgDraggable("#revert-box", {
  revert: true
});