Background
I am working on a sortable list, to avoid having to manually type in sorting order numbers in a database. It works via HTML5's drag'n'drop functionality, i.e. the new drag*
events in Javascript.
I currently have it working for the most part. I can click, and drag, and it'll sort itself.
Problem
From what I can tell, the drop
, along with the dragstart
and dragend
events, only are aware of the element they are going into. They can't tell if the mouse is on the top half of the dropzone, or the bottom half.
What I'd like, is when I'm hovering over the top half of a list item, for the dragged content to be placed ABOVE the item. Then if I'm hovering over the bottom half, for the dragged content to be placed BELOW the item.
Currently:
In the screencap below, I show a working (simplified) example of my code. I'm using a border-bottom
on the drop target to show that it's the target. Notice how when "Item 1" is above "Item 2", "Item 2" is lit up on the bottom, regardless of if I'm hovering over the top half or bottom half.
Code
var dragging = null;
document.addEventListener('dragstart', function(event) {
dragging = event.target;
event.dataTransfer.setData('text/html', dragging);
});
document.addEventListener('dragover', function(event) {
event.preventDefault();
});
document.addEventListener('dragenter', function(event) {
event.target.style['border-bottom'] = 'solid 4px blue';
});
document.addEventListener('dragleave', function(event) {
event.target.style['border-bottom'] = '';
});
document.addEventListener('drop', function(event) {
event.preventDefault();
event.target.style['border-bottom'] = '';
event.target.parentNode.insertBefore(dragging, event.target.nextSibling);
});
ul {
margin:0;
padding:0
}
li {
cursor:move;
display:block;
padding:20px 10px;
background:white;
border-bottom:solid 1px gray;
}
<ul>
<li draggable="true" class="sortable-bulk">List Item 1</li>
<li draggable="true" class="sortable-bulk">List Item 2</li>
<li draggable="true" class="sortable-bulk">List Item 3</li>
<li draggable="true" class="sortable-bulk">List Item 4</li>
<li draggable="true" class="sortable-bulk">List Item 5</li>
<li draggable="true" class="sortable-bulk">List Item 6</li>
<li draggable="true" class="sortable-bulk">List Item 7</li>
<li draggable="true" class="sortable-bulk">List Item 8</li>
<li draggable="true" class="sortable-bulk">List Item 9</li>
<li draggable="true" class="sortable-bulk">List Item 10</li>
</ul>
Question
Is there a way I can have it drop either above or below, not always below, depending on the mouse position while dragging?