There is probably a very simple solution to this but I just haven't been able to think it through.
I'm working an image gallery admin page. I'm using a drag and drop interface so the user can manage the order and content of their gallery.
So far the drag and drop works perfect. When I drag one image and drop it on another they swap places. Just like magic.
Being a complete noob I was pretty happy to get that far.
Here is where I've been stuck for days now. I'm trying to figure out a way to link the images to their new positions so I can submit that information to the database.
I was thinking there could be a way to get javascript to create variables named to match the columns and assign the image ID to it that occupies its position. I haven't figured out how to do that yet.
I'm open to other ideas too.
Here is my PHP:
$result = mysqli_query($con, "
SELECT *
FROM `gallery`
WHERE `order`") or die(mysqli_error());
$i = 0;
while ($row=mysqli_fetch_array($result))
{
$i++;
echo "<div id=columns>";
echo "<div class='column' id='c".$i."'><header>" . $i . "</header>";
echo "<div class='columncontent' draggable='true'><img src='../gallery/gimages/" . $row['file'] . "' width='75px' title='" .$row['name']. "' id='i" .$row['id']. "'><br>" . $row['name'] . "</div></div></div>";
}
Here is my javascript
<script type="text/javascript">
var dragSrcEl = null;
function handleDragStart(e) {
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', this.innerHTML);
e.dataTransfer.setData('text/plain', this.innerHTML);
}
var cols = document.querySelectorAll('#columns .columncontent');
[].forEach.call(cols, function(col) {
col.addEventListener('dragstart', handleDragStart, false);
});
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();
}
if (dragSrcEl != this) {
dragSrcEl.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData('text/plain');
}
return false;
}
function handleDragEnd(e) {
[].forEach.call(cols, function (col) {
col.classList.remove('over');
});
}
var cols = document.querySelectorAll('#columns .columncontent');
[].forEach.call(cols, function(col) {
col.addEventListener('dragstart', handleDragStart, false);
col.addEventListener('dragenter', handleDragEnter, false)
col.addEventListener('dragover', handleDragOver, false);
col.addEventListener('dragleave', handleDragLeave, false);
col.addEventListener('drop', handleDrop, false);
col.addEventListener('dragend', handleDragEnd, false);
});
</script>
Thanks for your help.