1

I'm trying to create a simple feature where users can drag and drop images inbetween two divs. The issue I am having is when you drag an image on top of another image then it will end up inside that img tag.

You can see the error here: http://codepen.io/anon/pen/smgyd

What I would like to happen is that the images just sit underneath each other, even after you drag one on top of the other.

I hope I have made my issue clear. Any advice is greatly appreciated. Thank you.

Lysergix
  • 23
  • 1
  • 5

1 Answers1

0

please append your code here as well.

The script does exactly what you want:

function drop(ev)
{
    ev.preventDefault();
    var data=ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}

If you drop an image while the mouse is over an image the ev.target equals this image. You will need to find the desired drop sink of the current target.

If you could use jQuery you could use $.closest("div"); since you are on vanilla JS, here is a thread that may helps you on this task: Finding closest element without jQuery

Community
  • 1
  • 1
Nico O
  • 13,762
  • 9
  • 54
  • 69
  • Thank you very much for your answer, but if I'm honest my JS skills are horrendous. I'm just following the W3 method for drag and drop via HTML5 and JS. Would you know exactly what I have to change? Apologies for being a baby, I'd really appreciate the help. – Lysergix Feb 26 '14 at 15:11
  • you are not a baby. This not an easy task. Do you do this to learn? You could just use jQuery + jQuery - Ui for that https://jqueryui.com/droppable/ – Nico O Feb 26 '14 at 15:13
  • For my website I have a list of images in a div that I would like the user to be able to drag into another div, and then print that div. Basically they are creating a backpack of items and then printing it off. So one div is called a "Backpack" and the other "Items". I will look into that jQuery link. Thanks again for your help. – Lysergix Feb 26 '14 at 15:20
  • your attemp was really good. But jQuery is much more powerfull. Good luck. This will be a good example: https://jqueryui.com/droppable/#photo-manager – Nico O Feb 26 '14 at 15:21