-1
I’m trying to do several div
have the "drag and drop" function.
This code works in a way that you can add and remove divs
dynamically (not yet integrated into the code). The code works fine, but when it runs again (adding or removing new ones div
) he starts behaving strangely.
- They move by clicking anywhere on
div
, not only in the titleh1
as before. - It is no longer possible to write or interact with
textareas
. - All moving events go to the last
div
of the list.
(Click "Submit" to perform the "Drag and Drop" function again)
var applyDrag = () => {
Array.prototype.slice.call(document.querySelectorAll(".contentCon")).forEach(e=>{
e.querySelector("h1").onmousedown = null;
dragElement(e);
console.log(e.querySelector("h1").innerText);
});
}
applyDrag();
var moveRoom = document.querySelector(".mainCon");
function dragElement(elmnt) {
elmnt.style.background = "grey";
elmnt.style.border = "solid black 1px";
var dragEl = elmnt.querySelector("h1");
dragEl.style.cursor = "move";
console.log(dragEl.innerText);
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (moveRoom) {
moveRoom.onmousedown = dragMouseDown;
} else {
dragEl.onmousedown = dragMouseDown;
}
function dragMouseDown(e) {
console.log(dragEl);
e = e || window.event;
e.preventDefault();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
}
}
<body>
<div class="mainCon">
<div class="contentCon" id="mainCode" style="position: absolute;">
<h1>Bloco principal</h1>
<button onclick="applyDrag()">Enviar</button>
<br>
<textarea cols="10" rows="10" spellcheck="false">Clique em "Enviar" para executar a função de "Drag and Drop" novamente.</textarea>
</div>
<div class="contentCon" style="position: absolute;">
<h1>Bloco final</h1>
<br>
<textarea id="ExitLog" cols="10" rows="10" spellcheck="false" readonly style="cursor: auto; width: 300;">Meu texto.</textarea>
</div>
</div>
</body>