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

0

I'm working with drag and drop , and need to detect with JS when the element is not dropped in the marked zone, ie when I drag the element but loosen it and it goes back to its place.

Is it possible to do this?

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));
    }
<div id="drag1" draggable="true" ondragstart="drag(event)"></div>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
        
    
asked by anonymous 11.01.2018 / 00:56

1 answer

1

More or less what you are 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>
    
11.01.2018 / 01:42