After exploring suggestions from my previous post on Stack Overflow, I have implemented a modified version to animate drag movements. While the HTML5 draggable
attribute can achieve dragging, its limitations and side effects are something I aim to avoid.
(function() {
let targets = document.querySelectorAll('.draggable');
let offsetX;
let offsetY;
Array.prototype.map.call(targets, (target) => {
target.isMouseDown = false;
target.initialOffsetLeft = target.offsetLeft;
target.initialOffsetTop = target.offsetTop;
target.addEventListener('mousedown', (e) => {
if (e.buttons === 1) {
target.style.zIndex = 10000
target.style.position = 'relative';
target.isMouseDown = true;
offsetX = target.initialOffsetLeft + e.offsetX;
offsetY = target.initialOffsetTop + e.offsetY;
}
});
document.addEventListener('mouseup', (e) => {
e.preventDefault();
target.style.zIndex = null
target.isMouseDown = false;
target.style.left = 0 + 'px';
target.style.top = 0 + 'px';
});
document.addEventListener('mousemove', (e) => {
e.preventDefault();
if (target.isMouseDown) {
target.style.left = e.pageX - offsetX + 'px';
target.style.top = e.pageY - offsetY + 'px';
}
});
});
})();
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Roboto', sans-serif
}
.draggable {
display: flex;
padding: 10px 12px;
margin-bottom: 11px;
border-radius: 5px;
margin-right: 5px;
background-color: #000000;
cursor: grab;
flex-grow:1;
color: #ffffff;
border: 1px solid #6c757d;
}
.group.card {
margin-top: 30px;
background-color: #000000;
margin-right: 2%;
margin-left: 2%;
border: 1px solid #6c757d;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22404d4d56515650435262170c100c11">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="group card">
<div class="card-body">
<div class="draggable">
Lorem ipsum dolor sit amet 1
</div>
<div class="draggable">
Lorem ipsum dolor sit amet 2
</div>
<div class="draggable">
Lorem ipsum dolor sit amet 3
</div>
</div>
</div>
As observed in the code snippet above, when any of the .draggable
elements are dragged, they shift downwards and rightwards. However, this behavior stops when either removing Bootstrap or eliminating all margins in the following:
.group.card {
/*margin-top: 30px;*/
background-color: #000000;
/*margin-right: 2%;*/
/*margin-left: 2%;*/
border: 1px solid #6c757d;
}
By making these adjustments, the drag function works correctly. What could be causing this issue and how can it be resolved?