Simple Drag and Drop • Russwurm

Simple Drag and Drop

Created: 10.11.2016 | Updated: 10.11.2016

Drag and Drop

Just need a drag and drop example to move one image over another one and fire an event and send some information back to the server. This is the simplest possible solution. It works only on Desktop because mobile devices are usually not listening to the drag events.

Working Example

This working example (on Desktops) allow to move one image over the other and give an alert about the source and destination images as well as a call to the server with the image ids.

Code

Let´s have a short look at the code. First the images are getting proper events for dragging stuff. If this is used for other elements than images it is necessary to add draggable="true" but images are automatically dragable.
<img id="img1" ondragstart="dragit(event)" ondragover="allowDrop(event)" ondrop="dropit(event)" src="https://www.russwurm.com/media/77/300x300">
<img id="img2" ondragstart="dragit(event)" ondragover="allowDrop(event)" ondrop="dropit(event)" src="https://www.russwurm.com/media/51/300x300">
<img id="img3" ondragstart="dragit(event)" ondragover="allowDrop(event)" ondrop="dropit(event)" src="https://www.russwurm.com/media/59/300x300">
And now the Javascript part to handle drag and drop:
<script>
// Disable the default behaviour of the browser to open a link on drop
function allowDrop(e) {
    e.preventDefault();
}

// Set the data to pass, in this case just the id of the object 
function dragit(e) {
    e.dataTransfer.setData("info", e.target.id);
}

// Get the transferred data (id of source element) and the id of the target element
// Show the values in alerting popup
// redirect to the server with the parameters
function dropit(e) {
    e.preventDefault();
    var from = e.dataTransfer.getData("info");
    var to = e.target.id;
    alert('from ' + from + ' to ' + to);
    window.location.href = "https://www.russwurm.com/info/simple-drag-and-drop-html5?from=" + from + "&to=" + to;
}
</script>

Links

Drag and Drop for Mobile (jQuery UI Touch Punch)






You can view this page as reduced HTML version as well.