Skip to content

Instantly share code, notes, and snippets.

@lordelph
Created January 17, 2017 18:52
Show Gist options
  • Save lordelph/4400148786b1fbd729d7de76f1eaf2e0 to your computer and use it in GitHub Desktop.
Save lordelph/4400148786b1fbd729d7de76f1eaf2e0 to your computer and use it in GitHub Desktop.
basic example for interact.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag Drop Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/interact.js/1.2.8/interact.min.js"></script>
<style>
#drag-1, #drag-2 {
width: 25%;
height: 100%;
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);
}
</style>
</head>
<body>
<div id="demo">
<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>
<script>
// 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,
onstart: function (event) {
console.log('onstart');
},
// call this function on every dragmove event
onmove: dragMoveListener,
// call this function on every dragend event
onend: function (event) {
console.log('onend');
var textEl = event.target.querySelector('p');
textEl && (textEl.textContent =
'moved a distance of '
+ (Math.sqrt(event.dx * event.dx +
event.dy * event.dy)|0) + 'px');
}
});
function dragMoveListener (event) {
console.log('dragMoveListener');
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 position attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment