Interact JS

by Nathan Kern

HTML

<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<a href="#" id="add">Expand</a>
<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>

CSS

html, body {
    height: 100%;
}

#drag-1 {
  touch-action: none;
  width: 25%;
  height: 50px;
  min-height: 6.5em;
  margin: 0;
  position: absolute;
  right: 200px;
  background-color: #29e;
  color: white;
  border-radius: 0.75em;
  padding: 4%;
  -webkit-transform: translate(0px, 0px);
          transform: translate(0px, 0px);
  -webkit-transition-property: width, border-radius;
  -webkit-transition-duration: 0.5s, 0.5s;
  transition-property: width, border-radius;
  transition-duration: 0.5s, 0.5s;
}

 #drag-2 {
  width: 25%;
  height: 50px;
  min-height: 6.5em;
  margin: 0;
  position: absolute;
  right: 0;
  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;
}

#drag-1.active {
    width: 50%;  
    border-radius: 0;
}

JavaScript

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

    // call this function on every dragmove event
    onmove: dragMoveListener,
    // call this function on every dragend event
    onend: function (event) {
    }
  });
	let moves = 0;
  function dragMoveListener (event) {
    const {dx, dy} = event;
		if (dx > 200 || dy > 200) {
      	console.log({dx, dy});
    }
    moves++;
    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 demo
  window.dragMoveListener = dragMoveListener;

                    
$( "#add" ).click(function() {
    $("#drag-1").toggleClass("active");
});