JSFiddle - React, Tailwind, and code Playground

by ChangJoo Park

HTML

<script src="https://unpkg.com/interact.js"></script>

<div id="app">  
  <div id="sidebar">
    <div class="item">
      <div class="component component-button draggable">
        OK
      </div>
    </div>
  </div>
  <div id="body">
    <div id="drag-1" class="draggable">
      <p> You can drag one element </p>
    </div>
    <div id="drag-2" class="draggable">
      <p> with each pointer </p>
    </div>
  </div>  
</div>

CSS

@import url('https://fonts.googleapis.com/css?family=Open+Sans');


#drag-1, #drag-2 {
  width: 100px;
  height: 100px;
  min-height: 6.5em;
  margin: 10%;

  background-color: #29e;
  color: white;

  border-radius: 0.75em;
  padding: 4%;

  -webkit-transform: translate(0px, 0px);
          transform: translate(0px, 0px);
}

#drag-me::before {
  content: "#" attr(id);
  font-weight: bold;
}

body {
  margin: 0;
}

#sidebar {
  width: 25%;
  height: 100%;
  display: inline-block;
  background-color: tomato;
}

#body {
  flex: 1;
  height: 100%;
  display: inline-block;
  background-color: #dfdfdf;
}

#app {
  display: flex;
}

.item {
  padding: 10px;
  margin: 0 auto;
}

.component {
  display: inline-block;
  font-family: Open Sans, sans-serif;
  background-color: #fff;
}

.component-button {
  padding: 20px 80px;
  border: 2px solid black;
}

JavaScript

// target elements with the "draggable" class
interact('.draggable')
  .draggable({
    // enable inertial throwing
    inertia: true,
    // keep the element within the area of it's parent
    restrict: {
      restriction: "parent",
      endOnly: true,
      elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    },
    // enable autoScroll
    autoScroll: true,

    // call this function on every dragmove event
    onmove: dragMoveListener,
    // call this function on every dragend event
    onend: function (event) {
      console.log(event)
    }
  });

  function dragMoveListener (event) {
    var target = event.target,
        // keep the dragged position in the data-x/data-y attributes
        x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
        y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

    // translate the element
    target.style.webkitTransform =
    target.style.transform =
      'translate(' + x + 'px, ' + y + 'px)';

    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
  }

  // this is used later in the resizing and gesture demos
  window.dragMoveListener = dragMoveListener;