Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and Drop (Swap, Remove) JavaScript

I am trying to create an application to practice and understand drag and drop.

My application has a drop zone, a toolbar for the draggable items and a drop zone to delete the items.

What is not being able to do is swapping position between two item in the drop zone. When I try to change position by dragging one over the other, another drop is performed over the previous element.

Here is the code pen link to my application.

<fieldset>
  <legend>Drop Zone</legend>
  <div id="dz" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</fieldset>
</form>
<div class="card text-xs-center">
  <div class="card-block">
    <div id="textbox">
      <div id="dti1" class="form-group" draggable="true" ondragstart="drag(event)">
        <label for="ti1">Text Input</label>
        <input type="text" class="form-control" id="ti1" placeholder="text">
      </div>
      <div id="dti2" class="form-group" draggable="true" ondragstart="drag(event)">
        <label for="ti2">Password</label>
        <input type="password" class="form-control" id="ti2" placeholder="Password">
      </div>
      <div id="dti3" class="form-group" draggable="true" ondragstart="drag(event)">
        <label for="ti3">Example textarea</label>
        <textarea class="form-control" id="ti3" rows="3"></textarea>
      </div>
    </div>
  </div>
</div>
<div class="delete" ondragover="allowDrop(event)" ondrop="del(event)">Drop here to delete </div>
</div>

this image will give you an idea of what I'm saying

this image will give you an idea of what I'm saying

like image 261
Mill3r Avatar asked Jun 04 '26 18:06

Mill3r


1 Answers

To prevent the drop inside the other element, you can add a check of the id:

function allowDrop(e) {
    'use strict';
    if (e.target.id === 'dz') {
        e.preventDefault();
    }
}

This will allow drop only to the main container

like image 86
Max Koretskyi Avatar answered Jun 07 '26 08:06

Max Koretskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!