Create a draggable element using Interact JS

Prakhar Kapoor
3 min readSep 8, 2021

--

Free and open source JS library for creating draggable, droppable,and resizable components.

Hello guys, in this article we are going to create a component having drag-n-drop feature.

First we are going to create a draggable element.

HTML:

CSS:

Next we are going to create a dropzone where the draggable element can be dropped.

HTML:

CSS:

Now comes the interesting part that how we add interactivity to the above created elements.

So, answer is pretty straightforward that we are going to add the 2 actions provided by the interact js library

  1. Draggable
  2. Dropzone

Draggable has several functions associated with them like onmove and similarly Dropzone have ondropactivate, ondragenter, ondrop,etc.

Javascript Code:

So, in the above code snippet we are first targeting the element having the class name “.item” then we are adding an action “onmove” on that targeted element.

Next, we are extracting the original position of the draggable item and since its a string so we are parsing it to float. Then we are simply finding the change in position using the event.dx and event.dy event listener.

Then

X-coordinate of new position = initialX + deltaX

Y-coordinate of new position = initialY + deltaY

At last we are using the css property “transform” to translate the (or change) the position of the element to the new position.

target.style.transform = `translate(${newX}px, ${newY}px)`;

So ,congartulations guys, we have just created our first draggable component using HTML,CSS,JS and a library called Interact JS.

Thanks ! 😉😀

CDN Link for importing the Interact JS Library:

=> https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js

--

--