Create Interactive HTML Elements with Drag, Resize, Rotate – Draggable.js

Category: Drag & Drop , Javascript , Recommended | January 31, 2025
Author:MaxBittker
Views Total:159 views
Official Page:Go to website
Last Update:January 31, 2025
License:MIT

Preview:

Create Interactive HTML Elements with Drag, Resize, Rotate – Draggable.js

Description:

draggable.js is a lightweight JavaScript library that enables draggable, resizable, and rotatable functionalities for HTML elements. It works on various HTML elements, including images, and supports multi-touch gestures.

You can drag elements by clicking or touching and moving them. The resizable and rotatable functionalities, activated by a handle in the bottom right corner, provide additional control.

See it in action:

How to use it:

1. Download and load  the library’s stylesheet and script into your HTML document:

<link rel="stylesheet" href="draggable.css">
<script type="module" src="draggable.js"></script>

2. Add the draggable class to the elements you want to make interactive. Elements are automatically centered using transform: translate(-50%, -50%). The library automatically manages the z-index to bring the dragged element to the front. Touch events are handled with passive: false to prevent scrolling during dragging.

<img class="draggable" src="draggable.png">
<div class="draggable">Draggable Element</div>

3. Track drag operations with the following callback functions. Each callback receives the DOM element, its current x and y positions, the current scale factor, and the current rotation angle in radians.

setDragStartCallback((element, x, y, scale, angle) => {
  // Called when dragging starts
});
setDragMoveCallback((element, x, y, scale, angle) => {
  // Called while dragging
});
setDragEndCallback((element, x, y, scale, angle) => {
  // Called when dragging ends
});

You Might Be Interested In:


Leave a Reply