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

Asked

Viewed 60 times

0

I’m working with drag and drop, and accurate to detect with JS when the element is not released in the marked zone, that is, when I drag the element but release it and it returns to its place.

It is 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>
        

  • Yes, include your code in the question

  • @Leandroangelo I put the simplified code to make it easy to understand.

1 answer

1


More or less 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.