delete
delete

Reputation:

How can I use jQuery to snap a dropped item inside a div?

I'm trying to recreate the World of Warcraft action bar for learning purposes.

So far I have the bar, and the individual slots are Droppable. What can I do so when the yellow div is dropped inside of the container, it is centered INSIDE the .item div?

@{
    ViewBag.Title = "Home Page";
}

<script language="JavaScript">
    $(function () {
        $(".draggable").draggable();
        $(".item").droppable({
            drop: function (event, ui) {
                $(this)
                .addClass("ui-state-highlight")
                .find("p")
                    .html("Dropped!");
            }
        });
    });
</script>

<div class="draggable">
</div>
<div class="bar">
    <div class="item">
    <p>a</p>
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>
    <div class="item">
    </div>    
    <div class="item">
    </div>
    <div class="item">
    </div>
</div>

alt text

Upvotes: 7

Views: 5895

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

How about this:

$(function() {
    $(".draggable").draggable();
    $(".item").droppable({
        drop: function(event, ui) {
            var $this = $(this);
            $this.append(ui.draggable);    

            var width = $this.width();
            var height = $this.height();
            var cntrLeft = width / 2 - ui.draggable.width() / 2;
            var cntrTop = height / 2 - ui.draggable.height() / 2;

            ui.draggable.css({
                left: cntrLeft + "px",
                top: cntrTop + "px"
            });
        }
    });
});

Edit: I noticed you have some text in the target div. If you want this to work with other elements in the droppable, you can position the dragged element absolutely and offset it using the left and top of the parent:

var width = $this.width();
var height = $this.height();
var top = $this.offset().top;
var left = $this.offset().left;

var cntrLeft = (width / 2 - ui.draggable.width() / 2) + left;
var cntrTop = (height / 2 - ui.draggable.height() / 2) + top;

And:

ui.draggable.css({
    left: cntrLeft + "px",
    top: cntrTop + "px",
    zIndex:1,
    position: 'absolute'
});

Notes:

  • ui.draggable is the draggable item that was dropped on the droppable.
  • $this.append(ui.draggable) appends the dragged item to the droppable div so that positioning can be done accurately.

Check out a live example here: http://jsfiddle.net/andrewwhitaker/F3sD3/

Upvotes: 7

Related Questions