JSFiddle - React, Tailwind, and code Playground
by frumbert
HTML
<script src="https://unpkg.com/plain-draggable"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/anim-event.min.js"></script>
<div class="outer">
<div class="drag">
</div>
<div class="line">
</div>
<div class="line-2">
</div>
</div>
CSS
.outer {
margin: 1rem auto;
width: 50vw;
height: 50vh;
border:1px solid indigo;
position: relative;
resize: both;
overflow: scroll;
}
.drag {
position: absolute;
top: 10%;
left: 10%;
width: 25px;
height: 25px;
background-color: blue;
}
.drag:after {
position: absolute;
top: 30px;
left: 30px;
height:1em;
width:150px;
content: attr(style);
}
.line {
position: absolute;
top: 0;
left: 60%;
bottom: 0;
width: 1px;
background-color: #999;
}
.line-2 {
position: absolute;
top: 0;
left: 75%;
bottom: 50%;
width: 1px;
background-color: #f00;
}
JavaScript
var snapped, offset;
elmLine = document.querySelectorAll(".line"),
draggable = new PlainDraggable(document.querySelector(".drag"), {
snap: Array.from(elmLine),
onMove: function(newPosition) {
if ((snapped = newPosition.snapped)) {
// how do I know the index of the elmLine to calculate here?
// which target was snapped?
offset = elmLine.getBoundingClientRect().left + pageXOffset - this.left;
}
}
});
(new MutationObserver(AnimEvent.add(function() {
if (snapped) {
draggable.left += (elmLine.getBoundingClientRect().left + pageXOffset - offset) -
(draggable.element.getBoundingClientRect().left + pageXOffset);
}
}))).observe(document.querySelector('.outer'), {
attriblutes: true,
attributeFilter: ['style']
});