nuander
nuander

Reputation: 1413

Move one div into another using jQuery

This ought to be super simple. I read tons of examples and can't figure out what I'm doing wrong. I was able to do this just using JavaScript in about 20 minutes so I must be missing something obvious and I apologize if this is a stupid question. Rather than type out my test scenario I created a simple JSFiddle that should allow the user to move the words into the box. I can't get the drop function to fire. In my test environment the drop function fires but the words always end up outside the box.

http://jsfiddle.net/nuander/3htow95z/5/

Any idea what I'm doing wrong?

NOTE: well StackOverflow wants me to retype all the code here so here's the stuff that's in JSFiddle

<div id="Moveable1">Move me 1</div>
<div id="Target1" class="target"></div>

.target { width:200px; height:100px; border:1px solid #000}

$(document).ready(function () {
    $("#Moveable1").draggable();
    $("#Target1").droppable({ drop: dropItem });
});

function dropItem(ev, ui) {
    alert("dropped");
    $(this).append($(ui.draggable));
}

Upvotes: 1

Views: 575

Answers (1)

p e p
p e p

Reputation: 6674

You're oh-so-close. Here's the doc for the drop event:

Triggered when an accepted draggable is dropped on the droppable (based on the tolerance option).

The default value for the accept option is *, which means it will fire the drop event by default when any draggable is dropped into it.

The second is where you were just off: based on the tolerance option. The default value for tolerance is:

"intersect": Draggable overlaps the droppable at least 50% in both directions.

In your fiddle, your droppable has a small defined width. However, your draggable does not. This means that your draggable is the full width of the container, which is much wider than the droppable and thus can't possibly intersect by 50%.

If you switch intersect to touch instead, you'll see the event fire properly, as in that case the draggable only needs to intersect the droppable by any amount.

$(document).ready(function () {
    $("#Moveable1").draggable();
    $("#Target1").droppable({        
        tolerance: 'touch',
        drop: dropItem
    });
});

function dropItem(ev, ui) {
    alert("dropped");
    $(this).append($(ui.draggable));
}

Here's the fiddle: http://jsfiddle.net/ramrgeop/

Upvotes: 1

Related Questions