Reputation: 4318
I am hoping someone may help me to figure out a sticking point I am at. I have tabs that are wrapped in div's that are added dynamically so at any time I do not know how many there will be. Even so, if I was to have 3 tabs, like so:
<div class="tabs">
<div class="tab">Tab 1</div>
<div class="tab">Tab 2</div>
<div class="tab">Tab 3</div>
</div>
I am using HTML5 Drag and Drop. What I am trying to do is figure out if the current tag that I have is greater than or less than the tab that I am over so I can then drop it before or after the tab. I start to get coordinates for the getBoundingClientRect() for the element that I have, but I have not figured out how to determine whether I am greater than or less than the tab I am hovering over. For example, if I was dragging Tab 2, how would I figure out if I am past Tab 3 to drop it there after or if I dragged it before Tab 1 to drop it there.
Pretty much this gets down to being able to do some math, which I am not good at, and logic to add to my jQuery code to know where to drop the current tab I have.
Thank you for help in advance.
Upvotes: 0
Views: 48
Reputation: 2141
Here you are: I did an example, that allow drop the element with larger id before element with smaller id.
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
// get id of dragging element
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
if (data > ev.target.id) {
var parent = document.getElementsByClassName('tabs')[0]
parent.insertBefore(
document.getElementById(data), ev.target);
}
}
<div class="tabs">
<div class="tab" id="1" draggable="true" ondragstart="drag(event)" ondrop="drop(event)" ondragover="allowDrop(event)">Tab 1</div>
<div class="tab" id="2" draggable="true" ondragstart="drag(event)" ondrop="drop(event)" ondragover="allowDrop(event)">Tab 2</div>
<div class="tab" id="3" draggable="true" ondragstart="drag(event)" ondrop="drop(event)" ondragover="allowDrop(event)">Tab 3</div>
</div>
Refer here: http://www.w3schools.com/html/html5_draganddrop.asp
Hope this helps.
Upvotes: 0
Reputation: 3811
Less math based approach to finding out where you're hovering but requires you add an index to each tab (dynamically or otherwise):
<div class="tabs">
<div class="tab" data-index="0">Tab 1</div>
<div class="tab" data-index="1">Tab 2</div>
<div class="tab" data-index="2">Tab 3</div>
</div>
Find the tab you're currently hovering over:
$('.tab').hover(function () {
var index = $(this).data('index');
console.log(index);
console.log(this); // div itself
});
Upvotes: 1
Reputation: 425
And people say you don't need math to be a programmer. Hehe!
Just check the left of the dragged div against the center (left + width)/2 of the target divs. If it's less, it's left of that div. If it's higher, it's right of the div.
Upvotes: 0