Reputation: 247
Below is a screenshot of a list that is generated via database lookup:
As you can see, the list is merely where each player ranks at his position.
I want to be able to drag and drop each box to switch players location on the list. After following some tutorials online, I'm able to do so. See the next image below:
However, the problem that I've encountered and have not been able to resolve is that when I move players up and down the list, I need the position rank (first column) to update as well; as you can see, for example, Patrick Mahomes is origanlly #3, but when I move him to the top #1 spot, that column doesn't update.
Any help or advice? Thank you in advance. The code I have so far:
<script>
document.addEventListener('DOMContentLoaded', (event) => {
var dragSrcEl = null;
function handleDragStart(e) {
this.style.opacity = '0.4';
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'move';
return false;
}
function handleDragEnter(e) {
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over');
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
if (dragSrcEl != this) {
dragSrcEl.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData('text/html');
}
return false;
}
function handleDragEnd(e) {
this.style.opacity = '1';
items.forEach(function (item) {
item.classList.remove('over');
});
}
let items = document.querySelectorAll('.playercontainer .box');
items.forEach(function(item) {
item.addEventListener('dragstart', handleDragStart, false);
item.addEventListener('dragenter', handleDragEnter, false);
item.addEventListener('dragover', handleDragOver, false);
item.addEventListener('dragleave', handleDragLeave, false);
item.addEventListener('drop', handleDrop, false);
item.addEventListener('dragend', handleDragEnd, false);
});
});
</script>
The HTML generating the list:
<table class="table table-hover playercontainer">
<tr>
<th>Pos. Rank</th>
<th>Name</th>
<th>Position</th>
</tr>
<tbody class="row_position">
{foreach $players as $player}
<tr draggable="true" class="box">
<td id="{$player.pos_rank}"><strong>{$player.pos_rank}</strong></td>
<td><input type="text" name="name" value="{$player.player}" readonly></td>
<td>{$player.pos}</td>
</tr>
{/foreach}
</tbody>
</table>
Upvotes: 0
Views: 765
Reputation: 71
I would need to see your HTML, but:
let items = document.querySelectorAll('.playercontainer .box');
might need to change it to just
let items = document.querySelectorAll('.playercontainer');
It seems like whatever div the inner HTML for the player name's are in needs to be the only thing that can be dragged around, whereas the possible tags that the numbers are in do not need the add eventListener added to them.
Upvotes: 1