Drag & drop: Detect when the element is not released in the marked place



  • I'm working with dragon and drop, and I need to detect with JS when the element is not released in the marked zone, that is, when I drag the element but the loose and it returns to its place.

    Is it possible to do that?

    HTML + Javascript

        function allowDrop(ev){
           ev.preventDefault();
        }
    
    function drag(ev){
       ev.dataTransfer.setData("text", ev.target.id);
    }
    
    function drop(ev){
       ev.preventDefault();
    
       var element = ev.dataTransfer.getData("text");
       ev.target.appendChild(document.getElementById(element));
    }</code></pre><pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="drag1" draggable="true" ondragstart="drag(event)"&gt;&lt;/div&gt;
    

    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>



  • Sort of what you're looking for?

    var noAlvo = false;
    function allowDrop(ev){
           ev.preventDefault();
           noAlvo = true;
        }
    

    function drag(ev){
    ev.dataTransfer.setData("text", ev.target.id);
    }

    function drop(ev){
    ev.preventDefault();
    var element = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(element));
    }

    function testTarget(ev){
    ev.preventDefault();
    console.log(noAlvo);
    }

    #drag1
    {
    width: 20px;
    height: 20px;
    display: block;
    background-color: #ccc;

    }

    #div1
    {
    width:50%;
    height: 100px;
    display: block;
    background-color: green;
    position: absolute;
    left: 25%;
    top: 25%;
    }

    <div id="drag1" draggable="true" ondragstart="drag(event)" ondragend="testTarget(event)"></div>
    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2