how to disable dragend animation in html5
Asked Answered
R

2

17

I created a draggable element by setting its draggable attribute. When I drop the element, there is an animation of the element snapping back to its origin position:

snap-back animation

How can the snap-back animation be disabled? I tried calling preventDefault() on the dragend event, but it had no effect on the animation.

The following snippet shows the basics:

document.getElementById('test').addEventListener(
    'dragend', evt => {
        evt.preventDefault();
    }
);
#container {
  border: 1px solid black;
  
  min-width: 300px;
  min-height: 200px;
  position: relative;
}

#test {
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  top: 25px;
  left: 40px;
}
<div id="container">
  <div id="test" draggable='true'></div>
</div>

Not every browser will show the dragged #test jumping back to the original position.

Reservist answered 24/3, 2017 at 4:58 Comment(1)
!here is the demoReservist
C
21

In order to prevent the animation, you need the drop event to fire. For the drop event to fire, you need to call preventDefault() in the handler for dragover.

document.addEventListener('dragover', function(e) { e.preventDefault() })

Example in MDN docs shows the same thing: https://developer.mozilla.org/en-US/docs/Web/Events/drop#Example

An old blog post describing the quirks of HTML5 Drag and Drop API: https://www.quirksmode.org/blog/archives/2009/09/the_html5_drag.html

Claudetteclaudia answered 5/8, 2018 at 18:13 Comment(2)
Can you please show a working example of this?Pectin
This has to be done on any parent of the draggableBellebelleek
G
0

As was said earlier, you need to explicitly describe onDragOver handler on the parent's container (where you will drop your draggable element) and put .preventDefault() on event to prevent this animation.

Here is a simple React code example for better understanding of this mechanic (you can position the box inside the container by dragging it):

Drag and drop app example

App.jsx

import './App.css'

const App = () => {
    function handleDragOver(e) {
        e.preventDefault()
    }

    function handleDrop(e) {
        let box = document.getElementById('box')

        if (box) {
            box.style.top = e.clientY + 'px'
            box.style.left = e.clientX + 'px'
        }
    }

    return (
        <div className="container" onDragOver={handleDragOver} onDrop={handleDrop}>
            <div id="box" draggable></div>
        </div>
    )
}

export default App

App.css

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.container {
    width: 100vw;
    height: 100vh;
    position: relative;
}

#box {
    width: 100px;
    height: 100px;
    background-color: lightgreen;
    position: absolute;
}
Geraldgeralda answered 22/8, 2022 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.