Search code examples
javascripthtmlcssinteractjs

Interactjs How To Change Start Position Drag Item


my dragitem initially appears in the upper left. I want to give a space of 100 pixels from the top and left at the opening. but I have to do this with interactjs own code, not css. because if i do it with css the scroll setting is broken

interact('.dragitem')
    .draggable({
        inertia: true,
        modifiers: [
        interact.modifiers.restrictRect({
            restriction: 'parent',
            endOnly: true
        })
        ],
        autoScroll: true,
        listeners: {
            move: dragMoveListener
        }
        
    })
    function dragMoveListener (event) {
    var target = event.target
    var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
    var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
    target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
    target.setAttribute('data-x', x)
    target.setAttribute('data-y', y)
    }
    window.dragMoveListener = dragMoveListener
.drag-container {
  width:1000px;
  height:1000px;
  background:red;
}
.dragitem {
width:100px;
height:100px;
background:blue;
}
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<div class="drag-container">
  <div class="dragitem">drag me</div>
</div>


Solution

  • You have to edit the starting position in style, data-x and data-y directly in HTML

    <div class="dragitem" style="transform: translate(100px, 100px);" data-x="100" data-y="100">drag me</div>
    

    interact('.dragitem')
        .draggable({
            inertia: true,
            modifiers: [
            interact.modifiers.restrictRect({
                restriction: 'parent',
                endOnly: true
            })
            ],
            autoScroll: true,
            listeners: {
                move: dragMoveListener
            }
        })
        function dragMoveListener (event) {
          var target = event.target
    
          var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
          var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
          target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
          target.setAttribute('data-x', x)
          target.setAttribute('data-y', y)
        }
        window.dragMoveListener = dragMoveListener
    .drag-container {
      width:1000px;
      height:1000px;
      background:red;
    }
    .dragitem {
      width:100px;
      height:100px;
      background:blue;
    }
    <script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
    <div class="drag-container">
      <div class="dragitem" style="transform: translate(100px, 100px);" data-x="100" data-y="100">drag me</div>
    </div>