Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  75] [ 6]  / answers: 1 / hits: 6790  / 11 Years ago, tue, december 3, 2013, 12:00:00

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>

More From » html

 Answers
9

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


[#49885] Monday, December 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
;