CGP
CGP

Reputation:

How do I use jQuery to drag and drop a <div> at a particular position?

I am not able to drag and drop a <DIV> in a particular position.

The <DIV>'s right now get added to the bottom of the previous <DIV> even if I move the first <DIV> away from the initial position.

For example:

Lets say each <DIV> height = 50, width = 100;

When I drop the first <DIV> it is dropped at position, say (10,10)

The next <DIV> gets dropped at (10,10+50). The next one at (10,10+50+50).

I want all the <DIV>'s to drop at (10,60).

My drop function:

drop: function(ev, ui) {
    if($(ui.draggable).is("img")){
        //$(this).css("position", "absolute");
        $(this).position().left = 85;
        $(this).position().top = 338;
        //$(this).css("position", "relative");
    }

});

If I set the position to absolute. It drops it at the position specified but further drag and drop does not happen.

Can you guys offer some help. Thanks in advance.

Update: This is my html code with the three divs and the style for left div and right div. No particular style given to main div except height.

<div id="maindiv" style="height:500px">
  <div id="left">
     <img id="1" src="/1.png"/>
     </div> <!-- Left Div End -->
 <div id="content">

 </div> <!-- Content End -->
 </div> <!-- main div End-->

Content style:

content {
    border:2px solid #DFA214;
    float:right;
    height:400px;
    margin:1px;
    overflow:auto;
    position:relative;
    width:74%;
}

If I change the position to absolute then drag and drop does not work further:

left {
    border:2px solid #DFA214;
    float:left;
    height:400px;
    margin:1px;
    position:relative;
    width:24%;
}

Upvotes: 2

Views: 1868

Answers (3)

SpliFF
SpliFF

Reputation: 38956

When you move relative you still occupy the original space (even if it appears empty). You need to change the elements logical position in the DOM instead.

Actually on re-reading your question you are moving relative so you need to account for the ORIGINAL position when setting a target position.

$(this).position().left = 85 - $(this).position().left;

Or something like that.

Upvotes: 1

Rob
Rob

Reputation: 3066

Try putting all the divs you want to move in a container div. Each of the child divs should have relatve positioning. Then change parent's size.

Upvotes: 0

Julio Greff
Julio Greff

Reputation: 135

The properties top, bottom, left and right only work when position is set to fixed, absolute and relative. To set the element to a fixed position, the only way is to use absolute. Maybe the drag and drop must be changed.

Upvotes: 0

Related Questions