mercredi 16 décembre 2020

Drag & Drop blocks with one class in pure JS

There is a block that can be dragged with the mouse, and the code works with id and document.getElementById. But on the site, blocks with same class will be added in unlimited quantities. How to make the data in the example blocks with one class dragged with the mouse?

   var card = document.getElementById('card');
   
    card.onmousedown = function(e) {

      var coords = getCoords(card);
      var shiftX = e.pageX - coords.left;
      var shiftY = e.pageY - coords.top;

      card.style.position = 'absolute';
      document.body.appendChild(card);
      moveAt(e);

      card.style.zIndex = 1000;

      function moveAt(e) {
        card.style.left = e.pageX - shiftX + 'px';
        card.style.top = e.pageY - shiftY + 'px';
      }

      document.onmousemove = function(e) {
        moveAt(e);
      };

      card.onmouseup = function() {
        document.onmousemove = null;
        card.onmouseup = null;
      };

    }

    card.ondragstart = function() {
      return false;
    };
body .card {
  position: relative;
  height: 12rem;
  width: 10%;
  min-width: 200px;
  box-shadow: 0 0 2rem -1rem rgba(0, 0, 0, 0.05);
  display: inline-block;
  z-index: 99999999!important;
  margin: 10%;
}

body .card .cardcontainer {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 1rem;
  background: var(--background);
  color: var(--text);
}
<div class="card center" id="card">   
  <div class="cardcontainer">  
    <textarea class="arguments"></textarea> 
  </div>
</div>
    
<div class="card center" id="card">   
  <div class="cardcontainer">  
    <textarea class="arguments"></textarea> 
  </div>
 </div>



Aucun commentaire:

Enregistrer un commentaire