nicki
nicki

Reputation: 187

JQuery drop functionality not working as expected?

I've been trying to implement drag and drop functionality using JQuery. I've got 3 'draggable' divs and 3 'droppable' divs. Div with id 'draggable1' should be accepted by div with id 'droppable1' and so on. However, it only works for one pair of the divs(draggable1 and droppable1). It doesn't work for the other two.

I think it's somehow related to the css positioning. When I don't set the margin properties for the individual divs, it works. However, if I want to position the divs elsewhere, the functionality doesn't work anymore.

Here's a jsfiddle I've created: https://jsfiddle.net/3ews8j8x/

HTML

<center><h3>Drag and Drop</h3></center>

<div class="wrap">
<div class="draggables" id="draggable1"></div><br>
<div class="draggables" id="draggable2"></div><br>
<div class="draggables" id="draggable3"></div><br>
</div>


<div id="droppable1"></div>
<div id="droppable2"></div>
<div id="droppable3"></div>  

CSS

body{
margin: 0;
}

.wrap{
width: 400px;
height: 300px;
background: #e3e3e3;
position: relative;
margin-top: 80px;
}

.draggables{
width: 20px;
height: 20px;
margin: auto;
position: absolute;
margin-left: 30px;
}

#draggable1{
background: #003366;
position: relative;
}


#draggable2{
background: #ffff00;
position: relative;
margin-top: 90px;

}

#draggable3{
background: #ff0000;
margin-top: -150px;
margin-left: 220px;
}

#droppable1{
width: 50px;
height: 50px;
background: #0000FF;
margin-left: 600px;
margin-top: -200px;
}

#droppable2{
width: 50px;
height: 50px;
background: #008080;
margin-left: 700px;
margin-top: -50px;
}

#droppable3{
width: 50px;
height: 50px;
background: #00cc00;
margin-left: 800px;
margin-top: -50px;
}  

Javascript code is provided in the link.

I want to know why it doesn't work when I try to change the positioning of the divs. Can it not be done or am I doing something wrong? I've been stuck with this problem for over 3 days now. Any help would be appreciated.

Thank you in advance.

Upvotes: 1

Views: 38

Answers (1)

Darren Gourley
Darren Gourley

Reputation: 1808

So there were a few fundamental errors. Firstly the .draggables are set to position:relative; These need to be absolute. You were positioning these .draggables with margins, you should be positioning them with top & left:

JSFiddle

.draggables{
    width: 20px;
    height: 20px;
    position: absolute;
}

#draggable1{
    background: #003366;
}


#draggable2{
    background: #ffff00;
    top: 90px;
}

#draggable3{
    background: #ff0000;
    top: 150px;
    left: 220px;
}

Upvotes: 1

Related Questions