Reputation: 811
I'm try to have 2 draggable images, and 2 destination locations, but I want image1 only to be able to be dropped in location1, and image2 only to be able to be dropped in location2, this code allows either image to be dropped in either location.
(I've left out doctype, head, body tags etc for reading simplicity)
CSS
#div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
#div2 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa;}
HTML
<script>
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="images/excercises/image1.jpg" draggable="true"
ondragstart="drag(event)" width="336" height="69">
<div id="div2" ondrop="drop(event)"
ondragover="allowDrop(event)"></div>
<img id="drag1" src="images/excercises/image2.jpg" draggable="true"
ondragstart="drag(event)" width="336" height="69">
Upvotes: 1
Views: 7036
Reputation: 2306
At first, fix your ID of the second image. (it is the same as the first img)
Then, to each of your DIVs add an attribute, whose content is the ID of image, you want to drop in
data-drop="drag1"
And set up a little condition inside a drop function
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
//allow drop only if an ID attribute of the image is the same as specified in a DIV attribute
if(ev.target.getAttribute('data-drop') == data)
ev.target.appendChild(document.getElementById(data));
}
EDIT
http://codepen.io/anon/pen/wgCkB
Upvotes: 1