Search code examples
javascripthtmljqueryeventsdrag-and-drop

Drag and Drop using Javascript and html


I want to have a if condition. After the drop is performed if the condition is not satisfied then the dropped item should revert back to its original position. I want to do it in javascript

function allowDrop(ev) {
  ev.preventDefault();
}

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

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
  if(ev.target.id=="div2"){
  alert(data+" "+ev.target.id);
  }
  else{

  I want the revert to happen here
  }
}
<body>

<h2>Drag and Drop</h2>
<p>Drag the image back and forth between the two div elements.</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
  <img src="img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
</div>

<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="div4" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>

</body>

Can somebody please help me?Thanks in advance.


Solution

  • you have to write drop code inside your if condition so if condion is not satisfied the item will not been dropped in the div check below i have edited your code

    <h2>Drag and Drop</h2>
    <p>Drag the image back and forth between the two div elements.</p>
    
    <div id="div1" ondrop="drop(event)" style="width:200px;height:200px;background:red;" ondragover="allowDrop(event)">
    <img src="img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
    </div>
    
    <div id="div2" ondrop="drop(event)" style="width:200px;height:200px;background:blue;" ondragover="allowDrop(event)">
    </div>
    <div id="div3" ondrop="drop(event)" style="width:200px;height:200px;background:orange;" ondragover="allowDrop(event)">
    </div>
    <div id="div4" ondrop="drop(event)" style="width:200px;height:200px;background:wheat;" ondragover="allowDrop(event)">
    </div>
    <script>
    function allowDrop(ev) {
    ev.preventDefault();
    }
    
    function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
    }
    
    function drop(ev) {
    ev.preventDefault();
    
    if(ev.target.id=="div2"){
    alert(data+" "+ev.target.id);
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
    }
    
    }
    </script>
    </body>
    </html>