Skip to content
Advertisement

Drag multiple divs with javascript

I’m interested in dragging some divs by clicking in their header. I followed instructions of W3SCHOOL https://www.w3schools.com/howto/howto_js_draggable.asp and some advices founded in the web. This is my actual code:

var draggableElements = document.getElementsByClassName("one");

for(var i = 0; i < draggableElements.length; i++){
    dragElement(draggableElements[i]);
}

function dragElement(elmnt) {
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    if (document.getElementsByClassName("oneheader")) {
          document.getElementsByClassName("oneheader").onmousedown = dragMouseDown;  
    } else {
            elmnt.onmousedown = dragMouseDown;
    }
    function dragMouseDown(e) {
        e = e || window.event;
        pos3 = parseInt(e.clientX);
        pos4 = parseInt(e.clientY);
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
        return false;
    }

    function elementDrag(e) {
        e = e || window.event;
        pos1 = pos3 - parseInt(e.clientX);
        pos2 = pos4 - parseInt(e.clientY);
        pos3 = parseInt(e.clientX);
        pos4 = parseInt(e.clientY);
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    }

    function closeDragElement() {
        document.onmouseup = null;
        document.onmousemove = null;
    }
}
.one {
  width:51vw; 
  height:60vh;
  position: absolute; 
  top:20%; 
  left:20%;
  z-index: 9998;
  background-color: #e0dace;
  background-image: url('https://www.transparenttextures.com/patterns/fresh-snow.png');
  text-align: center;
  border: 1px solid #e0dac9;
  overflow:hidden;
}

.oneheader {
  padding: 5px;
  cursor: move;
  z-index: 9999;
  background-color:rgba(145,143,135,1);
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first" class="one">
  <div id="oneheader1" class="oneheader">first </div>
</div>

<div id="second" class="one">
  <div id="oneheader2" class="oneheader">second </div>
</div>

I’ve created a Jsfiddle that works with entire divs. I would like this result but only clicking in the header.

Advertisement

Answer

You can take oneheader class to apply your dragElement function and take the parent node for positioning.

    elmnt.parentNode.style.top = (elmnt.parentNode.offsetTop - pos2) + "px";
    elmnt.parentNode.style.left = (elmnt.parentNode.offsetLeft - pos1) + "px";

https://jsfiddle.net/q3Lnykao/

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement